body:
The project I'm working on: Short-Range Coded Visible Light communication System.

Visible Light Communication (VLC) systems utilize light to transfer data between transmitter and receiver over short-range links. This project intends to build a wireless VLC system capable of transmitting voice between two microcontrollers such as Arduino or Raspberry pi using visible light. A Light Emitting Diode (LED) or Laser diode deployed at the transmitter side and a Light Dependent Resistor (LDR) or photodiode deployed at the receiving side. Data transmission via air with relatively high speed compared to radio-frequency communication systems. Digital data transmitted using on-off keying where the LED function as on-off light. Strings of ones (1) and zeros (0) are transmitted with high frequency such that the LED flicking is undetectable to the human eye. Both hardware (Arduino / Raspberry pi microcontroller) and software (MATLAB/ Arduino/ another software) are required for successful data transmission and reception.

I'm using Arduino Uno and these are the codes that I used but I'm hearing noise from the speaker not my voice

    Transmitter code:
    // Define microphone pin
    const int micPin = A0;

    // Define LED pin
    const int ledPin = 9;

    // Define sampling frequency (in Hz)
    const int samplingFrequency = 8000;

    void setup() {
      // Set microphone pin as input
      pinMode(micPin, INPUT);

      // Set LED pin as output
      pinMode(ledPin, OUTPUT);

      // Begin serial communication at 9600 baud rate
      Serial.begin(9600);
    }

    void loop() {
      // Read analog voltage from microphone
      int analogValue = analogRead(micPin);

      // Map analog voltage to PWM duty cycle (0-255)
      int dutyCycle = map(analogValue, 0, 1023, 0, 255);

      // Set LED brightness based on duty cycle
      analogWrite(ledPin, dutyCycle);

      // Print duty cycle value to serial monitor
      Serial.println(dutyCycle);

      // Delay to maintain sampling frequency
      delay(1000 / samplingFrequency);
    }

Receiver code:

    const int ldrPin = 9;
    const int speakerPin = 11;
    int voiceSample;

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

    void loop() {
      analogWrite(ldrPin, voiceSample);
      delay(10);
      voiceSample++;
      if (voiceSample > 255) {
        voiceSample = 0;
      }
      int voiceInput = analogRead(A0);
      voiceInput = map(voiceInput, 0, 1023, 0, 255);
      analogWrite(speakerPin, voiceInput);
    }

title: I need some help in transmitting voice via VLC

Answers: 1

body:
The `Serial.println(dutyCycle)` in your transmitter is going to seriously slow down communications. It takes 1.04 ms to send a single byte over serial at 9600 baud, and assuming you have 3 digits, plus carriage return and linefeed that will take over 5 ms for each serial print.

However you are trying to sample at 8000 times a second (once per 125 µs) so you simply won't keep up. I suggest removing the serial print.

---

>     delay(1000 / samplingFrequency);

The `delay` function takes a `long` argument, not a float. `1000 / 8000` will evaluate to zero so the sample rate will not in fact be 8000 times a second.

