body:
I'm working on epaper display, and writing code in Segger embedded studio for nRF52840DK.

Below is code for Driver IC IL0373 epaper display, has no response on paper display as it have driver IC SSD1680 [here][1]

Below *paper.c*

    #include "paper.h"
    #include <string.h>

    #include "nrf_gpio.h"
    #include "nrf_delay.h"
    #include "nrf_drv_spi.h"

    #define PAPER_RST_PIN 13
    #define PAPER_DC_PIN  14

    #define PAPER_SPI_INSTANCE 0
    #define PAPER_SPI_SS_PIN   29
    #define PAPER_SPI_MOSI_PIN 4
    #define PAPER_SPI_SCK_PIN  3

    #define PAPER_BYTE_WIDTH ((PAPER_PIXEL_WIDTH % 8 == 0) ? PAPER_PIXEL_WIDTH / 8 : PAPER_PIXEL_WIDTH / 8 + 1)
    #define PAPER_BYTE_HEIGHT PAPER_PIXEL_HEIGHT
    #define PAPER_BUFLEN PAPER_BYTE_WIDTH * PAPER_BYTE_HEIGHT

    #define PAPER_CMD_PWR  0x01
    #define PAPER_CMD_BTST 0x06
    #define PAPER_CMD_PON  0x04
    #define PAPER_CMD_PSR  0x00
    #define PAPER_CMD_PLL  0x30
    #define PAPER_CMD_TRES 0x61
    #define PAPER_CMD_VDCD 0x82
    #define PAPER_CMD_VCOM 0x50
    #define PAPER_CMD_LUT_VCDC 0x20
    #define PAPER_CMD_LUT_WW 0x21
    #define PAPER_CMD_LUT_BW 0x22
    #define PAPER_CMD_LUT_WB 0x23
    #define PAPER_CMD_LUT_BB 0x24
    #define PAPER_CMD_DISP 0x12

    static const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(PAPER_SPI_INSTANCE);

    static uint8_t paper_cmd_pwr[] = {
      PAPER_CMD_PWR,
      0x03, 0x00, 0x2b, 0x2b, 0x03,
    };

    static uint8_t paper_cmd_btst[] = {
      PAPER_CMD_BTST,
      0x17, 0x17, 0x17,
    };

    static uint8_t paper_cmd_pon[] = {
      PAPER_CMD_PON,
    };

    static uint8_t paper_cmd_psr[] = {
      PAPER_CMD_PSR,
      0xbf, 0x0d,
    };

    static uint8_t paper_cmd_pll[] = {
      PAPER_CMD_PLL,
      0x3a,
    };

    static uint8_t paper_cmd_tres[] = {
      PAPER_CMD_TRES,
      PAPER_PIXEL_WIDTH,
      (PAPER_PIXEL_HEIGHT >> 8) & 0xff,
      PAPER_PIXEL_HEIGHT & 0xff,
    };

    static uint8_t paper_cmd_vdcd[] = {
      PAPER_CMD_VDCD,
      0x28,
    };

    static uint8_t paper_cmd_vcom[] = {
      PAPER_CMD_VCOM,
      0x97
    };

    static uint8_t paper_cmd_lut_vcdc[] = {
      PAPER_CMD_LUT_VCDC,
      0x00, 0x08, 0x00, 0x00, 0x00, 0x02,
      0x60, 0x28, 0x28, 0x00, 0x00, 0x01,
      0x00, 0x14, 0x00, 0x00, 0x00, 0x01,
      0x00, 0x12, 0x12, 0x00, 0x00, 0x01,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00,
    };

    static uint8_t paper_cmd_lut_ww[] = {
      PAPER_CMD_LUT_WW,
      0x40, 0x08, 0x00, 0x00, 0x00, 0x02,
      0x90, 0x28, 0x28, 0x00, 0x00, 0x01,
      0x40, 0x14, 0x00, 0x00, 0x00, 0x01,
      0xA0, 0x12, 0x12, 0x00, 0x00, 0x01,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    };

    static uint8_t paper_cmd_lut_bw[] = {
      PAPER_CMD_LUT_BW,
      0x40, 0x17, 0x00, 0x00, 0x00, 0x02,
      0x90, 0x0F, 0x0F, 0x00, 0x00, 0x03,
      0x40, 0x0A, 0x01, 0x00, 0x00, 0x01,
      0xA0, 0x0E, 0x0E, 0x00, 0x00, 0x02,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    };

    static uint8_t paper_cmd_lut_wb[] = {
      PAPER_CMD_LUT_WB,
      0x80, 0x08, 0x00, 0x00, 0x00, 0x02,
      0x90, 0x28, 0x28, 0x00, 0x00, 0x01,
      0x80, 0x14, 0x00, 0x00, 0x00, 0x01,
      0x50, 0x12, 0x12, 0x00, 0x00, 0x01,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    };

    static uint8_t paper_cmd_lut_bb[] = {
      PAPER_CMD_LUT_BB,
      0x80, 0x08, 0x00, 0x00, 0x00, 0x02,
      0x90, 0x28, 0x28, 0x00, 0x00, 0x01,
      0x80, 0x14, 0x00, 0x00, 0x00, 0x01,
      0x50, 0x12, 0x12, 0x00, 0x00, 0x01,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    };

    static uint8_t paper_cmd_disp[] = {
      PAPER_CMD_DISP,
    };

    static uint8_t paper_buffer[PAPER_BUFLEN];
    static uint8_t paper_prev_buffer[PAPER_BUFLEN];

    static void paper_begin_command(void) {
      nrf_gpio_pin_clear(PAPER_DC_PIN);
    }

    static void paper_begin_data(void) {
      nrf_gpio_pin_set(PAPER_DC_PIN);
    }

    static ret_code_t paper_tx_cmd(uint8_t *cmd, uint8_t length) {
      ret_code_t ret;

      paper_begin_command();
      ret = nrf_drv_spi_transfer(&spi, cmd, 1, NULL, 0);
      if (ret != NRF_SUCCESS) return ret;

      if (length - 1 > 0) {
        paper_begin_data();
        ret = nrf_drv_spi_transfer(&spi, cmd + 1, length - 1, NULL, 0);
        if (ret != NRF_SUCCESS) return ret;
      }

      return ret;
    }

    static void paper_reset(void) {
      nrf_gpio_pin_clear(PAPER_RST_PIN);
      nrf_delay_ms(200);
      nrf_gpio_pin_set(PAPER_RST_PIN);
      nrf_delay_ms(200);
    }

    static ret_code_t paper_tx_lut(void) {
      ret_code_t ret;

      ret = paper_tx_cmd(paper_cmd_vcom, sizeof(paper_cmd_vcom));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_lut_vcdc, sizeof(paper_cmd_lut_vcdc));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_lut_ww, sizeof(paper_cmd_lut_ww));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_lut_bw, sizeof(paper_cmd_lut_bw));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_lut_wb, sizeof(paper_cmd_lut_wb));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_lut_bb, sizeof(paper_cmd_lut_bb));
      if (ret != NRF_SUCCESS) return ret;

      return ret;
    }

    static ret_code_t _paper_display(void) {
      ret_code_t ret;

      /*
       * TODO transfer chunks of 256 bytes rather than calling nrf_drv_spi_transfer
       * for each byte.
       */

      uint8_t command[1];

      command[0] = 0x10;
      ret = paper_tx_cmd(command, 1);
      if (ret != NRF_SUCCESS) return ret;

      paper_begin_data();
      for (int i = 0; i < PAPER_BUFLEN; i++) {
        ret = nrf_drv_spi_transfer(&spi, paper_prev_buffer + i, 1, NULL, 0);
        if (ret != NRF_SUCCESS) return ret;
      }

      nrf_delay_ms(10);

      /*
       * TODO i'm not yet sure about the purpose of sending the previous buffer too.
       * just sending 0x00s works pretty good. when sending the actual previous
       * image buffer, it looks like sections that have not changed become kinda
       * dirty / greyish (which could be useful because one can use three colors).
       */

      // memcpy(paper_prev_buffer, paper_buffer, PAPER_BUFLEN);

      command[0] = 0x13;
      ret = paper_tx_cmd(command, 1);
      if (ret != NRF_SUCCESS) return ret;

      paper_begin_data();
      for (int i = 0; i < PAPER_BUFLEN; i++) {
        ret = nrf_drv_spi_transfer(&spi, paper_buffer + i, 1, NULL, 0);
        if (ret != NRF_SUCCESS) return ret;
      }

      nrf_delay_ms(10);

      ret = paper_tx_lut();
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_disp, sizeof(paper_cmd_disp));
      if (ret != NRF_SUCCESS) return ret;

      nrf_delay_ms(100); // TODO use busy pin rather than arbitrary delays

      return ret;
    }

    ret_code_t paper_init(void) {
      ret_code_t ret;

      nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
      spi_config.ss_pin   = PAPER_SPI_SS_PIN;
      spi_config.mosi_pin = PAPER_SPI_MOSI_PIN;
      spi_config.sck_pin  = PAPER_SPI_SCK_PIN;

      ret = nrf_drv_spi_init(&spi, &spi_config, NULL, NULL);
      if (ret != NRF_SUCCESS) return ret;

      nrf_gpio_cfg_output(PAPER_RST_PIN);
      nrf_gpio_cfg_output(PAPER_DC_PIN);

      paper_reset();

      ret = paper_tx_cmd(paper_cmd_pwr, sizeof(paper_cmd_pwr));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_btst, sizeof(paper_cmd_btst));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_pon, sizeof(paper_cmd_pon));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_psr, sizeof(paper_cmd_psr));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_pll, sizeof(paper_cmd_pll));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_tres, sizeof(paper_cmd_tres));
      if (ret != NRF_SUCCESS) return ret;

      ret = paper_tx_cmd(paper_cmd_vdcd, sizeof(paper_cmd_vdcd));
      if (ret != NRF_SUCCESS) return ret;

      memset(paper_buffer, 0xff, PAPER_BUFLEN);
      memset(paper_prev_buffer, 0x00, PAPER_BUFLEN);

      return ret;
    }

    void paper_uninit(void) {
      // TODO uninit spi and free buffers
    }

    void paper_pixel_draw(uint16_t x, uint16_t y, uint32_t color) {
      ASSERT(x < PAPER_PIXEL_WIDTH);
      ASSERT(y < PAPER_PIXEL_HEIGHT);

      int bitn = y * PAPER_PIXEL_WIDTH + x;
      int byten = bitn / 8;
      bitn = 8 - bitn % 8 - 1;

      if (color == 0) paper_buffer[byten] |= 1UL << (bitn);
      else paper_buffer[byten] &= ~(1UL << (bitn));
    }

    void paper_rect_draw(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint32_t color) {
      ASSERT(x + width < PAPER_PIXEL_WIDTH);
      ASSERT(y + height < PAPER_PIXEL_HEIGHT);

      for (uint16_t _x = x; _x < x + width; _x++)
        for (uint16_t _y = y; _y < y + height; _y++)
          paper_pixel_draw(_x, _y, color);
    }

    void paper_display(void) {
      APP_ERROR_CHECK(_paper_display());
    }

    void paper_rotation_set(nrf_lcd_rotation_t rotation) {
      UNUSED_PARAMETER(rotation);

      // TODO
    }

    void paper_display_invert(bool invert) {
      UNUSED_PARAMETER(invert);

      // TODO
    }