You may want to consider the [delayMicroseconds](https://www.tutorialspoint.com/arduino/arduino_delaymicroseconds_function.htm) function.

---

Did you write this code or ChatGPT? [ChatGPT questions are currently banned on Stack Overflow](https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned).  I'm not sure about their policy in regards to Arduino Stack Exchange.


body:
I want to implement a simple external drive with ESP32-S3 that would act like a normal USB enabled flash drive when connected to a computer.

The actual storage of the data is done mechanically (for educational purposes) and controlled via the esp pins. (the exact setup is not important now)

I am using the esp32TinyUSB library to implement the communication between the ESP and the Computer. However the problem is, that when I actually try to store the data using the mechanical system (**which is very slow ~1 bit/s**), the USB disconnects from the computer.

Is there a way to fix this issue? I don't know how exactly the USB and MSC protocol works but I am thinking some keep-alive messages?

Here is the `setup()` which is typical for this library:

```cpp
void setup() {
  USB.onEvent(usbEventCallback);
  MSC.vendorID("myUSB");
  MSC.productID("myUSB");
  MSC.productRevision("1.0");
  MSC.onStartStop(onStartStop);
  MSC.onRead(onRead);
  MSC.onWrite(onWrite);
  MSC.mediaPresent(true);
  MSC.begin(DISK_SECTOR_COUNT, DISK_SECTOR_SIZE);
  USBSerial.begin();
  USB.begin();
}
```

and here is where the problem lies:

```cpp
static int32_t onWrite(uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize){
  // this check is there to only use the mechanical system of storage for
  //one of the segments
  if (lba == 8) {
    for(int i = 0; i < bufsize; i++) {
      writeAt(offset + i, buffer[i]); // this function is slow and probably causing problems
    }
  } else {
    memcpy(msc_disk[lba] + offset, buffer, bufsize); // otherwise store in memory
  }
  return bufsize;
}
```

thank you in advance!

UPDATE:

I later found, that the reason for the drive disconnecting is probably the fact, that the esp32 is not dealing with the interrupts (events) as fast as they are coming from the USB (which is unfortunately unavoidable). This probably causes the ESP32 to be overwelmed with the events to the point that it crashes.

I will have to come up with a queue in memory that will be holding the waiting events. It seems like there is nothing like keep-alive messages on this layer - the Windows OS just waits patiently and displays the loading bar...

title: Implementing very slow external drive using ESP32 and TinyUSB

Answers: 0


body:
I am working on a project that uses an Arduino Pro Mini to gather information from various sensor. Once the readings are taken I turn on an ESP-01 from a separate dedicated 3.3v power supply. The ESP-01 then sends the info to Adafruit.

This works fine. My problem lies in programming the Arduino Pro Mini. If I program it separately (without the ESP attached) using FTDI connected to my Mac using Arduino IDE everything goes great and program is successful.

If however I have the whole thing connected up on the PCB board where the TX on the Pro Mini is connected to RX on ESP-01 and the RX on Pro Mini to TX on ESP I can't get the program to upload. It just keeps trying to connect but can't even though it recognizes the board via the USB port.

Is there anyway to work around this without unsoldering things. I just want to tweak a bit of the programming on the Arduino Pro Mini. Not a big deal but I would be nice. I soldered a female header onto the end of the Pro Mini for programming.

I am enclosing a visual of the connection set up when I am trying to program Arduino Pro Mini.

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

Thanks in advance.

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

title: How can I program an Arduino Pro Mini with an ESP8266-01 connected to its TX and RX?

Answers: 0


body:
I've manage to build myself an RFID music player which I'm pretty chuffed with. It's definitely a bit home made but it woks and I'm proud of it. I don't know what plug type to buy to sort my problem below:

As you can see from the second photo, my wiring is a big mess. I've wired up all the components on the lid (the RFID reader, three buttons, and a speaker) with 21 single plug wire connections. As you can clearly see from the photo, it's a dogs breakfast of wires. Worse, the wiring is fragile and connections can break when I open and close the box.

The fix, I think, is fairly simple: to wire up a multi-wire plug connection between the lid and the box. That is have all the wires from the lid feed into one side of a plug, and all the wires on the bottom feed into the other side of the plug. That way, I can bundle all the wires up and attach them neatly out of the way, with the only moving part being the large multi-wire plugs.

I would really like one plug (male and female) with at least 21 pins, or few smaller pinned plugs to clean everything up. I don't know what to search for - when I google search for plugs, wiring harness, connections, etc, I get a variety of plugs and wires that just don't seem quite what I'm looking for.

Ideally, I'd like to be able to set up the plug by just screwing in each of the bare tinned wire ends. That way, alls I have to do is cut each single wire plug off, strip back the wire, tin it, then screw it into the plug in the right spot. Do that 21 times for each side and hey presto: 2 neat plugs.

Can someone please let me know what plug type I need? Or any other helpful suggestions?

![RFID Music Player][2]

[![Terrible wiring!][1]][1]

  [1]: https://i.stack.imgur.com/LBu0W.jpg
  [2]: https://i.stack.imgur.com/cu0cV.jpg

title: What do I need for a plug?

Answers: 1

body:
You could have use say 4 long stand-off spacers and mounted the circuit board on the underside of the lid (as you have done with the RFID reader), possibly inverting it for easier access to the arduino usb socket and SD card, so the lid could be removed without stressing the wiring.
If you had used a printed circuit board then edge connectors would have been a possibility.
I suppose you could use 0.1" header pins on the circuit board and use DuPont or similar connectors.


body:
I am trying to use an MPU6050 with my SAMD21 based board (actually LightAPRS W-2), but it doesn't work. The sensor definitely works, as I can get data from another 3.3v logic-level board, and the sensor works with a  level shifter with the Arduino Uno. I do not know what is wrong. My SAMD21 board I2C works fine with other devices, but both the MPU6050 and the MPU9250 don't work. Here is the code I am using:

```
/***************************************************************************
* Example sketch for the MPU9250_WE library
*
* This sketch shows how to measure pitch and roll angles from the MPU9250.
* I have also included the corrected angle method for comparison.
*
* For further information visit my blog:
*
* https://wolles-elektronikkiste.de/mpu9250-9-achsen-sensormodul-teil-1  (German)
* https://wolles-elektronikkiste.de/en/mpu9250-9-axis-sensor-module-part-1  (English)
*
***************************************************************************/

#include <MPU9250_WE.h>
#include <Wire.h>
#define MPU9250_ADDR 0x68

/* There are several ways to create your MPU9250 object:
 * MPU9250_WE myMPU9250 = MPU9250_WE()              -> uses Wire / I2C Address = 0x68
 * MPU9250_WE myMPU9250 = MPU9250_WE(MPU9250_ADDR)  -> uses Wire / MPU9250_ADDR
 * MPU9250_WE myMPU9250 = MPU9250_WE(&wire2)        -> uses the TwoWire object wire2 / MPU9250_ADDR
 * MPU9250_WE myMPU9250 = MPU9250_WE(&wire2, MPU9250_ADDR) -> all together
 * Successfully tested with two I2C busses on an ESP32
 */
MPU9250_WE myMPU9250 = MPU9250_WE(MPU9250_ADDR);

void setup() {
  Serial.begin(115200);
  Wire.begin();
  if(!myMPU9250.init()){
    Serial.println("MPU9250 does not respond");
  }
  else{
    Serial.println("MPU9250 is connected");
  }

  /* The slope of the curve of acceleration vs measured values fits quite well to the theoretical
   * values, e.g. 16384 units/g in the +/- 2g range. But the starting point, if you position the
   * MPU9250 flat, is not necessarily 0g/0g/1g for x/y/z. The autoOffset function measures offset
   * values. It assumes your MPU9250 is positioned flat with its x,y-plane. The more you deviate
   * from this, the less accurate will be your results.
   * The function also measures the offset of the gyroscope data. The gyroscope offset does not
   * depend on the positioning.
   * This function needs to be called at the beginning since it can overwrite your settings!
   */
  Serial.println("Position you MPU9250 flat and don't move it - calibrating...");
  delay(1000);
  myMPU9250.autoOffsets();
  Serial.println("Done!");

  /*  This is a more accurate method for calibration. You have to determine the minimum and maximum
   *  raw acceleration values of the axes determined in the range +/- 2 g.
   *  You call the function as follows: setAccOffsets(xMin,xMax,yMin,yMax,zMin,zMax);
   *  Use either autoOffset or setAccOffsets, not both.
   */
  //myMPU9250.setAccOffsets(-14240.0, 18220.0, -17280.0, 15590.0, -20930.0, 12080.0);

  /*  Sample rate divider divides the output rate of the gyroscope and accelerometer.
   *  Sample rate = Internal sample rate / (1 + divider)
   *  It can only be applied if the corresponding DLPF is enabled and 0<DLPF<7!
   *  Divider is a number 0...255
   */
  myMPU9250.setSampleRateDivider(5);

  /*  MPU9250_ACC_RANGE_2G      2 g    (default)
   *  MPU9250_ACC_RANGE_4G      4 g
   *  MPU9250_ACC_RANGE_8G      8 g
   *  MPU9250_ACC_RANGE_16G    16 g
   */
  myMPU9250.setAccRange(MPU9250_ACC_RANGE_2G);

  /*  Enable/disable the digital low pass filter for the accelerometer
   *  If disabled the bandwidth is 1.13 kHz, delay is 0.75 ms, output rate is 4 kHz
   */
  myMPU9250.enableAccDLPF(true);

  /*  Digital low pass filter (DLPF) for the accelerometer, if enabled
   *  MPU9250_DPLF_0, MPU9250_DPLF_2, ...... MPU9250_DPLF_7
   *   DLPF     Bandwidth [Hz]      Delay [ms]    Output rate [kHz]
   *     0           460               1.94           1
   *     1           184               5.80           1
   *     2            92               7.80           1
   *     3            41              11.80           1
   *     4            20              19.80           1
   *     5            10              35.70           1
   *     6             5              66.96           1
   *     7           460               1.94           1
   */
  myMPU9250.setAccDLPF(MPU9250_DLPF_6);
}

void loop() {
  xyzFloat angles = myMPU9250.getAngles();

/* This method provides quite precise values for x/y
   angles up 60°. */
  Serial.print("Angle x = ");
  Serial.print(angles.x);
  Serial.print("  |  Angle y = ");
  Serial.print(angles.y);
  Serial.print("  |  Angle z = ");
  Serial.println(angles.z);

/* Pitch and roll consider all axes for calculation. According to my experience
   it provides more reliable results at higher angles (>60°) */
  float pitch = myMPU9250.getPitch();
  float roll  = myMPU9250.getRoll();

  Serial.print("Pitch   = ");
  Serial.print(pitch);
  Serial.print("  |  Roll    = ");
  Serial.println(roll);

  Serial.println();

  delay(1000);

}
```

title: MPU9250 and MPU6050 not working on SAMD21 board

Answers: 0


body:
I'm following the standard process to put an STM32 "black pill" (STM32F401CC) into DFU mode so that I can upload from the Arduino IDE over USB:

1. Hold down boot0.
2. Press and release rst.
3. Release boot0.

When the board is not in a circuit this works somewhat reliably but not 100%. While breadboarding with only a few connections it becomes very unreliable and sometimes won't work at all.

The USB serial device set up by my Arduino sketch works fine, it is only DFU mode that does not want to work.

When it fails to enter DFU mode I see the following error in the Arduino upload process:

```
      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.13.0
      -------------------------------------------------------------------

An error occurred while uploading the sketch
Error: Target device not found
Establishing connection with the device failed
```

I'm using Arduino on Ubuntu 20.04 and when it fails I see in `/var/log/syslog`:

```
Apr 27 13:26:08 smurfenaar kernel: [79594.279257] usb 1-3: USB disconnect, device number 10
Apr 27 13:26:08 smurfenaar kernel: [79595.078232] usb 1-3: new full-speed USB device number 11 using xhci_hcd
Apr 27 13:26:09 smurfenaar kernel: [79595.192387] usb 1-3: device descriptor read/64, error -71
Apr 27 13:26:09 smurfenaar kernel: [79595.413389] usb 1-3: device descriptor read/64, error -71
Apr 27 13:26:09 smurfenaar kernel: [79595.636370] usb 1-3: new full-speed USB device number 12 using xhci_hcd
Apr 27 13:26:09 smurfenaar kernel: [79595.751435] usb 1-3: device descriptor read/64, error -71
Apr 27 13:26:09 smurfenaar kernel: [79595.973367] usb 1-3: device descriptor read/64, error -71
Apr 27 13:26:09 smurfenaar kernel: [79596.082540] usb usb1-port3: attempt power cycle
Apr 27 13:26:10 smurfenaar kernel: [79596.462407] usb 1-3: new full-speed USB device number 13 using xhci_hcd
Apr 27 13:26:10 smurfenaar kernel: [79596.462674] usb 1-3: Device not responding to setup address.
Apr 27 13:26:10 smurfenaar kernel: [79596.666550] usb 1-3: Device not responding to setup address.
Apr 27 13:26:10 smurfenaar kernel: [79596.874414] usb 1-3: device not accepting address 13, error -71
```

When it is successful I see:

```
pr 27 13:22:33 smurfenaar kernel: [79379.772197] usb 1-3: new full-speed USB device number 9 using xhci_hcd
Apr 27 13:22:33 smurfenaar kernel: [79379.899601] usb 1-3: New USB device found, idVendor=0483, idProduct=df11, bcdDe
vice=22.00
Apr 27 13:22:33 smurfenaar kernel: [79379.899605] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Apr 27 13:22:33 smurfenaar kernel: [79379.899607] usb 1-3: Product: STM32  BOOTLOADER
Apr 27 13:22:33 smurfenaar kernel: [79379.899609] usb 1-3: Manufacturer: STMicroelectronics
Apr 27 13:22:33 smurfenaar kernel: [79379.899611] usb 1-3: SerialNumber: 3466365E3135
```

and I can also see it with the `lsusb` command:

```
Bus 001 Device 052: ID 0483:df11 STMicroelectronics STM Device in DFU Mode

```

title: STM32 "black pill" won't enter DFU mode reliably

Answers: 2

body:
I found [this solution](https://www.stm32duino.com/viewtopic.php?t=1807) in the stm32duino forums:

> Tying A10 to GND successfully makes it enter DFU bootloader mode 100% of the time (though just not leaving PA10 floating is probably sufficient)
>
>  **Hypothesized Explanation**: In the last paragraph of Sec 4.3 of AN2606 (the STM bootloader manual), it states:
>>It is recommended to keep the RX pins of unused bootloader interfaces (USART_RX, SPI_MOSI, CAN_RX and USB D+/D- lines if present) at a known (low or high) level at the startup of the bootloader (detection phase). Leaving these pins floating during the detection phase might lead to activating unused interfaces.
>
> PA10 is the RX pin for USART_1. I believe that since PA10 is floating, the bootloader senses traffic on USART_1, and believes that's the interface it should use, and thus turns off USB. By tying PA10 to GND, the bootloader doesn't sense UART traffic and correctly enables USB.

While I followed the advice of tying it to ground I assume tying it to ground via a high resistance value would work too and should allow you to keep using PA10 for something else. After tying PA10 to GND I find entering DFU mode is 100% reliable, even when the board is in a circuit.

body:
I recently purchased two **"WeAct V3.0 STM32F411" Black Pill boards** on eBay. I've purchased many boards & other electronic items from this seller in the past without any issues. This eBay seller is very highly rated: 99.8% positive feedback with >1 million items sold. However, I cannot confirm whether these boards are "genuine" WeAct boards since I did not purchase them directly from WeAct.

Both of my Black Pill boards can be programmed with ST-LINK V2 using the standard 3 (or 4) wire SWD interface pins. No problems.

However, both boards initially failed to enter USB DFU programming mode after resetting boards with the `BOOT0` button pressed. Then I tried grounding pin `A10` as suggested above. **This totally fixed DFU programming**. Now both boards program perfectly every time via DFU mode.

The only downside is the requirement to press `BOOT0` + `NRST` buttons on board to initiate DFU programming mode prior to uploading with Arduino IDE.


body:
My dad watches netflix on his pc with his wireless mouse, hes gotten older and cannot hit the volume slide well enough.

I have an arduino kit (ard nano), an IR recevier and remote controller laying around (all from the arduino kit).

I want to use the remote control when you press volume down on it to make the windows volume go down.
I tried using chatgpt but have gotten nowhere, what would be the best simplest solution for this.

I was thinking it would be an easy read-in of the data from the receiver but how would you transfer this data on to windows? Is this possible, I havent found many examples online

Thank you all :)

title: IR Receiver Remote Controller for Windows

Answers: 1

body:
There are USB / HID keyboard codes for volume.  [Here][1] we see volume up is 0x80 and volume down is 0x81.

Consider obtaining an Arduino board which is capable of supporting a USB / HID port so that you can easily emulate a keyboard.  It would be best to choose a board with hardware USB / HID support.  But it may be possible to emulate (limited?) USB / HID support using software only.

There are plenty of Arduino USB / HID project ([here][2] and [here][3] are just 2 examples).  This should get you started designing an Arduino sketch which can transmit a keyboard's volume up and down control codes into one of the computer's USB ports.

And there are plenty of Arduino ASK / IR receiver projects ([here][4] and [here][5] are just 2 examples).  As there are many IR remote control codes, this part of the project might take a bit of research to uncover the codes used in the IR remote control you posses.

  [1]: https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2
  [2]: https://www.instructables.com/How-to-Make-a-Arduino-HID-Keyboard/
  [3]: https://learn.adafruit.com/circuitpython-essentials/circuitpython-hid-keyboard-and-mouse
  [4]: https://www.instructables.com/Using-an-IR-Receiver-With-Arduino/
  [5]: https://www.digikey.com/en/maker/blogs/2021/how-to-send-and-receive-data-over-ir-signals-with-an-arduino


body:
I am trying to write a program which takes in a number of pairs to be multiplied, then prints out the result of each multiplication. Instead of doing this, the program just prints out the number of multiplications and the numbers, but it never does the multiplications or add the newline characters (despite me explicitly using println). In the example below I specify 2 number pairs to multiply, and then enter 3,4,7,8 (entering a NL character after each number, but spaces and commas cause the same problem).

[![Result][1]][1]

I thought my approach would work, but I believe that there is something I am doing with the serial input that is causing the code not work (although there could be some other issue). I also wonder if maybe it's because I'm running this in Tinkercad and not the real Arduino IDE. Any help would be greatly appreciated.
```
void loop()
 {
  int numOfMults = 0;                             // number of pairs to multiply
  float *numArray;                                // pointer to beginning of array memory block
  numArray = (float *)malloc(sizeof(float)*50);   // dynamically allocate an array that can hold up to 50 floats

  numOfMults = Serial.parseInt(); // take in the number of multiplications from user

  Serial.println(numOfMults);

  // take in the specified amount of numbers (2 times the num of multiplications) in format: 1,2,3...
  // then convert that into an array of floats, where every 2 indices
  // is a pair of numbers to multiply
  for (int i = 0; i < (2*numOfMults) ;i++)
    {
      numArray[i] = Serial.parseFloat();
    }
      multNums(numOfMults,numArray);  // call function to get the product of all the numbers

      delay(5000);                    // wait 5 seconds before starting the loop again
 }

void multNums(int numofNums,float nums[])
{
  float *productArray;                                 // pointer to beginning of the product array memory block
  productArray = (float *)malloc(sizeof(float)*25);    // dynamically allocate an array that can hold up to 25 floats (for the products)

  // multiply all the number pairs in the array, store the product in another
  for(int i=0;i<(2*numofNums);i+2)
  {
      productArray[i/2] = nums[i]*nums[i+1];         // multiply current number pair, store in the product array one index at a time
  }
  // print the products
  for(int i=0; i < sizeof(productArray) ;i++)
  {
    Serial.println(productArray[i]);
  }
}
```

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

title: Program to Multiply Numbers Won't Actually Multiply Them

Answers: 2

body:
Ok I figured it out.

In the for loop I had to use i +=2, and not i+2.

What a dumb mistake..

body:
There are quite a few issues in this code:

 * In C++, you are supposed to do dynamic allocation with `new` rather
   than `malloc()`.

 * If you allocate dynamic memory in a loop and forget to free it (with
   `free()`/`delete`), you will quite quickly run out of memory.

 * Actually, you do not even need to do any dynamic allocation at all:
   automatic allocation is the safest way to handle these arrays.

 * Since you know the exact size you need, allocate that rather than a
   default size.

 * `multNums` receives as a parameter the number of multiplications, not
   the length of the array.

 * `i+2` does not change the value of `i`. You meant `i+=2`.

 * `sizeof(productArray)` does not give the length of the array, but its
   size in bytes. Besides, your last loop is supposed to iterate only
   through the initialized part of the array.

If you fix those issues, the program should work as expected.


body:
Hey all I have found some code on GitHub that works with my pool pump but it seems my model is a little newer than the one they used on on their GitHub. Most things seem to work **but what doesn't is that the buttons on the control board do not seem to call out correctly to the main board.**

The code for the buttons look to be this:

    #define BUTTON_BOOST        0x44
    #define BUTTON_TIMER        0x46
    #define BUTTON_POWER        0x4C
    #define BUTTON_LOCK         0x4E
    #define BUTTON_SELF_CLEAN   0x74

The bulk of the data **seems** to be coming from `void IRAM_ATTR Core1( void* p) {`...

And **perhaps** within that is the button code?

    if (sendingKeyCode) {
       if (totalBitsSent < 8) {
           digitalWrite(dataPin, (buttonStatus << totalBitsSent) & 0x80 ? HIGH : LOW);
           totalBitsSent++;
       }
       // FALLING edge 8 while sending keycode
       else if (totalBitsSent == 8) {
           // Receive ACK
           pinMode(dataPin, GPIO_MODE_INPUT);
           digitalWrite(dataPin, HIGH);
           totalBitsSent++;
       }
       // FALLING edge 9 while sending keycode
       else {
           sendingKeyCode = false;
           totalBitsSent = 0;
       }
    }

I did the rest api call (http://192.168.1.173:8080/api/v1/intex/swg/status) and got this:

    {
        "data": {
            "display": {
                "status": "ON",
                "brightness": 3,
                "current_code": "."
            },
            "status": {
                "power": "STANDBY",
                "boost": "OFF",
                "sleep": "OFF",
                "o3_generation": "OFF",
                "pump_low_flow": "OFF",
                "low_salt": "OFF",
                "high_salt": "OFF",
                "service": "OFF"
            },
            "mode": {
                "working": false,
                "programming": false
            }
        }
    }

So I know it can communicate with it just fine. And I also did this debug rest api call (http://192.168.1.173:8080/api/v1/intex/swg/debug) and got this back:

    {
        "data": {
            "powerStatus": "0x01",
            "statusDigit1": "0x00",
            "statusDigit2": "0x02",
            "statusDigit3": "0x00",
            "displayingDigit1": "0x00",
            "displayingDigit2": "0x02",
            "current_code": ".",
            "readBuffer": "[0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X48, 0X01], [0X68, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6C, 0X00], [0X49, 0XFF], [0X48, 0X01], [0X6A, 0X02], [0X49, 0XFF], [0X48, 0X01], [0X00, 0X00]",
            "compilation_date": "Apr 27 2023",
            "compilation_time": "16:20:36",
            "otaUpdating": false,
            "removeWifiConfig": false,
            "machineON": true,
            "wifiReconnecting": false,
            "readingMaster": true,
            "sendingKeyCode": false
        }
    }

**Would be great if someone more knowledgeable at binary and SDA/SCL would help me find my buttons binary code so that I can send that code to the pool pumps main controller.**

The GitHub> https://github.com/jingsno/intex-swg-iot

title: Pool pump man-in-the-middle SDA/SCL with ESP32

Answers: 0


body:
[![enter image description here][1]][1]I have an Arduino that is controlling two 6V DC motors through a L298N motor driver. The motor driver is being powered (from its Vin pin) by a 7.4V external source.

I then have the 5V pin from the motor driver connected to the 5V pin on an Arduino UNO to power the logic board.

Now, when I plugged in my Arduino to my computer to upload the sketch, everything was fine. However, when I unplugged the Arduino from the laptop, the Arduino was still being powered somehow from the 7.4V external source, though that source should only be powering the motors. I thought that unplugging the Arduino from the laptop would have cut power to the Arduino, but it was still somehow being powered by the external source.

What is going on here?

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

title: Why is my Arduino is getting power from the 5V pin?

Answers: 1

body:
The Arduino Uno can be powered from the 5 volts present on the USB cable or from an external 5 volts connected to the Arduino's 5V and GND (ground) pins.

In general, power supply outputs should never be connected in parallel unless they are designed for such an unusual configuration. From the description in the Question, it appears the USB power and the L289N power supplies were connected in parallel. Fortunately, the Arduino design include a power cut off shich.  Look for part "T1" [in this schmatic][1].  If power is applied from both the 5V pin and the USB port, the 5V pin is used and the USB power is cut off.

To answer your question specifically:

* Assuming [this is your board's schematic][2] (note, this is a link to an RAR file which contains a JPG of what is likely the wb291111 board's schematic) and assuming you have J6 jumper installed.

* If the Arduino 5V and GND (ground) pins were connected to the L289N board and the L289N board was supplying 5V power to the Arduino board, the Arduino board was never powered from the computer's USB port as transistor "T1" would have disconnected the USB power from the Arduino.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: http://www.geeetech.com/Documents/L298N_schematic.rar


body:
my results are here.
0 press--"a"
1st press--"b"
2nd press--"c"
3rd press-- still showing "c"
When button pressed 3rd time, It must be repeated to show "a" again. How can I repeat above 3 results to LCD?

```c++
#include <LiquidCrystal.h>
#include <ezButton.h>
ezButton button(7);
int count;
int count1;
const float rs = 1, en = 2, d4 = 3, d5 = 4, d6 = 5, d7 = 6;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
  button.setDebounceTime(50); // set debounce time to 50 milliseconds
  button.setCountMode(COUNT_FALLING);
  lcd.begin(16, 1);
}
void loop() {
  int count = button.getCount();
  button.loop();
  count1 = constrain(count, 0, 2);
  if(count1 == 0){
  lcd.print("a");
  }
  if(count1 == 1){
  lcd.print("b");
  }
  if(count1 == 2){
  lcd.print("c");
  }
  delay(500);
  lcd.clear();
}
```

title: How to show repeated result on LCD while button is pressing

Answers: 0


body:
Below is my current code for connecting to the A9G. As far as I can tell, it never actually opens a connection as ```HWSERIAL.println("AT");``` does not return anything. Any ideas would be appreciated.

The TX and RX pins of the A9G connected to the 0 and 1 pins on the teensy

```
    #include <SoftwareSerial.h>

    #define HWSERIAL Serial1

    void setup()
    {
      //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(115200);

      //Begin serial communication with Arduino and A6
      HWSERIAL.begin(115200);

      Serial.println("Initializing...");
      delay(1000);

      HWSERIAL.println("AT"); //Once the handshake test is successful, it will back to OK
      updateSerial();
    }

    void loop()
    {
      updateSerial();
    }

    void updateSerial()
    {
      delay(500);
      while (Serial.available())
      {
        HWSERIAL.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(HWSERIAL.available())
      {
        Serial.write(HWSERIAL.read());//Forward what Software Serial received to Serial Port
      }
    }
```

title: A9G GSM not connecting to teensy 4.0

Answers: 0


body:
I am uploading a simple Blynk cloud example code to control a led on GPIO2 of my esp01 board.

```cpp
#define BLYNK_TEMPLATE_ID ""
#define BLYNK_DEVICE_NAME ""

#define BLYNK_FIRMWARE_VERSION        "0.1.0"

#define BLYNK_PRINT Serial
//#define BLYNK_DEBUG

#define APP_DEBUG

// Uncomment your board, or configure a custom board in Settings.h
//#define USE_SPARKFUN_BLYNK_BOARD
//#define USE_NODE_MCU_BOARD
//#define USE_WITTY_CLOUD_BOARD
//#define USE_WEMOS_D1_MINI

#include "BlynkEdgent.h"

BLYNK_WRITE(V0)
{
 int pinValue = param.asInt();
  Serial.println("Value Change");
  digitalWrite(2,pinValue);
}
void setup()
{
  pinMode(2,OUTPUT);
  Serial.begin(115200);
  delay(100);

  BlynkEdgent.begin();
}

void loop() {
  BlynkEdgent.run();
}
```

when I run it for the first time it works flawlessly, it gets configured easily with Blynk app and i am able to control the led.
but, when I reboot my esp01 it does not store the credentials and again starts the code from beginning!!
I think I am not able to get out of programming mode.
Please help me out !!
Thanks

title: My esp01 code keeps on erasing after reboot

Answers: 0


body:
in my recent project, I'm trying to detect motion and capture an image using the esp32 cam module and send it to the server via HTTP.

Once the image is captured it is converted to a base64 string and while trying to send the data at the server the body of the HTTP request is empty i.e., the base64 string is not sent.

Code that sends the image
```
void sendPic(String data, String len) {

    if(WiFi.status() == WL_CONNECTED) {

      HTTPClient http;

      http.begin("http://192.168.1.35:8000/capture");

      String d = data ;

      int res_c = http.POST(d);

      if(res_c > 0){
        Serial.println(res_c);
      }
      else{
        Serial.println("Not sent");
        Serial.print(res_c);
      }
      http.end();
    }
}
```

Entire code

```
// turn on debug messages
#define VERBOSE
#include "Arduino.h"
#include <base64.h>
#include <esp_wifi.h>
#include <HTTPClient.h>
#include "EloquentSurveillance.h"

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

void sendPic(String data, String len) {

    if(WiFi.status() == WL_CONNECTED)

      HTTPClient http;

      http.begin("http://192.168.1.35:8000/capture");

      String d = data ;

      int res_c = http.POST(d);

      if(res_c > 0){
        Serial.println(res_c);
      }
      else{
        Serial.println("Not sent");
        Serial.print(res_c);
      }
      http.end();

    }
}

/**
 * Instantiate motion detector
 */
EloquentSurveillance::Motion motion;

/**
 *
 */
void setup() {
    Serial.begin(115200);

    WiFi.begin(ssid, password);
    Serial.println("Connecting");
    while(WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to WiFi network with IP Address: ");
    Serial.println(WiFi.localIP());

    if(WiFi.status() == WL_CONNECTED) {
      HTTPClient http;
      int res_c = -1;
      while(res_c < 0){
        http.begin("http://192.168.1.35:8080/capture");
        http.addHeader("Content-Type", "text/plain");
        String test = "hello from esp32";
        res_c = http.POST(test);

        if(res_c > 0){
          Serial.println(res_c);
        }
        else{
          Serial.println(res_c);
        }
        http.end();
      }

    }

    delay(3000);
    debug("INFO", "Init");

    /**
     * See CameraCaptureExample for more details
     */

    camera.aithinker();
    camera.vga();
    camera.bestQuality();

    /**
     * Configure motion detection
     *
     * > setMinChanges() accepts a number from 0 to 1 (percent) or an integer
     *   At least the given number of pixels must change from one frame to the next
     *   to trigger the motion.
     *   The following line translates to "Trigger motion if at least 10% of the pixels
     *   in the image changed value"
     */
    //motion.setMinChanges(0.015);
    motion.setMinChanges(0.02);

    /**
     * > setMinPixelDiff() accepts an integer
     *   Each pixel value must differ at least of the given amount from one frame to the next
     *   to be considered as different.
     *   The following line translates to "Consider a pixel as changed if its value increased
     *   or decreased by 10 (out of 255)"
     */
    motion.setMinPixelDiff(5);

    /**
     * > setMinSizeDiff() accepts a number from 0 to 1 (percent) or an integer
     *   To speed up the detection, you can exit early if the image size is almost the same.
     *   This is an heuristic that says: "If two consecutive frames have a similar size, they
     *   probably have the same contents". This is by no means guaranteed, but can dramatically
     *   reduce the computation cost.
     *   The following line translates to "Check for motion if the filesize of the current image
     *   differs by more than 5% from the previous".
     *
     *   If you don't feel like this heuristic works for you, delete this line.
     */
    //motion.setMinSizeDiff(0.015);
    motion.setMinSizeDiff(0.02);

    /**
     * Initialize the camera
     * If something goes wrong, print the error message
     */
    while (!camera.begin())
        debug("ERROR", camera.getErrorMessage());

    debug("SUCCESS", "Camera OK");
}

/**
 *
 */
void loop() {
    /**
     * Try to capture a frame
     * If something goes wrong, print the error message
     */
    if (!camera.capture()) {
        debug("ERROR", camera.getErrorMessage());
        return;
    }

    /**
     * Look for motion.
     * In the `true` branch, you can handle a motion event.
     * For the moment, just print the processing time for motion detection.
     */
    if (!motion.update())
        return;

    if (motion.detect()) {
        debug("INFO", String("Motion detected in ") + motion.getExecutionTimeInMicros() + " us");
        String encoded = base64::encode(camera.getBuffer(), camera.getFileSize());
        int size = camera.getFileSize() + 50;
        sendPic(encoded, (String)size);
        delay(4000);
    }
    else if (!motion.isOk()) {
        /**
         * Something went wrong.
         * This part requires proper handling if you want to integrate it in your project
         * because you can reach this point for a number of reason.
         * For the moment, just print the error message
         */
        debug("ERROR", motion.getErrorMessage());
    }
}
```

I'm a beginner in using esp32 cam any guidance on how to achieve the objective will be helpful. Thanks in advance!

title: ESP32-CAM not sending base64 string as HTTP post request

Answers: 0


body:
I am working on building a sensor using Arduino Nano 33 BLE that will measure temperature using two thermistors and angle changes. The measured values will be transmitted over Bluetooth to a smartphone every minute. I have written the code for temperature and angle measurements, as well as remote data transfer. However, I need this sensor to operate for 10 to 21 days on a 3.7v 250mAH battery. To achieve this, I planned to use the Arduino low-power library.

Unfortunately, I have not been able to find a library that is compatible with this Arduino board, nor have I found an example of how to put the board into sleep mode and then measure values every minute. I am aware of the option to power the board directly from a 3.3v source by cutting the 3.3V pads on the back of the board, disabling the power indication diode and turning off the sensors/the I2C pull-up resistors.

I would appreciate any suggestions or solutions to this problem. The full code of the sketch  is below:

```lang-cpp
#include <ArduinoBLE.h>
#include <Arduino_LSM9DS1.h>
//These  values are in the datasheet
#define RT0 100000   // Ω
#define B 4600      //  K
//--------------------------------------
#define VCC 3.3    //Supply  voltage
#define R 100000  //R=100KΩ

//Variables
float RT, VR, ln, TX0, TX1,  T0, VRT1, VRT0;
unsigned long last_time;
float x, y, z,angleX,angleY;

// Define the BLE service and characteristic
BLEService greetingService("180C");
BLEStringCharacteristic greetingCharacteristic("2A56", BLERead | BLENotify, 30);

void setup() {
  // Initialize BLE
  BLE.begin();

  // Set up the service and characteristic
  greetingCharacteristic.setValue("Hi");
  greetingService.addCharacteristic(greetingCharacteristic);
  BLE.addService(greetingService);

  // Start advertising the service
  BLE.advertise();
  Serial.begin(9600);
  T0 = 25 + 273.15;

  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }

  Serial.print("Accelerometer sample rate = ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println("Hz");
   // Set the initial rotation angles to 0
  angleX = 0;
  angleY = 0;
}

void loop() {

  if (millis()-60000>last_time){
  last_time=millis();
  VRT0 = analogRead(A0);              //Acquisition analog value of VRT
  Serial.println(analogRead(A0));
  VRT0  = (3.30 / 1023.00) * VRT0;      //Conversion to voltage
  VR = VCC - VRT0;
  RT = VRT0 / (VR / R);               //Resistance of RT
  ln = log(RT / RT0);
  TX0 = (1 / ((ln / B) + (1 / T0))); //Temperature from thermistor
  TX0 =  TX0 - 273.15;                 //Conversion to Celsius
  Serial.print("Temperature1:");
  Serial.print("\ ");
  Serial.print(TX0);
  Serial.println("\ C");
  VRT1 = analogRead(A1);              //Acquisition analog value of VRT
  Serial.println(analogRead(A1));
  VRT1  = (3.30 / 1023.00) * VRT1;      //Conversion to voltage
  VR = VCC - VRT1;
  RT = VRT1 / (VR / R);               //Resistance of RT
  ln = log(RT / RT0);
  TX1 = (1 / ((ln / B) + (1 / T0))); //Temperature from thermistor
  TX1 =  TX1 - 273.15;                 //Conversion to Celsius
  Serial.print("Temperature2:");
  Serial.print("\ ");
  Serial.print(TX1);
  Serial.println("\ C");

  IMU.readAcceleration(x, y, z);
    Serial.print("x=");
    Serial.print(x);
    Serial.print("y=");
    Serial.print(y);
    Serial.print("z=");
    Serial.print(z);

    // Calculate the rotation angles using the atan2 function
    angleX = atan2(y, z) * 180 / PI;
    angleY = atan2(x, sqrt(y * y + z * z)) * 180 / PI;

    // Map the rotation angles to the range [0, 360]
    angleX = fmod(angleX + 360, 360);
    angleY = fmod(angleY + 360, 360);

  // Print the rotation angles
  Serial.print("Rotation X: ");
  Serial.print(angleX);
  Serial.print(" degrees, Rotation Y: ");
  Serial.print(angleY);
  Serial.println(" degrees");

  BLEDevice central = BLE.central();
  if (central) {
    // Send the value of x to the connected device
    String message = String(TX0)+"/"+String(TX1)+"/"+String(angleX)+"/"+String(angleY);
    greetingCharacteristic.writeValue(message);
   }
  }
}
```

title: Arduino Nano 33 BLE power consumption optimization

Answers: 0


body:
I have timed the double reset as best as possible multiple times but the upload doesn't happen before the board leaves bootloader mode.

this is all I'm given as an error which doesn't appear until after the board leaves bootloader mode  (after the 8 seconds)
The one thing that I haven't been able to find info on is the fact that I do not have a SparkFun version, I have a non branded from ebay if that makes any difference

How can I fix?

    Sketch uses 3460 bytes (12%) of program storage space. Maximum is 28672 bytes. Global variables
     use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.

    avrdude: ser_open(): can't open device "\\.\COM11": The system cannot find the file specified.

    Failed uploading: uploading error: exit status 1

title: Pro Micro Double Reset help; Not able to get upload done in 8 seconds

Answers: 1

body:
* Remove the power to the board
* **Hold down** reset while you power it up.
* Release reset when the IDE says that it is uploading.


body:
I have a Mega2560 and would like to use it to power a single fan and display. The fan is a 5V fan that draws 260mA and I can't find power specs for this display. I can't find a clear answer for how much current I can safely draw off of the 5V pins on this board. Does anyone know if I'll be able to run these devices off of my Mega2560?

Board: https://www.amazon.ca/dp/B01H4ZLZLQ

Display: https://www.amazon.ca/gp/product/B085NHM5TC/

Fan: https://www.amazon.ca/dp/B07DXR1Y73/

title: Running a 5V, 4pin pwm fan with Mega2560

Answers: 0


body:
I'm gonna to upload some code to my LeArm using an Arduino board. I connected the rx and tx pins of the LeArm to the Arduino, but I got an error message when I tried to upload the code. I'm not sure if I did the connections correctly. Does anyone have any tips on how to upload the programs successfully?
[![enter image description here][1]][1]

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

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

  [1]: https://i.stack.imgur.com/EYObL.jpg
  [2]: https://i.stack.imgur.com/TMQLO.jpg
  [3]: https://i.stack.imgur.com/F47fz.jpg

title: Help with program upload problem!

Answers: 1

body:
Is the arduino MEGA you have a "chinese" version? if it is, try installing this drivers and try again :

> https://www.arduined.eu/ch340-windows-10-driver-download/


body:
The setup includes an WEMOS/ESP8266 R1 mini compatible board, a DHT11, a photo resistor and a magnetic reed.

The libs used are:
```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "DHT.h"
```
Compilation/loading is successful and the code starts normally, publishes and subscribes correctly.
```
Executable segment sizes:
ICACHE : 32768           - flash instruction cache
IROM   : 259412          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 27337   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)
DATA   : 1524  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 2300  ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 26416 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 290573 bytes (27%) of program storage space. Maximum is 1044464 bytes.
Global variables use 30240 bytes (36%) of dynamic memory, leaving 51680 bytes for local variables. Maximum is 81920 bytes.
esptool.py v3.0
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 5c:cf:7f:ad:11:6b
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 294720 bytes to 215795...
..
```

However the serial printing commands (ie Serial.println) in the code stop working for no apparent reason. The code/module is working, it is not dead.

I suspected json serialization but various changes that I tried didn't solve it. Then I thought that the dht lib is responsible, because serial printing stops in the dht function routine. But the adafruit stand alone examples work alright.

Here is the initial printing until it stops:
```
WiFi connected.
IP address:
192.168.xx.xx
ESP Mac Address: xx:xx:xx:xx:xx:xx
Subnet Mask: 255.255.255.0
Gateway IP: 192.168.xx.xx
DNS: 192.168.xx.xx
RRSI: -84
mqtt status in setup: 0
Humidity: 34.00% || Temperature: 24.00°C
before ser
```
This is the code function that requests dht data:
```

StaticJsonDocument<128> doc_dht;

void request_temp_hum() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  char  h_ch[10];
  char  t_ch[10];
  char buffer[256];
  doc_dht.clear();
  memset (h_ch, 0, sizeof(h_ch));
  memset (t_ch, 0, sizeof(t_ch));
  if (isnan(h) || isnan(t)) {
        Serial.println("Failed to read from the DHT sensor, check wiring.");
        return;
  }
  Serial.print("Humidity: ");
  Serial.print(h);
  //Print out the Temperature
  Serial.print("% || Temperature: ");
  Serial.print(t);
  Serial.println("°C ");

  dtostrf(t, 5, 2, t_ch);

  dtostrf(h, 5, 2, h_ch);

  doc_dht["sensor"] = "dht11";
  doc_dht["temp"] = t_ch;
  doc_dht["humi"] = h_ch;

  Serial.println("before serialization");
  serializeJson(doc_dht, buffer);
  Serial.println("after serialization..");
  client.publish("Home/info/dht", buffer);
  Serial.println("after publish");
  }
```
This is the mqtt publishes from the device:
```
02.05.2023 13:11:31 Home/info/dht {"sensor":"dht11","temp":"24.00","humi":"34.00"}
...
02.05.2023 13:26:38 Home/info/dht {"sensor":"dht11","temp":"25.00","humi":"34.00"}
```
Apart from the fact that I can't debug my code any further, it is evident that something is wrong and it might have further implications that I can't foresee. So why does serial printing stop working?

title: esp8266 r1 mini stops serial print during execution

Answers: 0


body:
Are there any options for programming an STM32 black-pill from the Arduino IDE without first having to manually push buttons to go into DFU mode or having to buy an ST-Link device?

A solution that leverages a second micro-controller board (I have Arduino Nanos, Pi Picos and ESP32 boards available) or requires some (easy) soldering would be fine.

title: Program SMT32 black-pill without pushing buttons or propriatary devices

Answers: 1

body:
Your question is one I was recently interested in as I too have begun using Blue/Black Pills, and I am still learning!
1. Have you got your Arduino IDE set up, and have you added the plugin for the STM32 boards? If not then you can find a tutorial in many places on the internet, one example being on youtube, if you prefer video tutorials...
 [https://www.youtube.com/watch?v=b1123kz_3MM][1]
Some are better than others and I prefer a written instruction, with or without pics!
Essentially you have to add:-
[https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json][2]
to your list or boards in the preferences. Many Tutorials will explain in detail.
2. Programming options include:
   1) STLink-v2.1 etc. The STLink-v2.1 is easy to source, cheap, and after it is eventually replaced by something else you can even repurpose it as if it is a STM32 USB stick!
   2) FTDI USB to TTL breakout adapter, 3.3v only, connected to the SWD pins on the opposite end to the USB socket.
   3) An Arduino board acting as a TTL/SWD adapter but already kind (talking) to Arduino!
   4) Burning an STM32-Arduino boot-loader onto the blue/black pill, and plug it in like an Arduino, using tutorials.
   5) Install STM32CubeProg, on your host computer, which is free and a very good IDE.
   6) NO DOUBT a search engine (of traditional values!) can find other options including JTAG, JLink, Bus-Pirate, etc. (Avoid search engines that send you straight to selling sites!)

   All of these need to be searched, read and understood before a logical choice is made, but all of them are usable choices. Every reader will know that you will get user advice insisting that you do what they have done, or worse, warning you to avoid methods that others have used successfully. Caveat Emptor!

Follow the easiest path to begin with, one of those that are given in the Arduino site perhaps, and investigate others when you have found what you want the process to do, and which process suits your methods and budget. Much depends on memory needs and applications.

  [1]: https://www.youtube.com/watch?v=b1123kz_3MM
  [2]: https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json


body:
I use a lot Arduino Uno, but in this case, I have some [BQ ZUM BT-328 boards][1], which are based on Arduino BT. The problem with some of BQ ZUM BT-328 boards is that the ultrasonic sensor ([HC-SR04][2]) is not working in any pin. However, apparantely, the boards work and the 2 servos ([SM-S4306R][3]) work fine too. When I change the ultrasonic sensor to other pins and with other wires, it is not working yet. However, I use that sensor in another different BQ ZUM BT-328 board and it is working fine, and if I add the same setup (2 SM-S4306R) and same code, it continues working fine. Then, the problem is just in some boards, not in everyone.

The ultrasonic example is:

    long distance;
    long responseTime;

    int pinTrig = 9;
    int pinEcho = 8;

    void setup(){
      Serial.begin(9600);
      pinMode(pinTrig, OUTPUT);
      pinMode(pinEcho, INPUT);
    }

    void loop(){
      digitalWrite(pinTrig, LOW);
      delayMicroseconds(5);

      digitalWrite(pinTrig, HIGH);
      delayMicroseconds(10);
      responseTime = pulseIn(pinEcho, HIGH);
      Serial.println("Tiempo "+ String(responseTime)+" microsegundos");

      distance = int(0.01716*responseTime);

      Serial.println("Distancia "+ String(distance)+"cm");
      delay(500);
    }