The e-paper display I have are with SSD1680 IC, [here][2]

In Adafruit Library I found the following parameters

For SSD1680, [here][2]

    #define SSD1680_DRIVER_CONTROL 0x01
    #define SSD1680_GATE_VOLTAGE 0x03
    #define SSD1680_SOURCE_VOLTAGE 0x04
    #define SSD1680_PROGOTP_INITIAL 0x08
    #define SSD1680_PROGREG_INITIAL 0x09
    #define SSD1680_READREG_INITIAL 0x0A
    #define SSD1680_BOOST_SOFTSTART 0x0C
    #define SSD1680_DEEP_SLEEP 0x10
    #define SSD1680_DATA_MODE 0x11
    #define SSD1680_SW_RESET 0x12
    #define SSD1680_TEMP_CONTROL 0x18
    #define SSD1680_TEMP_WRITE 0x1A
    #define SSD1680_MASTER_ACTIVATE 0x20
    #define SSD1680_DISP_CTRL1 0x21
    #define SSD1680_DISP_CTRL2 0x22
    #define SSD1680_WRITE_RAM1 0x24
    #define SSD1680_WRITE_RAM2 0x26
    #define SSD1680_WRITE_VCOM 0x2C
    #define SSD1680_READ_OTP 0x2D
    #define SSD1680_READ_STATUS 0x2F
    #define SSD1680_WRITE_LUT 0x32
    #define SSD1680_WRITE_BORDER 0x3C
    #define SSD1680_SET_RAMXPOS 0x44
    #define SSD1680_SET_RAMYPOS 0x45
    #define SSD1680_SET_RAMXCOUNT 0x4E
    #define SSD1680_SET_RAMYCOUNT 0x4F

For IL0373, [here][3]

    #define IL0373_PANEL_SETTING 0x00
    #define IL0373_POWER_SETTING 0x01
    #define IL0373_POWER_OFF 0x02
    #define IL0373_POWER_OFF_SEQUENCE 0x03
    #define IL0373_POWER_ON 0x04
    #define IL0373_POWER_ON_MEASURE 0x05
    #define IL0373_BOOSTER_SOFT_START 0x06
    #define IL0373_DEEP_SLEEP 0x07
    #define IL0373_DTM1 0x10
    #define IL0373_DATA_STOP 0x11
    #define IL0373_DISPLAY_REFRESH 0x12
    #define IL0373_DTM2 0x13
    #define IL0373_PDTM1 0x14
    #define IL0373_PDTM2 0x15
    #define IL0373_PDRF 0x16
    #define IL0373_LUT1 0x20
    #define IL0373_LUTWW 0x21
    #define IL0373_LUTBW 0x22
    #define IL0373_LUTWB 0x23
    #define IL0373_LUTBB 0x24
    #define IL0373_PLL 0x30
    #define IL0373_CDI 0x50
    #define IL0373_RESOLUTION 0x61
    #define IL0373_VCM_DC_SETTING 0x82
    #define IL0373_PARTIAL_WINDOW 0x90
    #define IL0373_PARTIAL_ENTER 0x91
    #define IL0373_PARTIAL_EXIT 0x92

I need help with how to convert the use of IL0373 in *paper.c* to SSD1680, or is it even possible to do so?

  [1]: https://github.com/leonrinkel/nRF52-eink-epaper/tree/master/src
  [2]: https://github.com/adafruit/Adafruit_EPD/blob/master/src/drivers/Adafruit_SSD1680.h
  [3]: https://github.com/adafruit/Adafruit_EPD/blob/master/src/drivers/Adafruit_IL0373.h

title: Converting code for driver IC IL0373 to SSD1680

Answers: 0


body:
Accidentally I just short circuit my arduino nano, using a led neopixel, between the 5vOutput with one of the data pins.

Now the pc doesnt recognize the device when I connect it.
In the device (a NANOV3.0).

[![enter image description here][1]][1]
 Only the PWR(POWER/ON) led is light up, while L light doesn't. Using the multimeter VoltsDC(20), between the ground (USB) and the pin 5v it just give me 2 Volts

What may it be? How should I chek it? It is possible to fix changing a microcomponent?
Thank you

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

title: What may have happend to this arduino NANO?

Answers: 0


body:
I realized that on the atmega boards the bootloader is programmed into the chip.

I'm curious, when compiling a sketch how does the compiler/assembler differ from compiling a standard C program for a chip without a bootloader?

Is there still a main? Does the linker put the startup code in a different area? Obviously with the bootloader you're no longer compiling a program which places code at the reset address.

title: How does the compiler/assembler work wrt bootloader?

Answers: 1

body:
On the Uno and similar AVR-based boards, the compiler and assembler are
not aware of the bootloader. The compiled program starts at address
zero. There you have the interrupt vector table, starting with the reset
vector. That vector is a jump to the C runtime startup code, which does
some low-level initialization, then calls `main()` from the Arduino core
library, which calls `setup()` and `loop()` from your sketch.

The bootloader lives at the end of the flash. The AVR chip has a few
bytes of non-volatile configuration memory called “fuses”. These bytes
are configured by the Arduino board maker to dedicate the last
512 bytes of flash to the bootloader, and to start executing the
code at the start of the bootloader on power up and on reset events. It
is then the bootloader's responsibility to jump to address zero in order
to start the user's program.


body:
Is there a way to run .exe file **on a windows computer that connected to arduino**? (I want to create some sort of stream deck, but it will be used for running Google Chrome and other .exe file on a windows computer)

Can someone explain how to run it using arduino uno by taking input from the user?

title: How to use arduino to run .exe file in a windows computer

Answers: 1

body:
As mentioned in comments, one way to do this would be to bind a windows shortcut key to do the action you desire and then have the arduino send that as a keystroke.  This would only be possible on devices (like the leonardo) that have native usb device support rather than a serial to usb converter chip.

An alternate (and more secure and reliable) approach would be to create a windows service that looks for the arduino and monitors it and runs actions when the arduino generates specific events.

The easiest way to get events would be to read incoming serial data from the arduino and parse it; this would work on all arduinos.  A more complex approach (only available on arduinos with native usb device support) would be to create a special USB device profile that generated the events, and a corresponding windows service or driver to recognize and use that custom device.

I've done things like this with my own projects, although in linux, not in windows.