Then, I suppose that those BQ ZUM BT-328 boards have some problem and maybe they are starting to fail. I say this, because the same problem works in some boards and in others fails. In those board in which it fails I checked the correct connection of pins (GND, VCC, digitals), change the pin and the wires without result. However, the servos continue to work fine and I can upload the code to the board. My questions are:

Am I correct and they are failing?

Why they are just failing with that sensor and not the SM-S4306R? I mean, maybe some specific component of the board is failing?

  [1]: https://www.electronicsdatasheets.com/manufacturers/bq/parts/zum-bt328
  [2]: https://www.alldatasheet.com/datasheet-pdf/pdf/1132203/ETC2/HC-SR04.html?gclid=Cj0KCQjw6cKiBhD5ARIsAKXUdyZcI10wW6rgVh6BaDVhlH8hpniDbfgKCNIIO77sIs1qq-c9nZZLqMEaAl3IEALw_wcB
  [3]: https://datasheetspdf.com/pdf/897796/SPRINGRC/SM-S4306R/1

title: Problem with some sensors but not with servos

Answers: 1

body:
Looks like in your sample code you did not complete the 10us pulse.

```C
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(5);

  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(10);
  digitalWrite(pinTrig, LOW); // you missed this
```

See [example](https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/).


body:
I wanted to try to interface the pcf7991at with arduino, I assembled the pcb containing the pcf7991at following the diagram shown in the datasheet.
I saw that a frequency of 125khz must go on the CLK pin of the pcf, so I ask you if it is possible to use an internal arduino timer to try to see if the pcf7991at works.