body:
I've been using ESP32s and ESP8266 for a few years now and I thought I'd give [these little boards](https://www.wemos.cc/en/latest/c3/c3_mini.html) a shot, they were cheaper for Bluetooth/WiFi combo, and I don't need all the bells and whistles of a full ESP32.

I have my firmware all debugged and working, it's been stable for a few months now. All it does is read a temperature from an Inkbird Bluetooth temperature sensor and log that info into a spreadsheet online for me via WiFi.

Up until this point I had the board connected via usb cable to my PC. Well I got a new PC and wanted to save a usb port so I moved it to a usb cable with an Apple AC wall adapter (5V 500mA). The board now never powers on.

Does anyone know what's happening here? It seems to not like booting unless it has a serial connection with the PC??? It doesn't like to power on if the PC is off either even though the usb port has power still.

I thought maybe this weird usb C port doesn't like 5V. So, I got it 3.3V via a breadboard power adapter rig. Nothing...

title: Wemos C3 Mini (ESP32-C3) does not run firmware unless connected to pc

Answers: 1

body: Your program could be busy, waiting for the com port to open.


body:
I'm having troubles understanding the inner workings of classes and such.

I have a class called ```Attributes``` that contains parameters. In my .ino, I can simply instantiate an object with ```Attributes greenBark(1, 2);``` and everything is hunkey dorey.

***Problem:*** Now I need to create a Attributes object in my other class, called Tree. I figured out if my constructor doesn't have parameters, I can create an object within another class just fine. However, my attributes class constructor has parameters. When I try to create an parameterized object within another class, the compiler tosses an error. **How can I create an attributes object within my tree class?** I'm sorry if I got some of these terms mixed up, I'm trying to keep up!

Here are my current files (made for this example:)

**The .ino file**

    #include "attributes.h"
    #include "tree.h"

    Attributes greenBark(1, 2);

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

    void loop()

    {
      greenBark.printAttributes();
    }

**attributes.cpp**

   #include "attributes.h"

    Attributes::Attributes(int size, int texture)

    {
      _size = size;
      _texture = texture;
    }

    void Attributes::printAttributes()
    {
      Serial.print("GreenBark Attributes: ");
      Serial.print("Size = ");
      Serial.print(_size);
      Serial.print(" Texure = ");
      Serial.print(_texture);
      Serial.println();
    }

**attributes.h**

    #pragma once
    #include <Arduino.h>

    class Attributes
    {
      public:
        Attributes(int size, int texture); // constructor
        void printAttributes(); // method

      private:
        int _size = 0;
        int _texture = 0;
    };

**tree.cpp**

    #include "attributes.h"
    #include "tree.h"

    Tree::Tree()
    {

    }

**tree.h**

    #pragma once
    #include <Arduino.h>
    #include "attributes.h"

    class Tree
    {
      public:

        Tree(); // constructor

        void makeTree(); // method

        // I want to create an attributes class object in my current class, so naturally I'd try to
        // create the object just like I did in my .ino sketch, but the below line doesn't work.

        //Attributes redBark(1, 2);

      private:
    };

The error provided is this:

    In file included from C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\ParameterizedConstructor.ino:2:0:
    C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected identifier before numeric constant
         Attributes redBark(1, 2);
                            ^
    C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected ',' or '...' before numeric constant
    In file included from C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.cpp:2:0:
    C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected identifier before numeric constant
         Attributes redBark(1, 2);
                            ^
    C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected ',' or '...' before numeric constant

    exit status 1

    Compilation error: expected identifier before numeric constant

title: Cannot instantiate a parameterized object inside of another class

Answers: 1

body:
I see two options here:

You might follow jsotola's comment and initialize `redBark` with braces:

```c++
Attributes redBark{1, 2};
```

For some reason, the syntax with parentheses is not allowed when
initializing an object in a class declaration, but the syntax with
braces is OK.

The other option is to initialize redBark in the `Tree`'s constructor
(and not in the class declaration) using an initializer list:

```c++
// In the class declaration:
Attributes redBark;

// The constructor:
Tree::Tree() : redBark(1, 2) {}
```


body:
[![this is the picture i have referd to][1]][1]

[![this is my circuit i have connected but when iam trying to get the o/p across the drain the p-mosfet is acting as a on switch and not able to turn off the circuit ][2]][2]
if my circuit has mistake please refer me the proper image.

    #define pwm 6
    void setup() {
      // initialize serial communication at 9600 bits per second:
      pinMode(6,OUTPUT);
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      //Serial.println(sensorValue);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);
      //Serial.println(voltage);
      float vol1=voltage*11;
      Serial.print("convertd voltageg ");
      Serial.println(vol1);
      int s=0;
      if (vol1>24){
      float duty=(24)/(vol1);
      Serial.print("Duty cycle ");
      duty=duty*100;
      Serial.println(duty);
       s=map(duty,0,100,0,255);
      Serial.print("maped values");
      Serial.println(s);
        analogWrite(6,s);}
      else if(vol1>18 && vol1<25){
        s=255;
        analogWrite(6,s);
        Serial.println(s);
      }
      //Serial.println(x);
    }

  [1]: https://i.stack.imgur.com/5liTu.png
  [2]: https://i.stack.imgur.com/7nn2t.png

title: why the p-mos is acting as a constant switch when the source is connect to any port in the circuit iam not able find the solution ?i

Answers: 2

body:
You have to be careful with such a circuit because you risk applying 12 volts to an arduino pin. To switch that P channel mosfet off, 12 volts has to be applied to the gate. Search for "mosfet high side switch". Usual solutions use both a P channel  mosfet and either an npn transistor or an N channel mosfet. A simpler alternative is to switch the motor using an N channel mosfet (low side switch). See https://gammon.com.au/motors for a full description.

Note: that circuit you have used appears to have come from here https://circuitjournal.com/how-to-use-a-p-channel-mosfet-with-an-arduino and is particularly risky because it relies on the grounds between the 5 volt and 12 volt circuits not being interconnected. It may work as shown, however not recommended for the reasons stated above, but your simulation does not appear to have the 12 volt power supply sharing a common positive rail with the 5 volt supply.

body: The Arduino when the output is High is ~5V referencing. The MOSFET gate sees it as -7V referencing the source. It is always best to use the source as the reference point for a MOSFET. Look at the data sheet and it shows it is doing what it is doing. The gate needs to about 0V referencing the source to be off. The exact value is dependent on the MOSFET used.You will need to add a transistor or mosfet to drive the P-Channel MOSFET with the Arduino. You could also use a opto isolator to switch the mosfet.


body:
Using M5StickC ESP32 with built-in MPU6886 accelerometer to read vibrations. In the loop() section the code gets 10 readings per second and if the readings exceed a threshold, it starts publishing the results in a JSON MQTT message on asyncmqttclient, again 10 publishes per second. The period of full publishing continues on until the readings fall back under the threshold+5 seconds.

However,when it starts publishing 10 messages per second, the accelerometer readings go haywire and the values are higher than they should be in reality. This is the results under asyncmqttclient publish:

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

The blue ellipse is just one knock. Goes up and down, and the vibration ends there. However the green ellipse part is the period where the code sends the publish messages, they should normally be down and silent like this:

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

This second graph values are from the same code, the only difference is i commented out the asyncmqttclient publish mqtt command. If i use pubsubclient it also gives the correct values.

    if (eq_status) { // Earthquake still happening
      eq_time_count++ ;

      if (((slta && !staLta.checkTrigger()) || (!slta && eq_time_count > eq_pet)) || (master && !slave_eq_state)) { // EQ Ends...
          eq_status = false;
          eq_time_count = 0;

          updateState("LISTENING");

          publish_mqtt(MQTT_PUB_EVENT, updateEvent(ax,ay,az,pga).c_str(), 0, true);

          digitalWrite(M5_LED, HIGH);
          if (SPK_HAT) ledcWriteTone(spkChannel, 0);
          lcd.set_brightness(lcd_brightness);
      } else {
        /* THIS IS THE PROBLEMATIC PART */
        publish_mqtt(MQTT_PUB_EVENT, updateEvent(ax,ay,az,pga).c_str(), 0, true);
        /*client.publish(MQTT_PUB_EVENT,updateEvent(ax,ay,az,pga).c_str());*/

      }
    } else {
        if (flush_update) { // Send periodic event update message
        flush_event++;
        if (flush_event > (flush_period*10)) {
          publish_mqtt(MQTT_PUB_EVENT, updateEvent(ax,ay,az,pga).c_str(), 0, true);
          flush_event = 0;
        }
      }
    }

I think there could be something wrong with either asyncmqttclient or espasyncTCP, or could there be any other cause?

  [1]: https://i.stack.imgur.com/f78nV.jpg
  [2]: https://i.stack.imgur.com/qSulS.jpg

title: AsyncMqttclient publish affects accelerometer readings

Answers: 0


body:
I've set up an esp32 board (wemos d1 r32) to send a request to a server hosted on my local network. If I set up a very basic go server, the board handles the response fine (200 with the appropriate body content). Once I switch to a Node JS Server, it only responds with a `400` status code. Weirdest of all none of the `console.log` calls in the route handlers get called, which indicates that it quits before it even gets to the express server. I've tested that the server returns the body & status code I want using postman, all looks good.

I've tried different frameworks (Koa) to see if this is related to Express, but it doesn't work with that either. I assume its something to do with NodeJS?

**Express server**
```
import express from "express";

const app = express();
app.use(express.json());
app.post("/", (req, res) => {
  console.log(req.body);
  req.statusCode = 200;
  res.send("200");
});

app.get("/hello", (req, res) => {
  res.setTimeout(50000);
  console.log(req.body);
  res.setHeader("Location", "123");
  res.setHeader("Server", "123");
  req.statusCode = 200;
  res.send("200");
});

app.listen(8090, () => {
  console.log(`Example app listening on port ${8090}`);
});
```

**Go server**
```
package main

import (
 "fmt"
 "net/http"
)

func hello(w http.ResponseWriter, req *http.Request) {
 for name, headers := range w.Header() {
  for _, h := range headers {
   fmt.Fprintf(w, "%v: %v\n", name, h)
  }
 }
 fmt.Fprintf(w, "hello\n")
}

func headers(w http.ResponseWriter, req *http.Request) {

 for name, headers := range req.Header {
  for _, h := range headers {
   fmt.Fprintf(w, "%v: %v\n", name, h)
  }
 }
}

func main() {
 fmt.Println("?")

 http.HandleFunc("/hello", hello)
 http.HandleFunc("/headers", headers)

 http.ListenAndServe(":8090", nil)
}
```

**Arduino script**
```
#include <HTTPClient.h>
#include <WiFi.h>

// #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include "esp_log.h"

const char* ssid = "xxx";
const char* password = "xxx";

String webserver = "http://192.168.0.19:8090/hello";

String qrCode;

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){

  WiFi.disconnect(true);
  delay(1000);
  WiFi.mode(WIFI_STA);
  delay(1000);
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
  delay(5000);
}

void setup() {
  esp_log_level_set("*", ESP_LOG_VERBOSE);
  Serial.begin(9600);
  Serial2.begin(9600);
  Serial.println("Hello, ESP32!");
  Serial.println(WiFi.getMode());
  Serial.println(WiFi.macAddress());

  WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::SYSTEM_EVENT_STA_CONNECTED);
  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP);
  WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::SYSTEM_EVENT_STA_DISCONNECTED);

  WiFi.begin(ssid, password);
}

int cnt = 0;

void loop() {
  while (Serial2.available()) {
    int  ch = Serial2.read();
    char character = ch;
    Serial.print(ch);

    // end char
    if(character == 13){
      Serial.print("\n");
      Serial.println(qrCode);
      Serial.println(cnt);
      qrCode = "";
      cnt = 0;
      send(qrCode);
    } else {
      cnt = ch + cnt;
      qrCode = qrCode + character;
    }
  }
}

void tryWifi() {
  WiFi.begin(ssid, password);
  int status = WiFi.status();
  while (status == 6 || status == 4 || status == 5 || status == 1) {
    Serial.print("Failed to connect:");
    Serial.print(status);
    Serial.print("\n");
    delay(1500);
    WiFi.begin(ssid, password);
  }
}

void send(String json) {
  HTTPClient http;

  if(http.begin(webserver)){

      int httpCode = http.GET();
      http.addHeader("Content-Type", "application/json");
      http.addHeader("Host", "something");
      // client.print("Content-Length: ");
      delay(1500);

      Serial.println(httpCode);
      Serial.println(http.getString());
      if (httpCode > 0) {
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);
        if(httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          if (payload != "false"){
            Serial.println(payload);
            delay(1500);
          } else {
          Serial.println("Bad Playload");
          }
        } else {

        }
      } else {
      Serial.println("Error sending to HTTP");
      }
      http.end();
    } else {
      Serial.println("?");
    }
}
```

title: ESP32 HTTP Request handles Go webserver response, but fails on node JS servers

Answers: 2

body:
Your Arduino code reads like this:

      int httpCode = http.GET();
      http.addHeader("Content-Type", "application/json");
      http.addHeader("Host", "something");
      // client.print("Content-Length: ");
      delay(1500);

      Serial.println(httpCode);
      Serial.println(http.getString());
      if (httpCode > 0) {

The call `http.GET()` actually performs the HTTP request. You're adding headers *after* you perform the request. They need to be added before it. So your code should read:

      // http.addHeader("Content-Type", "application/json");
      int httpCode = http.GET();

      // delay(1500);   -- there's no need to call delay() here

      Serial.println(httpCode);
      Serial.println(http.getString());
      if (httpCode > 0) {

HTTP status code 400 means "bad request". Some web servers will return this code if headers that they expect to see are missing or have non-sensical values. The Go and Javascript web servers are different implementations and may behave differently with malformed requests.

I've removed "Host" header as [`HTTPClient` does this for you][1]. And there's no need for the `delay()` call after calling `http.GET()`.

**Edit**: I also commented out the "Content-Type" header as it makes no sense on a GET request, thanks to @EdgarBonet for mentioning that. I'm leaving it there as a comment to make it clear that that any headers should be added *before* the request is performed.

  [1]: https://github.com/espressif/arduino-esp32/blob/master/libraries/HTTPClient/src/HTTPClient.cpp#L1186

body: I've figured out after an unreasonable amount of time that the request fails with a 400 as it doesn't have a slash at the end of the URL (`http://192.168.1.208:8090` -> `http://192.168.1.208:8090/`). This must be something specific to NodeJS, as it works ok on a go server.


body:
I'd like to display a sentence character by character on a single seven-segment display. What happens is that if my sentence is longer than 48 characters the central segment doesn't light up.

It works properly if I take out a letter from my string.

I have an Elegoo Uno R3, and am working on Windows, on the last version (2.0.3) of the Arduino IDE.

Is there a way to solve this issue?

Here's my code:

```
# include "SevSeg.h"

SevSeg  sevseg;
char    *str = "Per colpa di qualcuno non si fa credito a nessuno";
int     len = 50;

void setup(){
    byte numDigits = 1;
    byte digitPins[] = {};
    byte segmentPins[] = {6, 5, 2, 3, 4, 7, 8, 9};
    bool resistorsOnSegments = true;

    byte hardwareConfig = COMMON_CATHODE;
    sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
    sevseg.setBrightness(90);
}

void loop(){
  int i = 0;

  while (i < len)
  {
    sevseg.setChars(&(str[i]));
    delay(1000);
    sevseg.refreshDisplay();
    ++i;
  }
}
```
Thanx in advance,

Fab

title: strange behaviour with a single 7seg display

Answers: 1

body:
It looks like setChars is expecting a string, not a single character.

So I would be doing something like:

      while (int i = 0; i < len; i++)
      {
        char buf [2];
        buf [0] = str[i];
        buf [1] = 0;  // null terminator
        sevseg.setChars(buf);
        sevseg.refreshDisplay();
        delay(1000);
      }

See: <https://github.com/DeanIsMe/SevSeg/blob/master/SevSeg.cpp>


body:
I got MH-Z19C (CO2 ppm) ([datasheet](https://www.alldatasheet.com/datasheet-pdf/pdf/1303687/WINSEN/MH-Z19C.html)), and DHT11 (temperature) sensors from Ebay and followed instructions online to set it up with my ESP32 board ([ESP32](https://www.aliexpress.com/item/1005002611857804.html)).

I'm using a breadboard and 5V/3.3V power supply to power the sensors, while the ESP32 is linked to my PC with USB.

I'm struggling to understand the reason why I can't get a reading from my sensors. I tried countless guides online and double-checked everything multiple times.

I also tried connecting DHT11 to my board's 3.3V directly but it didn't change anything.

**How do you "debug" hardware? Is there no way to know what you're doing wrong?**
**You have to get it exactly right or nothing works?**

Serial monitor logs:
```
0 ppm
Failed to read from DHT sensor
```

MH-Z19C connections:
- VIN/GND <-> Power Supply 5V +/- respectively
- TX <-> ESP32 RX2
- RX <-> ESP32 TX2

DHT11 connections:
- Pin 1 <-> Power supply 3.3V
- Pin 2 <-> 10k Ohm pull-up <-> ESP32 D2
- Pin 4 <-> GND

Reference:
* https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide/
* https://www.electroniclinic.com/mh-z19b-ndir-co2-sensor-with-arduino-mhz19b/
* [ESP32 Pinout](https://randomnerdtutorials.com/esp32-pinout-reference-gpios/)

Libraries installed:
- [DHT sensor library by Adafruit](https://github.com/adafruit/DHT-sensor-library)
- [MH-Z19 by Jonathan Dempsey](https://github.com/WifWaf/MH-Z19)

```c++
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include "DHT.h"
#include <SoftwareSerial.h>
#include <MHZ19.h>
#include <Wire.h>

// pin for uart reading
#define RX_PIN 16  // Rx pin which the MHZ19 Tx pin is attached to.
#define TX_PIN 17 // Tx pin which the MHZ19 Rx pin is attached to.

#define DHTPIN 2     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

#define DHTTYPE DHT11   // DHT 11

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
MHZ19 myMHZ19;
SoftwareSerial mySerial(RX_PIN, TX_PIN);

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

  // Start Co2 sensor
  mySerial.begin(9600);                               // (Uno example) device to MH-Z19 serial start
  myMHZ19.begin(mySerial);                                // *Serial(Stream) refence must be passed to library begin().
  myMHZ19.autoCalibration();                              // Turn auto calibration ON (OFF autoCalibration(false))
}

void read_dht() {

  /////// DHT SENSOR \\\\\\
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("C "));
  Serial.print(f);
  Serial.print(F("F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("C "));
  Serial.print(hif);
  Serial.println(F("F"));

}

void loop() {
  // Wait a few seconds between measurements.
  delay(5000);

  int CO2;
  // Request CO2 (as ppm)
  CO2 = myMHZ19.getCO2();
  Serial.println(String(CO2) + " ppm");

  read_dht();
}

```

[![MH-Z19C from Ebay][1]][1]
[![MH-Z19C pins][2]][2]
[![DHT11 pins][3]][3]
[![dht11 wiring][4]][4]

  [1]: https://i.stack.imgur.com/g3Wr5.png
  [2]: https://i.stack.imgur.com/IgDu8.png
  [3]: https://i.stack.imgur.com/vytN1.png
  [4]: https://i.stack.imgur.com/OuM5w.jpg

title: ESP32 failing to read from DHT11, MH-Z19C sensors

Answers: 1

body:
You did a good job of giving links. You could have improved your question by showing, not just telling us, how you connected the sensors.

***How do you "debug" hardware? Is there no way to know what you're doing wrong? You have to get it exactly right or nothing works?***

No, that is too hard. I like to **divide and conquer** and **test sequentially**.

As already mentioned, test one sensor at a time.

To illustrate, I broke out an old ESP32 and a DHT22 and went about hooking them up as per your example.

Here are the connections:

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

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

Then I dowload the library that you had mentioned and I load their simplest example, DHTtester. If I am relying heavily on Arduino Libraries, I am relying on someone else's code, so I need to look through it so I am sure I am using it correctly.

Looking through the code, I make sure it specifies:

    #define DHTPIN 2     // Digital pin connected to the DHT sensor.
    #define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

and I double check that I have it connected correctly . As you can see, I have the pull-up resistor on the dataline....+3.3v to one side of the resistor and the other side goes to the DHT data pin and to the ESP GPIO2 pin (see the pics?).

I double check and then run the code and the serial monitor reveals...

    Humidity: 32.40%  Temperature: 23.40°C 74.12°F  Heat index: 22.64°C 72.75°F
    Humidity: 32.70%  Temperature: 23.30°C 73.94°F  Heat index: 22.54°C 72.57°F
    Humidity: 33.30%  Temperature: 23.30°C 73.94°F  Heat index: 22.55°C 72.60°F
    Humidity: 34.10%  Temperature: 23.30°C 73.94°F  Heat index: 22.58°C 72.64°F
    Humidity: 34.30%  Temperature: 23.30°C 73.94°F  Heat index: 22.58°C 72.65°F

...and if I breathe on the sensor, the RH jumps up....looks good.

If it had not have worked AND I was sure I had connected things correctly, I would have started going backwards....Can I get any program to work on the ESP, like a simple blink, there are lots of configuration options and it is easy to mess it up.

If I can get something to run, then I have to start to suspect the DHT - do I have another to test?...and so on and so forth.

Then I would repeat the same process with the CO2 sensor.

Then I would try to use them both at the same time.

Hope it helps.

  [1]: https://i.stack.imgur.com/21I5W.jpg
  [2]: https://i.stack.imgur.com/elbWG.jpg


body:
I have been given to understand the ATTiny88 is very similar to the Arduino Uno / ATMega328 MCU.  There does not seem to be a tag for the ATTiny88, so that is why I chose the tags I did.  I do not have a high enough reputation to create a tag, yet.  Thanks to the generous help of timemage, Edgar Bonet, and others, my MCU board is now responding, albeit very erratically, to pulses on pins 12 and 13, designated Phase_B and Phase_A, respectively, in the code below.  I have not yet entirely ruled out a hardware issue (I will do so), but a software issue is still likely.  I don't quite know what.  The MCU is registering pulses, but it very often misses large numbers of turns in either direction.  What's more, it frequently reports the wrong direction, strongly favoring a CW rotation, but sometimes reporting a CCW rotation when the knob is turned CW.  It is definitely not an overflow issue, as the anomalous effects are seen in abundance when in the mid range of the variables.

```
#include <Arduino.h>
#include <TM1637Display.h>
#include "PinChangeInterrupt.h"

volatile uint8_t counter = 0;
volatile bool Update = false;
volatile int currentStatePhase_B;
volatile int lastStatePhase_B;
volatile int pulses = 0;

// Shutdown Output
#define SW 11

// Rotary Encoder Inputs
#define Phase_A 13
#define Phase_B 12
// TM1637 I/O ports
#define DIO 3
#define CLK 4
TM1637Display display(CLK, DIO);

void setup() {

  // Set encoder pins as inputs
  pinMode(Phase_A,INPUT);
  pinMode(Phase_B,INPUT);
  pinMode(SW, OUTPUT);

 // Read the initial state of Phase_B
 lastStatePhase_B = digitalRead(Phase_B);

 // Call updateEncoder() when any high/low changed seen
 // on interrupt 0 (pin 2), or interrupt 1 (pin 3)
 attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, RISING);
 attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, RISING);

  display.setBrightness(0x0f);
  display.clear();
  display.showNumberDec(0, false);
}

void loop() {
 if (Update){
  // Show decimal numbers with/without leading zeros
    display.showNumberDec(pulses, false);
    delay(1000);
    display.showNumberDec(counter, false);
  Update = false;
 }
}

void updateEncoder(){
 // Read the current state of Phase_B
 currentStatePhase_B = digitalRead(Phase_B);

 // If last and current state of Phase_B are different, then pulse occurred
 // React to only 1 state change to avoid double count
 if (currentStatePhase_B != lastStatePhase_B  && currentStatePhase_B == 1){
    // If the Phase_A state is different than the Phase_B state then
  // the encoder is rotating CCW so decrement
  if (digitalRead(Phase_A) != currentStatePhase_B) {
   counter --;
  } else {
   // Encoder is rotating CW so increment
   counter ++;
  }
 }
    if (counter > 1023){
      counter = 1023;
    }
    if (counter < 0){
      counter = 0;
    }
    pulses ++;
 // Remember last Phase_B state
 lastStatePhase_B = currentStatePhase_B;
 Update = true;
}

```

title: ATTiny88 missing pulses - maybe

Answers: 1

body:
OK, I have an answer.  The MCU is still missing a lot of pulses, but I am fairly certain this is a hardware issue, or at least mostly so.  I found some code by Ralph S. Bacon and Marko Pinteric.  The YouTube video can be found [here][1]

  [1]: https://www.youtube.com/watch?v=sQNPAsZKnDw

As should always be the case, the ISR is brief.  Here it is a single line that merely sets a Boolean variable true.  In the loop section, the code repeatedly checks to see if the interrupt has occurred.  The checkRotaryEncoder function then verifies the pin values to make sure the encoder is in a valid state (not bouncing).  If so, then the counter value is updated with the result.

```
#include <Arduino.h>
#include <TM1637Display.h>
#include "PinChangeInterrupt.h"

uint8_t lrmem = 3;
int lrsum = 0;
int num = 0;
unsigned int counter = 0;

// Shutdown Output
#define SW 11
// Rotary Encoder Inputs
#define Phase_A 12
#define Phase_B 13
// TM1637 Display I/O
#define DIO 3
#define CLK 4
TM1637Display display(CLK, DIO);

// A turn counter for the rotary encoder (negative = anti-clockwise)
int rotationCounter = 200;
// Flag from interrupt routine (moved=true)
volatile bool rotaryEncoder = false;

// Rotary encoder has moved (interrupt tells us) but what happened?
// See https://www.pinteric.com/rotary.html
int8_t checkRotaryEncoder()
{
    // Reset the flag that brought us here (from ISR)
    rotaryEncoder = false;

    static uint8_t lrmem = 3;
    static int lrsum = 0;
    static int8_t TRANS[] = {0, -1, 1, 14, 1, 0, 14, -1, -1, 14, 0, 1, 14, 1, -1, 0};

    // Read BOTH pin states to deterimine validity of rotation (ie not just switch bounce)
    int8_t l = digitalRead(Phase_A);
    int8_t r = digitalRead(Phase_B);

    // Move previous value 2 bits to the left and add in our new values
    lrmem = ((lrmem & 0x03) << 2) + 2 * l + r;
    // Convert the bit pattern to a movement indicator (14 = impossible, ie switch bounce)
    lrsum += TRANS[lrmem];
    /* encoder not in the neutral (detent) state */
    if (lrsum % 4 != 0)
    {
        return 0;
    }
    /* encoder in the neutral state - clockwise rotation*/
    if (lrsum == 4)
    {
        lrsum = 0;
        return 1;
    }
    /* encoder in the neutral state - anti-clockwise rotation*/
    if (lrsum == -4)
    {
        lrsum = 0;
        return -1;
    }
    // An impossible rotation has been detected - ignore the movement
    lrsum = 0;
    return 0;
}

void setup() {
  // Set encoder pins as inputs
  pinMode(Phase_A,INPUT);
  pinMode(Phase_B,INPUT);
  // Set Power Switch as output
  pinMode(SW, OUTPUT);
  // Initialize display
  display.setBrightness(0x0f);
  display.clear();
  display.showNumberDec(0, false);
  // Set up interrupt pins and vector
  attachPCINT(digitalPinToPCINT(Phase_A), rotary, CHANGE);
  attachPCINT(digitalPinToPCINT(Phase_B), rotary, CHANGE);
}

void loop()
{
  // Has rotary encoder moved?
  if (rotaryEncoder) {
    // Get the movement (if valid)
    int8_t rotationValue = checkRotaryEncoder();
    // If valid movement, do something
    if (rotationValue != 0) {
      counter += rotationValue;
      if (counter > 1023){
        counter = 1023;
      }
      else if (counter < 0){
        counter = 0;
      }
      display.showNumberDec(counter, false);
    }
  }
}

// Interrupt routine just sets a flag when rotation is detected
void rotary()
{
    rotaryEncoder = true;
}
```
Any comments are welcom.  In addition, Ralph Bacon used the IRAM_ATTR directive to create the rotary() ISR.  My understanding of this directive is it is not necessary in most cases.  On the other hand, presumably the code will execute faster if it is pushed into flash RAM.  I could not make this work.  The compiler complains, "expected initializer before 'rotary'"  Is this by chance because the ATTiny88 does not have flash RAM?  If not, then what?


body:
I am using a DS1302 RTC module with an Arduino Mega 2560 Rev 3. I follow steps on this [website][1] since I have no experience with RTC module before. Here are the outputs I am getting.

```
17:15:21.835 -> Current Date / Time: 26/2/2023 17:15:44
17:15:26.830 -> Current Date / Time: 26/2/2023 17:16:13
17:15:31.856 -> Current Date / Time: 26/2/2023 17:16:42
17:15:36.853 -> Current Date / Time: 26/2/2023 17:17:11
```

As you can see from the above output, the DS1302 is running five times faster than the real time (output past 30 seconds as real word past 5 seconds). Same thing happened if use different codes with different libraries.

Does this mean the RTC module itself is broken, or I can modify RTC module's speed with code?

  [1]: https://surtrtech.com/2018/01/27/how-to-simply-use-ds1302-rtc-module-with-arduino-board-and-lcd-screen/

```c++
//This code is to use with DS1302 RTC module, it permits you to setup the actual time and date
//And you can visualize them on the serial monitor
//This code is a modified version of the code provided in virtuabotixRTC library
//Refer to https://Surtrtech.com for more information

#include <virtuabotixRTC.h> //Library used

//Wiring SCLK -> 6, I/O -> 7, CE -> 8
//Or CLK -> 6 , DAT -> 7, Reset -> 8

virtuabotixRTC myRTC(6, 7, 8); //If you change the wiring change the pins here also

void setup() {
  Serial.begin(9600);
  // Set the current date, and time in the following format:
  // seconds, minutes, hours, day of the week, day of the month, month, year
  myRTC.setDS1302Time(15, 15, 17, 7, 26, 2, 2023); //Here you write your actual time/date as shown above
  //but remember to "comment/remove" this function once you're done
  //The setup is done only one time and the module will continue counting it automatically
}

void loop() {
  // This allows for the update of variables for time or accessing the individual elements.
  myRTC.updateTime();

  // Start printing elements as individuals
  Serial.print("Current Date / Time: ");
  Serial.print(myRTC.dayofmonth); //You can switch between day and month if you're using American system
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print(" ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);

  // Delay so the program doesn't print non-stop
  delay(5000);
}
```

title: DS1302 RTC module running too fast

Answers: 1

body:
I stumbled over the exact same issue today (using Arduino Uno/atmega328) and a module/board like this:
https://surtrtech.com/2018/01/27/how-to-simply-use-ds1302-rtc-module-with-arduino-board-and-lcd-screen/
When reading out time after setting it, it runs 5-6 times too fast.

I found some hint here regarding precision:
https://forum.arduino.cc/t/ds1302-drift/327796/7

However, they were talking about a 2 minutes of drift every 24 hours which for sure is a totally different thing.
One comment there was to pay special attention to the ground as noise there might be interpreted as additional clock signals and speed up the clock. So I played with the grounds on the board and disconnected everything else connected so far to pins of the Arduino board, but that did not change anything, still 5-6 times faster.

I also played with and without CR2032 battery and 5V and 3.3V input to the clock board's VCC input pin and ...suddenly... it worked ok.
I think with 3.3V input on VCC and no battery, it initially had the "normal" precision but now I can again connect it to 5V input and it still runs normal...
I also kept it a while disconnected from external power source (only running on battery), then connecting it back to the Laptop and reading out date/time values and still it worked ok.

It is totally weird.

Regards, Dan


body:
After several tries, i was successful with reading stable battery voltage using internal voltage reference of 1.1v, now the issue i face is that i cannot read stable sensor voltage, could you please let me know how can i read my sensor voltage? or do i need additional voltage divider (my sensor goes directly to A0 and GND pin).

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

    void loop() {
      //REFS1 AND REFS0 to 1 1 -> internal 1.1V refference
      ADMUX |= B11000000;
      //We read A1 (MUX0) for battery voltage
      ADMUX |= B00000001;
        //We read A0 for sensor voltage
      ADMUX |= B00000000;                // for my sensor
      // Start AD conversion
      ADCSRA |= B11000000;
      // Detect end-of-conversion
      while (bit_is_set(ADCSRA,ADSC));
      float val = ADCL | (ADCH << 8);
      val = val * 5.7; // Using 4.7k and 1k voltage divider
      Serial.println(val);
    }

Something like the code below must workout but unfortunately it does not help!

      int sensorValue = analogRead(A0);
      voltage =  ((sensorValue/ val) * 1023.);
      delay(1000);
      Serial.println("voltage:  ");
      Serial.print(voltage);
      if (voltage<=215){
      digitalWrite (led, HIGH);
      }
      else if (voltage>=215){
      digitalWrite (led, LOW);
      }

I cannot find the issue, it should work, i believe.

//////////////////////new edit/////////////////////////////////////

    const long internalReference = 1078L; //measured AREF to be 1.078 ~ 1.078*1000= 1078V

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

    void loop() {
     analogReference (INTERNAL);
     ADMUX |= B00000000;
     ADCSRA |= B11000000;    //ADEN and ADSC equal to 1   (Start conversion)
      while(bit_is_set(ADCSRA, ADSC));    //Wait for conversion to end
      long val = ADCL | (ADCH << 8);   //Get analog read value
      float voltage = (val/internalReference)*1024;
     Serial.println (voltage);

     }

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

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

title: Using 1.1Vf to read stable battery voltage and sensor voltage

Answers: 1

body:
To measure the voltage at A0 with an internal reference of 1.1v, the formula is `float voltage = 1.1 * analogRed(A0) / 1023;`. Your code can be simplified as

```
float Vref = 1.1;

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

void loop() {
  analogReference (INTERNAL);
  float voltage = Vref * analogRead(A0) / 1023;
  Serial.print (“voltage at A0:”);
  Serial.println(voltage);
  Serial.print (“Solar panel voltage:”);
  Serial.println(voltage * 5.7);
  delay(1000);
}


body:
I am using ESP32-S3-WROOM-1-N8 module https://www.digikey.de/de/products/detail/espressif-systems/ESP32-S3-WROOM-1-N8/15200089 .
I have compared pinout of all Wroom modules ESP32 ESP32-S3 as well as ESP32-WROVER have all the programming pins in exactly same positions so I was expecting this programmer to work for any of these modules. I am looking at GND, 3v3, EN, RX, TX, GPIO0.

I am using this flexy pin board from aliexpress https://de.aliexpress.com/item/1005004605613498.html?spm=a2g0o.order_list.order_list_main.91.21ef5c5f6R74vM&gatewayAdapt=glo2deu

When Uploading sketch I am getting following error:

```
StopIteration
[6848] Failed to execute script 'esptool' due to unhandled exception!

Chip is ESP32-S3
Features: WiFi, BLE
Crystal is 40MHz
MAC: 7c:df:a1:ec:d1:f0
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Configuring flash size...
Failed uploading: uploading error: exit status 1
```
[![enter image description here][1]][1]

Looks like it failed while configuring flash memory, I have gone through esptool's codebase on Github it seems to fail at this function https://github.com/espressif/esptool/blob/master/esptool/loader.py#L1167
I am not experienced with all this so can't figure out what is the issue.
On board config, I have set

```
Flash mode: QIO 80MHz
Flash size: 8MB
```
I have selected `ESP32S3 Dev Module` as the board
ESP32 Library `v2.0.6`

Update: When I opened the serial monitor, it is showing following

```
ESP-ROM:esp32s3-20210327
Build:Mar 27 2021
rst:0x7 (TG0WDT_SYS_RST),boot:0x8 (SPI_FAST_FLASH_BOOT)
Saved PC:0x40049b21
invalid header: 0xa5ff005a
```

Am I wrong in assuming all these modules can be programmed with this programmer?

Thanks in advance

Update 2:
Changing upload speed from 921600 to 115200 fixed it, but the module still errored when running it.
Serial monitor shows following:
```
ESP-ROM:esp32s3-20210327
Build:Mar 27 2021
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3fce3808,len:0x44c
load:0x403c9700,len:0xbec
load:0x403cc700,len:0x2920
entry 0x403c98d8
[    81][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): XTAL: 40 / 1 = 40 Mhz, APB: 80000000 Hz
E (491) psram: PSRAM ID read error: 0x00ffffff
[    83][W][esp32-hal-psram.c:71] psramInit(): PSRAM init failed!
[   120][D][esp32-hal-rmt.c:615] rmtInit():  -- TX RMT - CH 0 - 1 RAM Blocks - pin 48
```
Which went away after I disabled PSRAM in upload setting.
Now I seem to be able to program and run it but the serial monitor is only showing debug messages, the message I am trying to print to serial is not showing up.
Also blink sketch is also not working for BUILTIN_LED as well as GPIO1

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

title: Programming ESP32-S3 WROOM with a flexy pin board

Answers: 0


body:
I am building a CircuitPython weather station based on Adafruit M4 board stacked with Adafruit ESP32 AirLift module. Both work fine together when it comes to making http calls (via Adafruit_requests library). However I would like to build a HTTP server serving weather measures instead.
And here is a problem: all Adafuit examples are based on ESP32 or Raspberry Pico boards natively fitted with WIFI. Adafuit M4 board doesn't have the same core python packages since it doesn't sport WIFI.
So example written for Pico doesn't work on M4 with ESP AirLift, there are a number of packages missing to do so (like wifi and socket), adafuit_esp package has to be used instead.
This package however seems to be incompatible with Adafuit HTTPServer:
https://docs.circuitpython.org/projects/httpserver/en/stable/index.html
HttpServer requires socket object as a parameter to be initialized:

    esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
    socket.set_interface(esp)
    server = HTTPServer(socket)

this code fails when I'm trying to start the server:

    try:
        server.start(esp.pretty_ip(esp.ip_address))
        print("Listening on http://%s:80" % esp.pretty_ip(esp.ip_address))
    #  if the server fails to begin, restart the pico w
    except OSError:
        time.sleep(5)
        print("restarting..")
        microcontroller.reset()

and the error is:

    >>> %Run -c $EDITOR_CONTENT
    Creating display
    Creating server socket
    ESP32 found and in idle mode
    Firmware vers. bytearray(b'1.2.2\x00')
    MAC addr: ...
    ...
    Connecting to AP...
    Connected to jama  RSSI: -27
    My IP address is 192.168.0.24
    Creating HTTP Server...
    starting server..
    Traceback (most recent call last):
      File "<stdin>", line 175, in <module>
      File "adafruit_httpserver/server.py", line 91, in start
    AttributeError: 'socket' object has no attribute 'bind'
    >>>

So it looks like that's not the right socket ?
it works for ESP and Requests libs but not for HTTPServer.

Here are imports:

    from adafruit_esp32spi import adafruit_esp32spi
    import adafruit_esp32spi.adafruit_esp32spi_socket as socket

My question then (or two) is if anyone know a workaround for this issue
and/or a different socket or server packages I can use instead ?

Here is the full code for the reference, it is not finished and contains more stuff that described here but unrelated to the issue:

    import os
    import time
    import busio
    import board
    import microcontroller
    from digitalio import DigitalInOut, Direction
    import adafruit_bh1750
    # import adafruit_requests as requests
    from adafruit_bme280 import basic as adafruit_bme280
    from adafruit_httpserver.server import HTTPServer
    from adafruit_httpserver.request import HTTPRequest
    from adafruit_httpserver.response import HTTPResponse
    from adafruit_httpserver.methods import HTTPMethod
    from adafruit_httpserver.mime_type import MIMEType
    from adafruit_epd.epd import Adafruit_EPD
    from adafruit_epd.il0373 import Adafruit_IL0373
    from adafruit_esp32spi import adafruit_esp32spi
    import adafruit_esp32spi.adafruit_esp32spi_socket as socket

    try:
        from secrets import secrets
    except ImportError:
        print("WiFi secrets are kept in secrets.py, please add them there!")
        raise

    #  onboard LED setup
    # led = DigitalInOut(board.LED)
    # led.direction = Direction.OUTPUT
    # led.value = False

    i2c = board.I2C()  # uses board.SCL and board.SDA
    bh1750 = adafruit_bh1750.BH1750(i2c)
    bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, 0x76)
    bme280.sea_level_pressure = 1012.50

    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    ecs = DigitalInOut(board.D9)
    dc = DigitalInOut(board.D10)
    srcs = DigitalInOut(board.D6)  # can be None to use internal memory
    rst = None #DigitalInOut(board.D1)  # can be None to not use this pin
    busy = None #DigitalInOut(board.D5)  # can be None to not use this pin

    esp32_cs = DigitalInOut(board.D13)
    esp32_ready = DigitalInOut(board.D11)
    esp32_reset = DigitalInOut(board.D12)

    print("Creating display")
    display = Adafruit_IL0373(
        128,
        296,  # 2.9" Tri-color display
        spi,
        cs_pin=ecs,
        dc_pin=dc,
        sramcs_pin=srcs,
        rst_pin=rst,
        busy_pin=busy,
    )

    display.set_black_buffer(1, True)
    display.set_color_buffer(1, True)
    display.rotation = 1
    display.fill(Adafruit_EPD.WHITE)
    # display.display()
    # display.text(splash, 12, 12, Adafruit_EPD.BLACK, size=1)

    #  connect to network
    print("Creating server socket")
    esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
    socket.set_interface(esp)

    if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
        print("ESP32 found and in idle mode")
    print("Firmware vers.", esp.firmware_version)
    print("MAC addr:", [hex(i) for i in esp.MAC_address])

    for ap in esp.scan_networks():
        print("\t%s\t\tRSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"]))

    print("Connecting to AP...")
    while not esp.is_connected:
        try:
            esp.connect_AP(secrets["ssid"], secrets["password"])
        except OSError as e:
            print("could not connect to AP, retrying: ", e)
            continue
    print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
    print("My IP address is", esp.pretty_ip(esp.ip_address))

    print("Creating HTTP Server...")
    server = HTTPServer(socket)

    #  font for HTML
    font_family = "monospace"

    #  the HTML script
    #  setup as an f string
    #  this way, can insert string variables from code.py directly
    #  of note, use {{ and }} if something from html *actually* needs to be in brackets
    #  i.e. CSS style formatting
    def webpage():
        html = f"""
        <!DOCTYPE html>

        <meta http-equiv="Content-type" content="text/html;charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Pico W HTTP Server</title>

Pico W HTTP Server

This is a Pico W running an HTTP server with CircuitPython.

The current ambient temperature near the Pico W is
        {temp_test}°{unit}

Control the LED on the Pico W with these buttons:

        <form accept-charset="utf-8" method="POST">
        <button class="button" name="LED ON" value="ON" type="submit">LED ON</button>
</form>

<form accept-charset="utf-8" method="POST">
        <button class="button" name="LED OFF" value="OFF" type="submit">LED OFF</button>
</form>

Party?</h>

<form accept-charset="utf-8" method="POST">
        <button class="button" name="party" value="party" type="submit">PARTY!</button>
</form>

        """
        return html

    #  route default static IP
    @server.route("/")
    def base(request: HTTPRequest):  # pylint: disable=unused-argument
        #  serve the HTML f string
        #  with content type text/html
        with HTTPResponse(request, content_type=MIMEType.TYPE_HTML) as response:
            response.send(f"{webpage()}")

    #  if a button is pressed on the site
    @server.route("/", method=HTTPMethod.POST)
    def buttonpress(request: HTTPRequest):
        #  get the raw text
        raw_text = request.raw_request.decode("utf8")
        print(raw_text)
        #  if the led on button was pressed
        if "ON" in raw_text:
            #  turn on the onboard LED
            led.value = True
        #  if the led off button was pressed
        if "OFF" in raw_text:
            #  turn the onboard LED off
            led.value = False

        #  reload site
        with HTTPResponse(request, content_type=MIMEType.TYPE_HTML) as response:
            response.send(f"{webpage()}")

    print("starting server..")
    # startup the server
    try:
        server.start(esp.pretty_ip(esp.ip_address))
        print("Listening on http://%s:80" % esp.pretty_ip(esp.ip_address))
    #  if the server fails to begin, restart the pico w
    except OSError:
        time.sleep(5)
        print("restarting..")
        microcontroller.reset()

    #  text objects for screen
    #  connected to SSID text
    connect_text_area.text = "Connected to:"
    ssid_text = "%s" % secrets('ssid')
    # ssid_text_area = label.Label(terminalio.FONT, text=ssid_text, color=0xFFFFFF, x=0, y=offset_y+15)
    #splash.append(ssid_text_area)
    #  display ip address
    ip_text = "IP: %s" % wifi.radio.ipv4_address
    # ip_text_area = label.Label(terminalio.FONT, text=ip_text, color=0xFFFFFF, x=0, y=offset_y+30)
    #splash.append(ip_text_area)
    #  display temp reading
    temp_text = "Temperature: %.02f F" % float(temp_test)
    # temp_text_area = label.Label(terminalio.FONT, text=temp_text, color=0xFFFFFF, x=0, y=offset_y+45)
    #splash.append(temp_text_area)

    def get_weather_conditions():
        temp = bme280.temperature
        print("\nTemperature: %0.1f C" % temp)
        hum = bme280.relative_humidity
        print("Humidity: %0.1f %%" % hum)
        pres = bme280.pressure
        print("Pressure: %0.1f hPa" % pres)
        alt = bme280.altitude
        print("Altitude: %0.2f meters" % alt)
        light = bh1750.lux
        print("Light: %.2f Lux" % light)
        return [temp, hum, pres, alt, light]

    clock = time.monotonic() #  time.monotonic() holder for server ping

    while True:
        try:
            #  every 30 seconds, ping server & update temp reading
            if (clock + 30) < time.monotonic():
                if wifi.radio.ping(ping_address) is None:
                    connect_text_area.text = "Disconnected!"
                    ssid_text_area.text = None
                    print("lost connection")
                else:
                    connect_text_area.text = "Connected to:"
                    ssid_text_area.text = "%s" % secrets('ssid')
                    print("connected")
                clock = time.monotonic()
                #  comment/uncomment for desired units
                #  temp_test = str(ds18.temperature)
                temp_test = str(c_to_f(19.45))
                temp_text_area.text = "Temperature: %s F" % temp_test

    #         display.show(splash)
            #  poll the server for incoming/outgoing requests
            server.poll()
        # pylint: disable=broad-except
        except Exception as e:
            print(e)
            continue

title: CircuitPython - how to connect Adafruit esp32 AirLift with Adafuit HttpServer - incompatible socket object

Answers: 1

body:
Official answer from Adafuit for this question is that HTTPServer lib is created for Raspeberry PICO and do not work on other boards like Feather M4 express indeed. Different set of libraries needs to be used instead, here is the relevant example:
https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/tree/main/examples/server


body:
I have been trying to run stepper motor via Arduino Uno and A4988 motor driver via this tutorial: https://howtomechatronics.com/tutorials/arduino/how-to-control-stepper-motor-with-a4988-driver-and-arduino/
The schematic for my wiring:[![schematic][1]][1]

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

So far I have checked the connections multiple times, tried different Arduino boards and A4988 drivers, even tried using a DRV8825 driver, manually declaring HIGH for SLEEP and RESET pins and LOW for ENABLE via arduino. Checked with several batteries which show no problem, even had a friend check the motors via other different driver(YS-DIV268n) he had and the motors worked fine.
I even tried increasing the current from driver via the potentiometer on it but none of these worked.

All this time I observed that the driver got hot quite a lot and that's it.
The arduino code is as follows:
```/*     Simple Stepper Motor Control Exaple Code
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 */

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

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

  digitalWrite(dirPin,LOW); //Changes the rotations direction
  // Makes 400 pulses for making two full cycle rotation
  for(int x = 0; x < 400; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000);
}```

title: Stepper motor not working with A4988 driver

Answers: 0


body:
I have made a USB game controller using the Arduino Micro and Omron microswitches (VX-01-1A3) for the buttons. The switch is wired with one end connected to a digital pin and the other end connected to GND. However, I am experiencing issues such as double-clicking, poor contact, and disconnection while using the microswitch. I have tried implementing debounce code, replacing the switch and cables, but the problem persists and often returns after only a few weeks of normal operation.

In the [datasheet for the Omron VX series][1],  I came across a diagram:

[![Operating range of VX][2]][2]

which prompted me to measure the current through the switch when pressed, which was only about 0.3mA. Since the digital pin voltage of the Arduino Micro is 5V, this state is not within the normal operating range shown in the diagram.

Could this be the reason for the poor contact of my microswitch?
If so, how can I increase the current through the switch to bring it within the normal operating range? Would adjusting the pull-up resistor (using an external pull-up resistor instead of the Arduino's built-in pull-up resistor) be a feasible solution?

Thank you for your help.

  [1]: https://omronfs.omron.com/en_US/ecb/products/pdf/en-vx.pdf
  [2]: https://i.stack.imgur.com/MIXgm.jpg

title: Poor Contact and Low Current Issues with Microswitches in Arduino USB Game Controller

Answers: 0


body:
# Error messages

```
    Arduino: 1.8.14 Hourly Build 2020/12/15 11:33 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:62:18: error: 'HTTP_GET' conflicts with a previous declaration

       62 |   HTTP_GET     = 0b00000001,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:29: note: previous declaration 'HTTPMethod HTTP_GET'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                             ^~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:63:18: error: 'HTTP_POST' conflicts with a previous declaration

       63 |   HTTP_POST    = 0b00000010,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:50: note: previous declaration 'HTTPMethod HTTP_POST'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                  ^~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:64:18: error: 'HTTP_DELETE' conflicts with a previous declaration

       64 |   HTTP_DELETE  = 0b00000100,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:83: note: previous declaration 'HTTPMethod HTTP_DELETE'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                                                ^~~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:65:18: error: 'HTTP_PUT' conflicts with a previous declaration

       65 |   HTTP_PUT     = 0b00001000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:61: note: previous declaration 'HTTPMethod HTTP_PUT'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                             ^~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:66:18: error: 'HTTP_PATCH' conflicts with a previous declaration

       66 |   HTTP_PATCH   = 0b00010000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:71: note: previous declaration 'HTTPMethod HTTP_PATCH'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                                       ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:67:18: error: 'HTTP_HEAD' conflicts with a previous declaration

       67 |   HTTP_HEAD    = 0b00100000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:39: note: previous declaration 'HTTPMethod HTTP_HEAD'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                       ^~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:68:18: error: 'HTTP_OPTIONS' conflicts with a previous declaration

       68 |   HTTP_OPTIONS = 0b01000000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:96: note: previous declaration 'HTTPMethod HTTP_OPTIONS'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                                                ^~~~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:69:18: error: 'HTTP_ANY' conflicts with a previous declaration

       69 |   HTTP_ANY     = 0b01111111,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:19: note: previous declaration 'HTTPMethod HTTP_ANY'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                   ^~~~~~~~

    Multiple libraries were found for "ESPAsyncTCP.h"

     Used: C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncTCP

     Not used: C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncTCP-master

    exit status 1

    Error compiling for board Generic ESP8266 Module.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.
```

# Code

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include <ESPAsyncTCP.h>
    #include <ESPAsyncWebServer.h>
    int Wifiled = 15;

    ESP8266WebServer esp(80);

    String HTML = "";

    String FORM = "testing the second website";

    void setup()
    {
           HTML +="";
           HTML +=  "";
           HTML +=    "<title>MY SMART HOME</title>";
           HTML +="";

           HTML +=  "";
           HTML +=  "";
           HTML +=  "
";
           HTML +=    "
WELCOME TO MY SMART SENSOR DATA
";
           HTML +=    "
PH SENSOR DATA
";
           HTML +=    "Serial.monitor";
           HTML +=    "
EC SENSOR DATA
";
           HTML +=  "
";
           HTML +=  "";
           HTML +="";
        pinMode(Wifiled,OUTPUT);
        delay(1000);
        Serial.begin(115200);
        WiFi.begin("LAPTOP","123456789");
        while(WiFi.status() != WL_CONNECTED)
        {
              Serial.print(".");
              digitalWrite(Wifiled,HIGH);
              delay(250);
              digitalWrite(Wifiled,LOW);
              delay(250);
        }
            digitalWrite(Wifiled,HIGH);
            Serial.println("wifi connected");
            Serial.println(WiFi.localIP());

            esp.on("/",sendHtml);
            esp.on("/process",sendform);
            esp.begin();
    }
    void sendform()
    {
      esp.send(200,"text/html;",FORM);
    }

    void sendHtml()
    {
      esp.send(200,"text/html;",HTML);

    }

    void loop()
    {
       esp.handleClient();
       delay(200);
       char buffer[20]="";
       if(Serial.available()>0){
      //  char data=Serial.read();
       Serial.readBytesUntil('\n',buffer,20);
       Serial.println(buffer);
       }
    }

title: ESPAsyncWebServer code not compiling

Answers: 1

body: You've included <ESP8266WebServer.h> and <ESPAsyncWebServer.h>, it's one or the other, you can't have both. Hence you're getting error: 'HTTP_GET' conflicts with a previous declaration


body:
I'm trying to read CO2 data from a MH-Z19C sensor with an ESP32 board but I'm not getting anything. The error code from the library is 2 indicating a timeout (no data received).

Did I get the wiring wrong?
I wonder if the sensor is fried ?

Library: MH-Z19 by Jonathan Dempsey

Connections:

 - MH-Z19C RX to TX2 (17)
 - MH-Z19C TX to RX2 (16)
 - MH-Z19C VIN to Power Supply 5V
 - MH-Z19C GND to Power Supply 3V

Code:
```c++
#include <SoftwareSerial.h>
#include <MHZ19.h>
#include <Wire.h>

// pin for uart reading
#define RX_PIN 16  // Rx pin which the MHZ19 Tx pin is attached to.
#define TX_PIN 17 // Tx pin which the MHZ19 Rx pin is attached to.

MHZ19 myMHZ19;
SoftwareSerial mySerial(RX_PIN, TX_PIN);

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

  // Start Co2 sensor
  mySerial.begin(9600);                               // (Uno example) device to MH-Z19 serial start
  myMHZ19.begin(mySerial);                                // *Serial(Stream) refence must be passed to library begin().
  myMHZ19.autoCalibration();                              // Turn auto calibration ON (OFF autoCalibration(false))
}

void loop() {
  // Wait a few seconds between measurements.
  delay(5000);

  int CO2;
  // Request CO2 (as ppm)
  CO2 = myMHZ19.getCO2();
  Serial.println(String(CO2) + " ppm");

  if (myMHZ19.errorCode != RESULT_OK) {
    Serial.print("Failed to receive CO2 value: ");
    Serial.println(myMHZ19.errorCode);
  }
}

```
[![backwards][1]][1]
[![wiring][2]][2]
[![esp32][3]][3]
[![power supply][4]][4]
[![circuit][5]][5]

  [1]: https://i.stack.imgur.com/0K5YY.jpg
  [2]: https://i.stack.imgur.com/cpULg.jpg
  [3]: https://i.stack.imgur.com/UEfWD.jpg
  [4]: https://i.stack.imgur.com/Rd05v.jpg
  [5]: https://i.stack.imgur.com/ooC22.png

title: Esp32 fails to read MH-Z19C sensor

Answers: 1

body:
This is not a Winsen Mh-z19 sensor (or any clone following it's specs) so you won't be able to read data using a mhz19 library.
Most probably it's a HC8 sensor and someone would have to rewrite library to get data from it.
Here are specs: https://pcus.ru/download/hc8.pdf and some more info:
https://spezifisch.codeberg.page/posts/2022-08-23/co2-sensor-reverse-engineering/


body:
a request for information has been formulated, how to say it?

in Ascii: i2C dialog: Tx -----> Rx ----> PCF8574

a drawing
https://nsm09.casimages.com/img/2023/02/28/23022802163423870818122937.jpg

3 elements on the i2C bus
- an Arduino "Tx" to read values from an electric counter
- an Arduino "Rx" to recycle the values and also to dialogue on a Rs485 bus
- and a PCF8574 which receives the commands from the Arduino "Rx" to operate telestage relays

1st question:

    I2C_writeAnything (foo1);
    (foo2);
    (foo3);
    I2C_writeAnything (foo X?);

What is the maximum number of foo1 .. foo2 ...foo10 that I can put ?

Is this the right method?
or do we have to group them by pack?

2nd question:

when we use several libraries, in their sketch we find calls to #include <Wire.h>
that are added to the main sketch.
Can this be a cause of problems?

thanks

    Arduino "Tx" for electrical measurements (simulation with a "random")

    void loop()  {

    unsigned long foo1 = random(2294967295);
    unsigned long foo2 = random(2294967295);
    unsigned long foo3 = random(2294967295);
    unsigned long foo4 = random(2294967295);
    unsigned long foo5 = random(2294967295);

    if (timer0.available()) {
    Wire.beginTransmission (SLAVE_ADDRESS);

    I2C_writeAnything (foo1);
    I2C_writeAnything (foo2);
    I2C_writeAnything (foo3);
    I2C_writeAnything (foo4);
    I2C_writeAnything (foo5);

    Wire.endTransmission ();

    if (!Wire.endTransmission ()) { Serial.println ("endTransmission () : "); }
    timer0.restart();
    }
    } /*Loop*/

    //Arduino "Rx" for reading and using the Electrical values
    #include <Wire.h>
    #include <I2C_Anything.h>   //http://www.gammon.com.au/i2c
    const byte MY_ADDRESS = 42;

    volatile boolean haveData = false;
    volatile unsigned long foo1;
    volatile unsigned long foo2;
    volatile unsigned long foo3;
    volatile unsigned long foo4;

    #include "PCF8574.h"    //https://github.com/RobTillaart/Arduino/tree/master/libraries/PCF8574
    PCF8574 PCF27a (0x3D);  // adjust addresses i2c pcf8574

    //...setup
    //...loop

    void receiveEvent (int howMany)  {

    // if (howMany >=  4)
    if (howMany >=  (sizeof foo1))    {
    I2C_readAnything (foo1);
    I2C_readAnything (foo2);
    I2C_readAnything (foo3);
    I2C_readAnything (foo4);

    haveData = true;
    }
    }  // end of receiveEvent

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

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

title: I2C_Anything ++

Answers: 1

body:
A return on the module of Electrical measurements.
with an i2C bus.
 (it can be useful for other people)

No more errors, no more blocking, it purrs like a kitten.

For the structure I copied the work of Peter_n (thanks to you)
 it helped me a lot:
https://forum.arduino.cc/t/i2c-not-sending-all-data-with-i2c_anything/293609

and for the :  Wire.setWireTimeout(3000,true);
not sure where to put it, it's put on both parts.

a copy of the sketches

Master_I2C_Anything_Linky_uneStructure_bigOctes.ino

      // base Written by Nick Gammon - May 2012 :
    // struct de Peter_n : https://forum.arduino.cc/t/i2c-not-sending-all-data-with-i2c_anything/293609

    //------------------ Dialogue on i2c bus between 2 ATMega328 - Arduino-Uno ------------
    // --- 2x6 32-bit values  ou 1x 7
    //------------------   functional test model ---------------------------
    // Add in setup :  Wire.setWireTimeout(3000,true);

      #include <Wire.h>
      #include <I2C_Anything.h>   //http://www.gammon.com.au/i2c

      const byte SLAVE_ADDRESS = 42;

      #include "Timers.h"         //https://github.com/nettigo/Timers
      Timer timer0;   // delay

    //------------  struct -------------------------
    //------------ linky info ---- 7 types de variables --------//

      struct sensorData_STRUCT {
      byte sensorNumber;
        uint16_t A;   // uint16_t PAPP in VA
        uint32_t B;   // uint32_t BASE index in Wh
        uint32_t C;   // uint32_t HCHC index heures creuses en Wh
        uint32_t D;   // uint32_t HCHP Index heures pleines en Wh
        uint8_t E;    // uint8_t  IINST  Returns in Amp
        uint8_t F;    // uint8_t ISOUSC  Returns ISOUSC
        uint8_t G;    // uint8_t PTEC Periode tarifaire en cours (0 = HP, 1 = HC)
         uint8_t H;    // test
      } sensorData[1]; // [x] number of structures

    //---------------------- SETUP --------------------
    void setup() {
      Serial.begin (115200);
      Serial.println(F(" Master_I2C_Anything_Linky_structure_double.ino "));
      Serial.print(__DATE__); Serial.println(__FILE__);

      Wire.begin ();

      Wire.setWireTimeout(3000,true);

      // fill fixed data
      sensorData[0].sensorNumber = 0;
     // sensorData[1].sensorNumber = 1; //desactivé

      timer0.begin(SECS(3));  //delay transmission

      } /*Setup*/

    //-------------------- LOOP -----------------------
      void loop()  {

    //---------------- strucuture ------------
    // collect new data
      sensorData[0].A = 10 ;
      sensorData[0].B = random(2000000000);
      sensorData[0].C = random(2000000000);
      sensorData[0].D =  random(2000000000) ;
      sensorData[0].E =  random(2000000000) ;
      sensorData[0].F =  random(2000000000) ; // valeur fixe
      sensorData[0].G = 70 ; // valeur fixe
      //     = 19 octes
    //unsigned long : non-negative integer of  0 à 4 294 967 295 sur 32 bits de 4 octets

    //------------------

      if (timer0.available()) {

     // 1; 2; choix du nbr de structre
      for( int sensor = 0; sensor < 1; sensor++)  {
        // transmit the data
        Wire.beginTransmission( SLAVE_ADDRESS);
        I2C_writeAnything( sensorData[sensor]);

        int error = Wire.endTransmission (); //(true) ?
         if( error != 0) {
          Serial.println(F("Error, no acknowledge from Slave"));
        }
      }

        timer0.restart();
      }

      } /*Loop*/

    //---------------------- End pgm ----------------------------

Slave_I2C_Anything_PCF8574_4DO_uneStructure_bigOctes.ino

    /*
     *  DESCRIPTION :
     *  un Arduino Uno en liaison avec un module i2c PCF8574 avec 4 Relais
     *  il recoi aussi d'un autre Arduino des valeurs en Kw pour le basculement des relay
     *
     *
     *  LIBRAIRIES:
     *    - Rob Tillaart pour PCF8574 https://github.com/RobTillaart/Arduino/tree/master/libraries/PCF8574
     *    - Nick Gammon  for bus i2c  http://www.gammon.com.au/i2c
     *    - Timers de Łukasz Tretyn   https://github.com/nettigo/Timers
     *
     *  ELEMENTS: sur le bus i2c
     *    - Expander PCF8574 avec module Metasys JC / 4DO - 0X3D  i2c adress
     *    - ATMega328  pour mesure Electrique
     *    - ATMega328  en Reception
     *
     *  MODIFICATION:
     *    -x- model de Peter_n : https://forum.arduino.cc/t/i2c-not-sending-all-data-with-i2c_anything/293609/11
     *    -o-
     *    -o-
     *
     *     RAS
    */

    //------ Mars 2023 -------- Linky PCF8574 - 4DO / Bus i2c -----------------//

    // -------------  Functional TEST BUS I2C -----------------------//
    // une struct de 19 Octes, pour un maximum  de 32octes

    //------ i2C Bus ------------
      #include <Wire.h>
      #include <I2C_Anything.h>
      const byte MY_ADDRESS = 42;

      // The struct must be the same in the Master and in the Slave
      //unsigned long:4 octet (32 bits) - max 4294967295
      struct sensorData_STRUCT {
      byte sensorNumber;
        uint16_t A;   // uint16_t PAPP in VA
        uint32_t B;   // uint32_t BASE index in Wh
        uint32_t C;   // uint32_t HCHC index heures creuses en Wh
        uint32_t D;   // uint32_t HCHP Index heures pleines en Wh
        uint8_t E;    // uint8_t  IINST  Returns in Amp
        uint8_t F;    // uint8_t ISOUSC  Returns ISOUSC
        uint8_t G;    // uint8_t PTEC Periode tarifaire en cours (0 = HP, 1 = HC)
         uint8_t H;    //
        };

    /*  struct sensor2Data_STRUCT {
      byte sensor2Number;
        int G;
        int H;
        int I;
        int J;
        int K;
        int L;
        }; */

      // A special struct for the received sensor data
      volatile sensorData_STRUCT sensorDataNew;

      // A flag to indicate new data
      volatile boolean haveData = false;

      // The normal sensor data
      sensorData_STRUCT sensorData[1];  //nbr de structure [2]

    //---------------- PCF8574 -------------------------------
      #include "PCF8574.h"
      PCF8574 PCF27a (0x3D);  // adjust addresses i2c pcf8574

      #define RELAY_ON  0    //
      #define RELAY_OFF 1    //

    // -----------------------------------------------------------------------------
    //      -----------------          SETUP          ---------------------
    // -----------------------------------------------------------------------------

    void setup() {

      Wire.begin (MY_ADDRESS);  // bus i2C
      Wire.onReceive (receiveEvent);

      Serial.begin (115200);
      Serial.println(F(" SlaveI2CAnythingPCF8574Structure_bigOctes "));
      Serial.print(__DATE__); Serial.println(__FILE__);

      // fill fixed data
      sensorData[0].sensorNumber = 0;

      Wire.setWireTimeout(3000,true);

      PCF27a.begin();           // i2C PCF8574

    //--------- testing IsConnected i2c PCfx ------------
      Serial.print(F(" PCF8574_LIB_VERSION : \t")); Serial.println(PCF8574_LIB_VERSION);
      if (!PCF27a.begin())   {
        Serial.println(F("could not initialize..."));
        }
      if (!PCF27a.isConnected())   {
        Serial.println(F("=> not connected"));
      }
      else   {
        Serial.println(F("=> connected!!"));
        }

      } /* fin Setup */

    // --------------------------------------------------------------------------
    //         -----------------        LOOP      ------------------------
    // --------------------------------------------------------------------------
     void loop() {

    //---------------- i2C bus -------------------------------
      int sensor;  int sensor2;

        if( haveData)  {
        // New data has arrived, copy it in one of the two sensorData.
        // Disable interrups as short as possible
        // The interrupts are disabled to avoid an receiveEvent interrupt that writes new data.
        noInterrupts();
        sensor = sensorDataNew.sensorNumber;

      if( sensor == 0 || sensor == 1) {         // destination, source, size
      memcpy( &sensorData[sensor], (const void *) &sensorDataNew, sizeof( sensorData_STRUCT));

      }
      haveData = false;
      interrupts();

        printData(sensor) ; //print Data
        cmdRelay() ;        // Relay PCF8574
       }

     } /* fin Loop */

    // -----------------------------------------------------------------------------
    //   -------------------  Receiving messages I2C    ------------------
    // -----------------------------------------------------------------------------
    //howMany est le nombre d'octets reçus et par conséquent combien vous pouvez lire
    //avec Wire.read(), pour un maximum de 32 octes.

     void receiveEvent( int howMany) {
      if( howMany == sizeof( sensorData_STRUCT)) {
        I2C_readAnything( sensorDataNew);
             haveData = true;
      }
      else {
        // something is wrong. Wrong number of bytes received.
        // it is possible to set a volatile variable to an error.
      }
     }

    // -----------------------------------------------------------------------------
    //   -------------------  Relay Control   ------------------
    // -----------------------------------------------------------------------------
     void cmdRelay() {
    //-------- Relay 1 ---------
      if (sensorData[0].A > 829308135 ) { PCF27a.write(0, RELAY_ON); }
      else { PCF27a.write(0, RELAY_OFF); }
         //Serial.println(PCF27a.read(0));
    //-------- Relay 2 ---------
      if (sensorData[0].B > 304929158) { PCF27a.write(1, RELAY_ON); }
      else { PCF27a.write(1, RELAY_OFF); }
          //Serial.println(PCF27a.read(1));
    //-------- Relay 3 ---------
      if (sensorData[0].C > 590793899 ) { PCF27a.write(2, RELAY_ON); }
      else { PCF27a.write(2, RELAY_OFF); }
         //Serial.println(PCF27a.read(2));
    //-------- Relay 4 ---------
      if (sensorData[0].D > 304929158) { PCF27a.write(3, RELAY_ON); }
      else { PCF27a.write(3, RELAY_OFF); }
          //Serial.println(PCF27a.read(3));
     }

    // -----------------------------------------------------------------------------
    //   -------------------  Print data   ------------------
    // -----------------------------------------------------------------------------
      void printData(int sensor) {

      if (sensor == 0 ) {
        Serial.print(F( "------ sensor["));
        Serial.print( sensor); Serial.println(F( "] ------"));
        Serial.print(F( "a PAPP  = ")); Serial.println( sensorData[0].A);
        Serial.print(F( "b BASE  = ")); Serial.println( sensorData[0].B);
        Serial.print(F( "c HCHC  = ")); Serial.println( sensorData[0].C);
        Serial.print(F( "d HCHP  = ")); Serial.println( sensorData[0].D);
        Serial.print(F( "e IINST = ")); Serial.println( sensorData[0].E);
        Serial.print(F( "f ISOUSC= ")); Serial.println( sensorData[0].F);
        Serial.print(F( "g PTEC  = ")); Serial.println( sensorData[0].G);
         Serial.print(F( "h test  = ")); Serial.println( sensorData[0].G);

    Serial.println(sizeof( sensorData_STRUCT));
        }
        Serial.println();
      }
    //------------------------------ End pgm -------------------------------------


body:
In our electronics tinker club, we had installed Arduino IDE 1.8 including drivers + the Holtek UART bridge (vendor ID 04D9, product ID B534) for the Elegoo Smart Car Kit 3.0 Plus ([product link](https://www.elegoo.com/en-de/products/elegoo-smart-robot-car-kit-v-3-0-plus)). The board is an Arduino Uno clone.

We now installed Arduino IDE 2.0.3 in parallel and tried that one, because its features looked promising.

However, in Arduino IDE 2.0.3, we had problems uploading the compiled sketch to the Smart Car Board. When I checked, it reported a different vendor ID and product ID (sorry, I didn't record which one).

I reinstalled the Holtek UART bridge driver ([direct download executable](https://roboter-basteln.de/downloads/arduino/USB Seriell Treiber Elegoo Smart Car 3+ (Holtek UART Bridge).exe)) and tried again. The vendor ID and product ID were correct this time, but uploading was still not going well in Arduino IDE 2.0.3.

Switching back to Arduino IDE 1.8 doesn't help. While the code still compiles (I expected it to), the upload problems now affect Arduino 1.8 as well, which was totally fine before we installed Arduino IDE 2.0.3.

How could I fix this issue?

I'll try to uninstall and reinstall everything, but I'm not sure it will be possible to uninstall all drivers.

title: Arduino IDE 1 interfering with Arduino IDE 2?

Answers: 1

body:
I spent more time (almost 20 working hours) to isolate this problem by

- testing the behavior with all of our 9 robot hardware in the club
- testing the behavior with all of our 8 notebooks in the club
- testing with the 6 different implementations we had, bricking and not bricking our robot hardware
- testing with an additional notebook that didn't seem affected
- combinations thereof

Finally I had a reproducible procedure with which I could "brick" a robot hardware and another procedure which would "unbrick" it.

That way I was able to a) minimize the code that was needed to "brick" the robot and b) compare that to the other codes that didn't have the issue. Finally I could ask [this new question](https://arduino.stackexchange.com/questions/92513/where-does-this-sketch-have-undefined-behavior) and get valuable feedback.

It turned out that this was **not related to the new Arduino 2.0.3 or 2.0.4 IDE. It was just a timely coincidence** that we wrote a new sketch we never wrote before in this way for this hardware.

That code used `Serial.begin()` with a "high" baud rate and obviously less delays than we ever used on this hardware before. And it [turned out](https://arduino.stackexchange.com/a/92523/35430) our hardware can't handle speeds higher than 19200 baud (!) without `delay()` statements. That's so slow!