title: interface pcf7991at to arduino

Answers: 2

body:
The Arduino is indeed capable of generating a 125kHz signal.
This example generates a 125kHz signal (50% duty cycle) on digital pin 3 of an Arduino Uno/Nano using Timer 2.

```
const int pulsePin = 3;  // note OC2B Pin D3 ! ! !
volatile uint32_t pulseCount = 0;

void setup(){

  pinMode(pulsePin, OUTPUT);

  cli() ;
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = 127 ; // f =  125kHz @16MHz clock
  OCR2B = (float) OCR2A * 0.5 ;
  TCCR2A |= (1 << WGM21) | (1 << WGM20) | (1 << COM2B1 ) ; // Mode 7 (fast PWM )
  TCCR2B |= (1 << CS20) | (1 << WGM22) ;   // ps /1  mode 7
  sei() ;
}

void loop() {
}
```

body:
The communication between MCU (Arduino) and IC (PCF7991AT) can work at any frequency (like SPI or I2C). The 125khz antenna frequency is generated in the IC internally. But you need to set the divider of the clock source (your crystal hooked up to the IC)

[https://datasheet.lcsc.com/lcsc/2208260930_NXP-Semicon-PCF7991AT-1081-M_C5143533.pdf][1]

See
page 7 -> 8.4 short explanation
page 13 -> to set the register

Hope this helps!

  [1]: https://datasheet.lcsc.com/lcsc/2208260930_NXP-Semicon-PCF7991AT-1081-M_C5143533.pdf


body:
Whenever I try to format a sketch in the IDE (1.8.19) I get this output in the terminal:

    Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: 'java.lang.String cc.arduino.packages.formatter.AStyleInterface.AStyleMain(java.lang.String, java.lang.String)'
           at cc.arduino.packages.formatter.AStyleInterface.AStyleMain(Native Method)
           at cc.arduino.packages.formatter.AStyle.run(AStyle.java:80)
           at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
           at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
           at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
           at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
           at java.base/java.security.AccessController.doPrivileged(Native Method)
           at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
           at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
           at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
           at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
           at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
           at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
           at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
           at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

...And formatting fails.

I can use astyle from the command line (linux mint) and it works well.

Guessing that some basic package was missing, or corrupted, I reinstalled Arduino, but the issue remained.

I don't precisely recall any specific changes made to my system prior to encountering this behavior, as it's been like this for at least 8 or 9 months now. I hadn't used Arduino for some time up until that point and it may have been a fresh instal.

Since I just started a new project for a buddy of mine and encountered the bug again I decided maybe it was time to see about a better solution.

Any help troubleshooting this would be greatly appreciated.

title: Arduino IDE Auto Format Error

Answers: 1

body:
I googled the first line of stack trace and found similar [issue on github](https://github.com/arduino/Arduino/issues/11728) (but for SUSE linux). In this issue the Arduino IDE was installed by system package manager and after downloading latest package from arduino.cc/en/software it started working.

In general Arduino IDE linux packages are somehow problematic (as far as I know Ubuntu has still version around 1.0.6) and it's better to use latest version directly from arduino.cc


body:
I am trying to use SIM7600 MQTT command to publish and subscribe to shiftr.io broker.

I have not been able to get pass stage of connecting to broker.

I use this
AT+CMQTTCONNECT=0,"tcp://instance.cloud.io:1883",90,1,"username","token"

I get this error code.
+CMQTTCONNECT:  0, 25

Of which code 25 indicate DNS error

title: SIM7600 MQTT CONNECTION TO shiftr.io broker

Answers: 1

body:
You answered your own question with "DNS error".

The domain name that you're using, `instance.cloud.io`, is currently not valid. You can verify this quite simply by searching the web for any web site that looks up domain names for you and searching for that domain name.

In this case, "instance" is most likely a placeholder for the correct name. You need to go back to whatever tutorial or instructions you were following for this and use the correct name for this to work.


body:
I'm using Industruino D21G (SAMD21G version) with Visual Studio Code extension for Arduino. `attachInterrupt` seems to have no effect. I tried Industruino CH1, CH6 and CH7 with the same result. When I poll these channels in a loop, I detect signal level change as expected. Here is the code:

```
#include <Arduino.h>
#include <Indio.h>

constexpr int PROXIMITY_SENSOR_NC = 6;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Indio.digitalMode(PROXIMITY_SENSOR_NC, INPUT);
  attachInterrupt(digitalPinToInterrupt(PROXIMITY_SENSOR_NC), blink, FALLING);
  digitalWrite(LED_BUILTIN, HIGH);
}

void blink() {
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}

void loop() {
}
```
Any ideas what could be wrong?

title: attachInterrupt has no effect on Industruino SAMD21

Answers: 1

body: Industrial level I/O on Industruino, which includes CH1, CH6 and CH7 I tried, is not connected directly to the microcontroller. It uses a buffer and communicates through I2C in pull mode. That's why interrupt on I/O change has no effect.


body:
So I'm using arduino 1.8.18 installed on zip file. I am using the HardWire library. The project is the STM32 quadcopter by joop brokking. http://www.brokking.net/ymfc-32_downloads.html

complete error -
```
Arduino: 1.8.18 (Windows 10), Board: "Generic STM32F103C series, STM32F103C8 (20k RAM. 64k Flash), Serial, 72Mhz (Normal), Smallest (default)"

C:\Users\ishaa\Documents\Arduino\libraries\HardWire\src\utility\twi.c:26:20: fatal error: avr/io.h: No such file or directory

Multiple libraries were found for "Wire.h"

 #include <avr/io.h>

 Used: C:\Users\ishaa\Desktop\arduino-1.8.18\hardware\Arduino_STM32-master\STM32F1\libraries\Wire
                    ^
 Not used: C:\Users\ishaa\Desktop\arduino-1.8.18\hardware\Arduino_STM32-master\STM32F1\libraries\WireSlave

compilation terminated.

exit status 1

Error compiling for board Generic STM32F103C series.
```
As you can see I'm using the stm32 lib by roger clark. The ide is unable to detect any of the avr/.h files. I tried replacing the path in twi.c, but then the other avr files start giving errors.

Why is this happening?

title: fatal error: avr/io.h: No such file or directory (on Windows 11)

Answers: 0


body:
Is it possible to connect ESP32 cam to the Nodemcu motor shield? I already have a ESP8266 chip connected to the Nodemcu motor shield.

In get this error after connecting this ESP32 cam to the Nodemcu motor shield like this

    VCC: Connect to 5V on the NodeMCU motor shield
    GND: Connect to GND on the NodeMCU motor shield
    UnR: Connect to TX on the NodeMCU motor shield
    U0T: Connect to RX on the NodeMCU motor shield

***A fatal esptool.py error occurred: Failed to connect to ESP8266: Timed out waiting for packet header***

title: Connect ESP32 cam to the Nodemcu motor shield

Answers: 0


body:
I need to recognize a signal from an IR remote, not to use a library for working with IR remotes/receivers. How can when the button is clicked to display its name. I have PIC12F615 microcontroller with this code: [code][1] and 5 buttons connected to him and I need recognise which button pressed. I have some code but it gives different hex codes if I pressed the same button.

    byte IRpin = 2;

    volatile boolean remote = false;
    volatile unsigned long irCode = 0;

    void remoting ()
    {
      if ( remote )
      {
        remote = false;
        unsigned long T;
        for ( byte n = 0; n < 32; n ++ )
        {
          do
          {
            T = pulseIn ( IRpin, HIGH, 2200 );
          }
          while ( T < 64 );
          bitWrite ( irCode, n, T > 1120 );
        }
      }
    }

    void setup ()
    {
      Serial.begin ( 9600 );
      Serial.println ( "\n\tReady for keyboard reading!\n" );
      pinMode ( IRpin, INPUT_PULLUP );
      attachInterrupt ( digitalPinToInterrupt ( IRpin ), remoting, FALLING );
    }

    void loop ()
    {
      if (irCode)
      {
        Serial.println (irCode, HEX);
        irCode = 0;
      }
      delay (40);
      remote = true;
    }

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

  [1]: https://github.com/circuitvalley/IR-Remote-Control/blob/master/NEC IR Transmitter Remote/main.c
  [2]: https://i.stack.imgur.com/Pf4Ik.jpg

Answers: 1

body:
The function pulseIn() has this comment in the source code: "This function performs better with short pulses in noInterrupt() context" see: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_pulse.c. It is not clear if your code violates the "short pulse" rule, however, blocking an Interrupt Service Routine (in your case, the external interrupt call back routine remoting() ) for the entire length of an IR data stream is certain to cause other problems, for example, with the millis() timer.

This is in the style of your code but avoids using interrupts. It has been tested against an NEC remote control and gives repeatable results. Your code fails the same test.

```
byte IRpin = 2;

unsigned long irCode = 0;

void setup ()
{
  Serial.begin ( 9600 );
  Serial.println ( "\n\tReady for keyboard reading!\n" );
  pinMode ( IRpin, INPUT_PULLUP );
}

void loop () {
  while ( digitalRead ( IRpin ) );  // wait until start of first pulse
  unsigned long T;
  uint8_t validPulses = 0 ;
  for ( byte n = 0; n < 36 ; n ++ ) // enough to drop long header
  {
    T = pulseIn ( IRpin, HIGH , 12000 );  // 12ms timeout
    if ( T < 4000 && T > 400 && validPulses < 32 ) {
      // valid pulse
      bitWrite ( irCode, validPulses++, T > 1120 );
    }
  }
  if (irCode > 0 ) Serial.println (irCode, HEX);
  else Serial.println ("no code");
  irCode = 0 ;
}

```


body:
```
int trigPin = 10;

const int echoPin = 8;

int led = 7;

const int distance = 200;

void setup()
{
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(led, OUTPUT);
}
void loop()
{
 int duration, cm;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);

 duration = pulseIn(echoPin, HIGH);
 cm = duration/58;
 if (cm < distance)
 {
  digitalWrite(led, HIGH);
 }
 else
 {
  digitalWrite(led, LOW);
 }
 delay(100);
}
```
[![enter image description here][1]][1]

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

title: It is required to turn on the LED if the distance to the object is less than or equal to 200 centimeters. Find the error in the code

Answers: 1

body:
1. You have `trigPin` as pin 10, however your wiring diagram shows it connected to pin 9, so that won't work.

2. `pulseIn` returns an `unsigned long` (microseconds) - see [pulseIn](https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/). You are collecting the results in an `int` which has a maximum value of 32767. The value may be overflowing and thus not be correct.


body:
I have written a simple script to get angle measurements from a magnetic sensor. The script works very well on Windows. However, when compiling the script on a Linux VirtualBox (Ubuntu 20.04), the sensor repeats the first angle reading and does not change from this, despite the angle changing. There are no errors/warnings given by Windows or Linux at any stage of compiling/uploading.

Uploading the script on Windows and then viewing in Linux serial monitor works. However, uploading it on Linux and then viewing in Windows serial monitor does not work ("Board is not available"), even when connecting the board to Linux and not Windows.

I've compared both systems and everything seems to be the same: the same Arduino Uno R3 board, Arduino IDE 1.8.19 on both systems, Arduino AVR Boards 1.8.3 on both, "Arduino Uno" selected as the board on both, the library is SimpleFOC v2.2.0 on both. The only difference I can see is that the Windows port is COM3, whereas the Linux port is /dev/ttyACM0.

My script is the following and I would appreciate any help or advice to get this working on Linux. Thank you.

```
#include <SimpleFOC.h>

#define PI 3.1415926535897932384626433832795

// Magnetic sensor instance
MagneticSensorSPI AS5x4x = MagneticSensorSPI(8, 14, 0x3FFF);

void setup() {
  // initialize magnetic sensor hardware
  AS5x4x.init();

  // use monitoring with serial
  Serial.begin(9600);

  Serial.println("Ready.");
  _delay(1000);
}

void loop() {
  Serial.println(AS5x4x.getAngle()); // display angle
}
```

title: Arduino Readings Update Correctly on Windows but not Linux

Answers: 1

body: It turns out that the Arduino Library Manager was giving me incorrect information about the library version installed. By removing the library it was using and then installing the correct library that corresponds to the required version number, the code now works well.


body:
I'm pretty new to esp32 and I'm trying to combine two codes in one, they are simple codes from projects that I found online, the first one uses PIR sensor to send message to telegram each time motion is detected, second code uses RFID to open door lock. When I tried directly merging the two codes together the esp32 went crazy on serial monitor and nothing worked even the WIFI failed to connect.

Then I tried creating task for each one using freeRTOS and I did it like this:

 ***task1***: *for* Wifi connection **running on CORE 0** //wifi function is taken from sketch 1

 ***task2***: *for* RFID and door lock **running on CORE 1** //taken from sketch 2

 ***task3***: *for* motion detection and sending telegram message **running on CORE 0** //taken from sketch 1

Again esp32 went crazy when I opened serial monitor and it gave me this error:` " Guru Meditation Error: Core  1 panic'ed (IllegalInstruction). Exception was unhandled. " `

I have no clue why is this happening, does it really require RTOS to combine the two sketches and run them at the same time, or a simple delays and if statements would solve the problem? I need some help please.

**Sketch 1: Motion detection** from [enter link description here][1]

```
/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/telegram-esp32-motion-detection-arduino/

  Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
*/

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Initialize Telegram BOT
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)

// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "XXXXXXXXXX"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

const int motionSensor = 27; // PIR Motion Sensor
bool motionDetected = false;

// Indicates when motion is detected
void IRAM_ATTR detectsMovement() {
  //Serial.println("MOTION DETECTED!!!");
  motionDetected = true;
}

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

  // PIR Motion Sensor mode INPUT_PULLUP
  pinMode(motionSensor, INPUT_PULLUP);
  // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
  attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  bot.sendMessage(CHAT_ID, "Bot started up", "");
}

void loop() {
  if(motionDetected){
    bot.sendMessage(CHAT_ID, "Motion detected!!", "");
    Serial.println("Motion Detected");
    motionDetected = false;
  }
}
```

**Sketch 2: RFID door lock** from [enter link description here][2]

```
/*
 * This ESP32 code is created by esp32io.com
 *
 * This ESP32 code is released in the public domain
 *
 * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-rfid-nfc-door-lock-system
 */

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN    5  // ESP32 pin GIOP5
#define RST_PIN   27 // ESP32 pin GIOP27
#define RELAY_PIN 22 // ESP32 pin GIOP22 connects to relay

MFRC522 rfid(SS_PIN, RST_PIN);

byte keyTagUID[4] = {0xFF, 0xFF, 0xFF, 0xFF};

void setup() {
  Serial.begin(9600);
  SPI.begin(); // init SPI bus
  rfid.PCD_Init(); // init MFRC522
  pinMode(RELAY_PIN, OUTPUT); // initialize pin as an output.
  digitalWrite(RELAY_PIN, HIGH); // lock the door

  Serial.println("Tap an RFID/NFC tag on the RFID-RC522 reader");
}

void loop() {
  if (rfid.PICC_IsNewCardPresent()) { // new tag is available
    if (rfid.PICC_ReadCardSerial()) { // NUID has been readed
      MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

      if (rfid.uid.uidByte[0] == keyTagUID[0] &&
          rfid.uid.uidByte[1] == keyTagUID[1] &&
          rfid.uid.uidByte[2] == keyTagUID[2] &&
          rfid.uid.uidByte[3] == keyTagUID[3] ) {
        Serial.println("Access is granted");
        digitalWrite(RELAY_PIN, LOW);  // unlock the door for 2 seconds
        delay(2000);
        digitalWrite(RELAY_PIN, HIGH); // lock the door
      }
      else
      {
        Serial.print("Access denied, UID:");
        for (int i = 0; i < rfid.uid.size; i++) {
          Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
          Serial.print(rfid.uid.uidByte[i], HEX);
        }
        Serial.println();
      }

      rfid.PICC_HaltA(); // halt PICC
      rfid.PCD_StopCrypto1(); // stop encryption on PCD
    }
  }
}

```

  [1]: https://RandomNerdTutorials.com/telegram-esp32-motion-detection-arduino/
  [2]: https://esp32io.com/tutorials/esp32-rfid-nfc-door-lock-system

title: FreeRTOS is not solving my problem to run tasks parallelly

Answers: 1

body:
No, you don't need an RTOS to do something simple like:

    if (motionDetected)
        open_the_door ();

---

You basically have two loops:

    void loop ()
      {
      if (motionDetected)
          send_a_message_to_open_the_door ();
      }

And:

    void loop ()
      {
      if (message_received_to_open_the_door)
         open_the_door();
      }

So, you combine them into a single loop:

    void loop ()
      {
      if (motionDetected)
         open_the_door();
      }

I'll leave you to make the actual code changes.


body:
I need to recognize a signal from an IR remote, not to use a library for working with IR remotes/receivers. How can when the button is clicked to display its name. I have PIC12F615 microcontroller with this code: [code][1] and 5 buttons connected to him and I need recognise which button pressed. Why NEC IR remote control decoder does not work, it doesn't set nec_ok to true.If output nec_state to the terminal, I get 0 1 0 1 0 1 and so on.

        boolean nec_ok = 0;
    byte i, nec_state = 0, command, inv_command;
    unsigned int address;
    unsigned long nec_code;

    void setup() {
    Serial.begin(9600);
    // Timer1 module configuration
    TCCR1A = 0;
    TCCR1B = 0; // Disable Timer1 module
    TCNT1 = 0; // Set Timer1 preload value to 0 (reset)
    TIMSK1 = 1; // enable Timer1 overflow interrupt
    attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Enable external interrupt (INT0)
    }

    void remote_read() {
    unsigned int timer_value;
    if(nec_state != 0){
    timer_value = TCNT1; // Store Timer1 value
    TCNT1 = 0; // Reset Timer1
    }
    switch(nec_state){
    case 0 : // Start receiving IR data (we're at the beginning of 9ms pulse)
    TCNT1 = 0; // Reset Timer1
    TCCR1B = 2; // Enable Timer1 module with 1/8 prescaler ( 2 ticks every 1 us)
    nec_state = 1; // Next state: end of 9ms pulse (start of 4.5ms space)
    i = 0;
    return;
    case 1 : // End of 9ms pulse
    if((timer_value > 19000) || (timer_value < 17000)){ // Invalid interval ==> stop decoding and reset
    nec_state = 0; // Reset decoding process
    TCCR1B = 0; // Disable Timer1 module
    }
    else
    nec_state = 2; // Next state: end of 4.5ms space (start of 562µs pulse)
    return;
    case 2 : // End of 4.5ms space
    if((timer_value > 10000) || (timer_value < 8000)){
    nec_state = 0; // Reset decoding process
    TCCR1B = 0; // Disable Timer1 module
    }
    else
    nec_state = 3; // Next state: end of 562µs pulse (start of 562µs or 1687µs space)
    return;
    case 3 : // End of 562µs pulse
    if((timer_value > 1400) || (timer_value < 800)){ // Invalid interval ==> stop decoding and reset
    TCCR1B = 0; // Disable Timer1 module
    nec_state = 0; // Reset decoding process
    }
    else
    nec_state = 4; // Next state: end of 562µs or 1687µs space
    return;
    case 4 : // End of 562µs or 1687µs space
    if((timer_value > 3600) || (timer_value < 800)){ // Time interval invalid ==> stop decoding
    TCCR1B = 0; // Disable Timer1 module
    nec_state = 0; // Reset decoding process
    return;
    }
    if( timer_value > 2000) // If space width > 1ms (short space)
    bitSet(nec_code, (31 - i)); // Write 1 to bit (31 - i)
    else // If space width < 1ms (long space)
    bitClear(nec_code, (31 - i)); // Write 0 to bit (31 - i)
    i++;
    if(i > 31){ // If all bits are received
    nec_ok = 1; // Decoding process OK
    detachInterrupt(0); // Disable external interrupt (INT0)
    return;
    }
    nec_state = 3; // Next state: end of 562µs pulse (start of 562µs or 1687µs space)
    }
    }

    ISR(TIMER1_OVF_vect) { // Timer1 interrupt service routine (ISR)
    nec_state = 0; // Reset decoding process
    TCCR1B = 0; // Disable Timer1 module
    }

    void loop() {
    Serial.println(nec_ok);
    if(nec_ok){ // If the mcu receives NEC message with successful
    nec_ok = 0; // Reset decoding process
    nec_state = 0;
    TCCR1B = 0; // Disable Timer1 module
    address = nec_code >> 16;
    command = nec_code >> 8;
    inv_command = nec_code;

    attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Enable external interrupt (INT0)
    }
    }

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

  [1]: https://github.com/circuitvalley/IR-Remote-Control/blob/master/NEC IR Transmitter Remote/main.c
  [2]: https://i.stack.imgur.com/Pf4Ik.jpg

Answers: 1

body:
External interrupt version of NEC protocol decoder using micros() for timing instead of Timer 1.
Drops NEC repeat codes,
Otherwise, in the style of the code in the question.

```
volatile boolean nec_ok = 0;
byte command, inv_command;
volatile byte nec_state = 0 ;
unsigned int address;
volatile unsigned long nec_code;
volatile uint32_t errFlag = 0 ;
volatile uint32_t decodeStartAtMs = 0 ;

void setup() {
  Serial.begin(9600);
  pinMode( 2, INPUT_PULLUP ) ;
  attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Enable external interrupt (INT0)
}

void remote_read() {

  static byte i = 0 ;
  static bool wasSpace;
  static unsigned long enteredAtUs = 0 ;
  static unsigned long pulseLengthLastUs ;

  wasSpace = ! digitalRead( 2 ) ;
  pulseLengthLastUs = micros() - enteredAtUs; // Calculate pulse length
  enteredAtUs = micros(); // Store current time for next entry

  switch (nec_state) {

    case 0 : // Wait here until 9ms pulse found )
      if ( pulseLengthLastUs > 8000 && pulseLengthLastUs < 10000 ) {  // got a 9ms pulse
        decodeStartAtMs = millis() ;  // for timeout
        nec_state = 1 ;
        nec_code = 0 ;
        i = 0 ;
      }
      break;

    case 1 : // handle 4.5ms space
      /*
      if ((pulseLengthLastUs > 2000) && (pulseLengthLastUs < 2500)) {
          // silently drop repeat codes !!!
          nec_state = 0; // Reset decoding process
      }
      else
      */
      if ((pulseLengthLastUs > 5500) || (pulseLengthLastUs < 3500)) {
        errFlag = 10000000 + pulseLengthLastUs ;
        nec_state = 0; // Reset decoding process
      }
      else
        nec_state = 2; // Next state: end of 562µs pulse (start of 562µs or 1687µs space)
      break;

    case 2 : // handle 562µs or 1687µs space
      if ((pulseLengthLastUs > 1900) || (pulseLengthLastUs < 400)) { // Time interval invalid ==> stop decoding
        errFlag = 20000000 + pulseLengthLastUs ;
        nec_state = 0; // Reset decoding process
        break;
      }

      if ( wasSpace ) {
        // we are interested only in the space length
        if ( pulseLengthLastUs > 1000) // If space width > 1ms (short space)
          bitSet(nec_code, (31 - i)); // Write 1 to bit (31 - i)
        else // If space width < 1ms (long space)
          bitClear(nec_code, (31 - i)); // Write 0 to bit (31 - i)
        i++;
        if (i > 31) { // If all bits are received
          i = 0 ;
          nec_ok = 1; // Decoding process OK
          detachInterrupt(0); // Disable external interrupt (INT0)
        }
      }
      break;
  }
}

void loop() {

  if ( errFlag > 0 ) {
    Serial.print( "Error: " ) ;
    Serial.println( errFlag ) ;
    errFlag = 0 ;
  }

  if ( nec_state > 0 && millis() - decodeStartAtMs > 90 ) {
    Serial.println( "Timeout" ) ;
    nec_state = 0 ;
  }

  if (nec_ok) {
    Serial.print( "Code received = " ) ;
    Serial.println( nec_code, HEX ) ;

    address = (nec_code >> 16) & 0xFF; // Extract address from received code
    inv_command = (nec_code >> 8) & 0xFF; // Extract inverted command from received code
    command = nec_code & 0xFF; // Extract command from received code
    if (command == ((~inv_command) & 0xFF)) { // Verify command validity
      Serial.print("Received valid NEC code: ");
      Serial.print(address, HEX); Serial.print(", ");
      Serial.print(command, HEX); Serial.print(", ");
      Serial.println(inv_command, HEX);
    }
    else {
      Serial.println("Received invalid NEC code!");
    }
    nec_ok = 0; // Reset decoding process
    nec_state = 0; // Reset decoding state
    attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Re-enable external interrupt (INT0)
  }

}
```

This utility can be used to verify the output of an IR receiver showing the timings of the pulses and spaces to  4us resolution.

```
// protocol analyser utility
// intended to dump timings to the serial console for example from demodulated NEC IR codes
// Connect the IR receiver output to pin 2

const uint8_t DATA_SIZE = 100 ;

struct intervalRead_t {
  uint32_t durationUs ;
  bool space ;
} ;

intervalRead_t intervalRead[ DATA_SIZE ] ;

volatile unsigned long enteredAtUs = 0 ;
volatile uint8_t index = 0 ;
volatile bool firstPulse = true ;

void saveTimes() {

  bool wasSpace;
  uint32_t pulseLengthLastUs ;

  wasSpace = ! digitalRead( 2 ) ;
  pulseLengthLastUs = micros() - enteredAtUs; // Calculate pulse length
  enteredAtUs = micros(); // Store current time for next entry

  if ( firstPulse ) {
    firstPulse = false ;
    index = 0 ;
  }
  else {
    if ( index < DATA_SIZE  )  {
      intervalRead[ index ].durationUs = pulseLengthLastUs ;
      intervalRead[ index ].space = wasSpace ;
      index++ ;
    }
  }
}

void setup() {
  Serial.begin(9600);
  pinMode( 2, INPUT_PULLUP ) ;
  attachInterrupt(digitalPinToInterrupt(2), saveTimes, CHANGE); // Enable external interrupt (INT0)
}

void loop() {
  if ( !firstPulse && micros() - enteredAtUs > 500000UL  ) {
    for ( uint8_t i = 0; i < index ; i++ ) {
      Serial.print( i ) ;
      Serial.print( "\tinterval= " ) ;
      Serial.print( intervalRead[ i ].durationUs ) ;
      Serial.print( "us  \t") ;
      Serial.print( intervalRead[ i ].space ? "space" : "pulse" ) ;
      Serial.println( ) ;
    }
    Serial.println( ) ;
    firstPulse = true ;
  }
}

```


body:
I am using the [ESP32 Arduino Framework](https://github.com/espressif/arduino-esp32) and I have some [GPIO expanders](https://www.ti.com/product/TCA6408A) attached via I²C. They work fine and I now want to map some unused pin numbers to them so I can used my custom pin numbers in `pinMode`, `digitalRead` and `digitalWrite`.

Luckily, [the Arduino core links these functions weakly](https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/esp32-hal-gpio.c#L228).

```c++
extern void pinMode(uint8_t pin, uint8_t mode) __attribute__ ((weak, alias("__pinMode")));
```

I defined my own functions like so:
```c++
void pinMode(uint8_t pin, uint8_t mode) {
    if(pin<0x80)
        // call conventional handler
    else
        // communicate with GPIO expander via I²C
}
```

Unfortunately, calling any of the functions will not result in the linker picking my implementation but the linker picks the default implementation.

Any ideas how to override the weakly linked `pinMode`, `digitalWrite` and `digitalRead`?

title: override pinMode, digitalWrite and digitalRead

Answers: 1

body:
I found the issue: I ran `platformio run --target clean` instead of `platformio run --target cleanall`. It seems that only the latter command cleans all build artifacts. The next time I compiled and uploaded, it worked as expected.

Another issue occurs only with Adafruit libraries: Some libraries do not use `uint8_t` for ports but `int8_t` and they do checks like
```c++
if(pin_number >=0)  {
    // code that only works with pin numbers between 0x01 and 0x80
}
```
Take the [Adafruit GFX library](https://github.com/adafruit/Adafruit-GFX-Library/blob/5ea4be3ffeae918899aeec8cbb67f87359cf0026/Adafruit_SPITFT.cpp#L533) as an example. As a workaround, I will map my GPIO expander ports to 0x40, 0x41, ...


body:
I'm using an arduino uno with two DC motors. I'm also using the built in LED to tell me when the motors should be on as a debug tool. The code is a simple while loop that turns both the motors and the LED on for 10 seconds, and off for 5, and repeat, while a witch is on. This works fine when the motors are not connected to power (when the switch is on, the LED turns on for 10 secs, off for 5 and repeat), but when the motor driver is connected to the power the timing is changed. The motors and the LED are on for less than a second, and off for 5. the "on" period changes a bit, once it even reached the intended 10 seconds.

Why is that and how do I fix that? I tried changing batteries (though i don't know how that might change things, as the led is also working incorrectly and it works of a seperate power source).

the Arduino is connected to a 9V battery and the motors are connected to 4 AA batteries through a L298N motor driver.

this is my code:
```
#include <Arduino.h>
int RightSpeedPin = 5;
int Rdir2 = 6;
int Rdir1 = 7;
int led = 13;
int LeftSpeedPin = 10;
int Ldir2 = 8;
int Ldir1 = 9;
int SwitchPin = 4;
int ReadVal;
void setup() {
  // put your setup code here, to run once:
  pinMode(Rdir1, OUTPUT);
  pinMode(Rdir2, OUTPUT);
  pinMode(RightSpeedPin, OUTPUT);
  pinMode(LeftSpeedPin, OUTPUT);
  pinMode(Ldir1, OUTPUT);
  pinMode(Ldir2, OUTPUT);
  pinMode(SwitchPin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  ReadVal = digitalRead(SwitchPin);
  while (ReadVal == 1)
  {
    digitalWrite(led, HIGH);
  // starting situation- both motors heading forward
    // running for 10 secs
    digitalWrite(Rdir1, HIGH);
    digitalWrite(Ldir1, HIGH);
    digitalWrite(Rdir2, LOW);
    digitalWrite(Ldir2, LOW);
    analogWrite(RightSpeedPin, 255);
    analogWrite(LeftSpeedPin, 255);
    delay(10000);
    // off for 5
    analogWrite(RightSpeedPin, 0);
    analogWrite(LeftSpeedPin, 0);
    digitalWrite(led, LOW);
    ReadVal = digitalRead(SwitchPin);
    delay(5000);
  }
}
```
[link to the schematics][1]. its rough, I'm not very experienced at drawing schematics. Note that all the ground wires are connected to a breadboard ground rail other that the 9V that powers the arduino. its connected with a round plug, so i don't have individual wires.
EDIT: fixed the schematic
[![circuit][2]][2]

  [1]: https://crcit.net/c/58642dd9da3d41948a9847bb69c874b9
  [2]: https://i.stack.imgur.com/eBwSk.png

title: timing changes once DC motors are connected to power

Answers: 1

body:
After debugging by printing:

    sTime = millis();
    analogWrite(RightSpeedPin, 255);
    analogWrite(LeftSpeedPin, 255);
    delay(5000);
    analogWrite(RightSpeedPin, 0);
    analogWrite(LeftSpeedPin, 0);
    Serial.print(millis() - stime);

I got times that are less than 300 ms, and no reset (added print to setup). I still have no idea why.
after that, I just replaced delay with `while (millis() < Stime + t) {` which solved my problem.


body:
I'm using an ESP8266-01S for a battery-powered project. The ESP is in DeepSleep, a doorbell relay pulls RST to GND, bringing the ESP to life to do some stuff, before going back to DeepSleep.

My problem is that once the program ran successfully and the ESP is in DeepSleep, the next RST will not bring it up properly. Instead, it will linger in some undefined state, eating around 33.7mA constantly (I went through that battery quite quickly without realizing it).

With serial output enabled, I reliably get something like this when entering those undefined states:

`rll�r$�n�l�b|���rb�b�nnlnnbbp�$blrl`

Edit: setting the Baud rate to 74880 revealed the above to be the following:

    11:58:17.042 -> �
    11:58:17.042 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)
    11:58:17.042 ->

The next RST will then perform successfully, i.e. the ESP comes up, does its thing and goes into DeepSleep. My multi meter shows a power consumption of roughly 15uA, which looks like proper DeepSleep to me.

Another RST would then bring the ESP back into the undefined state, and so on.

Cutting power provokes the same behaviour, so it feels like it could be a hardware thing, some lingering current or something.

I created a minimal version of my program that shows the behaviour on the ESP:
```
int Led = LED_BUILTIN;

void setup() {
  pinMode(Led, OUTPUT);
}

void loop() {

  digitalWrite(Led, false);
  delay(4000);// Delay 4 seconds
  digitalWrite(Led, true);
  delay(1000);// Delay 1 second

  ESP.deepSleep(0);
}
```

Is there anything I'm missing or doing wrong, maybe something on the hardware side, to make DeepSleep work on an ESP8266-01S? Do the pins have to be initialized or brought in a defined state somehow? Also, is there a better way than Serial Output to figure out what's going on?

I believe I don't have to [connect GPIO16 to RST](https://arduino.stackexchange.com/a/52305/8337), since I don't want to wake the ESP by software, but through hardware events only.

Edit: I left the device in DeepSleep over night and RSTed it in the morning, and this time it recovered fine for once.

title: ESP8266-01S only coming back from DeepSleep every 2nd time

Answers: 0


body:
I have tested the library and LCD with simple script and everything worked fine. Now I am trying to add the LCD functionality to my working program but the code reaches the lcd.begin(); function it causes a runtime error and no following lines are executed. I have tried many different configurations and none of them have worked; including have lcd.begin() in the setup(), in the InitSM(), loop(), and RunSM() and it crashes every time.

I am wondering if I am running into a similar issue described [here][1].

Following thebusybee's advice, I started with a simple working script that could print to the LCD screen. I then started adding initializing functions in the setup until it stopped working. `InitSM(&AFC);` is the line that causes the LCD functions to stop working. `InitSM(&AFC);` calls millis(), enables watchdog timer interrupts, and external interrupt on digital pin 2. Below is the exam code.

```
// Library
#include <Arduino.h>
#include <EventTimers.h>
#include <EventCheckers.h>
#include <avr/sleep.h>
#include <Timeout.h>
#include <AFCSM.h>
#include <DoorServo.h>
#include <EventTypes.h>
#include <HardwareInterrupts.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);
//LiquidCrystal_I2C *lcdA; //0x27,20,4
//lcdA = &lcd;
//lcdA->begin();

// global variables
static uint8_t TimerCheck = 0;
static uint8_t Timer30;
static EventType LCDButton;
static EventType BatteryEvents;
static EventType BumperEvents;
static EventType FogEvents;
static EventType CurrentEvent;
static EventType FrontDoor;
static EventType BackDoor;
static AFCDATA AFC;
static AFCState PreviousState;

void setup() {
  // set up serial communication with computer
  Serial.begin(9600);

  // uart for MiniOFS to MCU
  Serial1.begin(1200, SERIAL_8N1);

  /*** set up interrupts, not init ***/
  SetUpWatchdogT(); // 8sec interrval counter for 32sec environ sensor check
  SetUpButtonInt(); // external button interrupt for LCD screen

  // init LCD
  lcd.begin();

  // Enable interrupts
  sei();

  // Set the sleep mode to Power-Down
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  // initi doors
  initDoor();

  // init statemachine
  InitSM(&AFC);
  PreviousState = AFC.State;
}

void loop() {
  Serial.flush();

  lcd.clear();
  // lcd.setCursor(2,0);   //Set cursor to character 2 on line 0
  lcd.print("LED INIT!");
  Serial.println("printed");
}

ISR(WDT_vect) {
  // Add to timer
  TimerCheck += 1;

  // check if 30secs have elapsed time has
  if (TimerCheck >= 3){
    TimerCheck = 0; // reset counter
    Timer30 = true; // raise flag
  }

}

void Buttonisr(){
  // Button Flag
  LCDButton = BUTTON_ON;
}
```

I narrowed it down to being the external interrupt enable on digital pin 2. Below are the functions for the setup and enable of the external interrupt.
```
void SetUpButtonInt(){

    // set up the pin as an input and attach a isr
    pinMode(ButtonPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(ButtonPin), Buttonisr, RISING); // interrupt on rising edge of pin

    return;
}

void EnableButtonInt(){

    EIMSK |= (1 << INT0); // enable external interrupt
    Serial.println("enable external interrupt");
    return;
}
```

How can this setup affect the lcd I2C setup?

  [1]: https://arduino.stackexchange.com/questions/23168/library-liquidcrystal-i2c-dont-work-in-other-class-composition
  [2]: https://i.stack.imgur.com/iYaR4.png

title: LiquidCrystal_I2C, lcd.begin() causes runtime error on Arduino Mega2560

Answers: 0