body:
SSD1306 OLED display connected to an ESP32-S2 over hardware I2C. I noticed that the text will sometimes get scrambled or lag during a screen update. When left running long enough, the screen will get stuck and stop updating, despite serial monitor continuing to function. Does anyone know how to fix this? Here is a video of the laggy behavior: https://youtu.be/9OYW00cE24U
[![128x32 SSD1306 OLED scrambled text][1]][1]

    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    unsigned long drawState = 1;
    unsigned long previousTime = 0;
    unsigned long eventInterval = 4000;

    #define OLED_ADDR 0x3C
    #define SCREEN_WIDTH 128
    #define SCREEN_HEIGHT 32
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

    void setup() {
      Serial.begin(115200);
      Wire.setClock(400000);
      if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        Serial.println(F("SSD1306 allocation failed"));
        for (;;)
          ;
      }
    }

    int screenSwitchLast = millis();

    void loop() {

      if (millis() - screenSwitchLast >= eventInterval) {
        screenSwitchLast = millis();

        switch (drawState) {
          case 1:
            drawTemp(); //draw Temperature
            break;
          case 2:
            drawHum(); //draw Humidity
            break;
        }

        drawState++;
        if (drawState > 2) {
          drawState = 1;
        }
      }
    }

    void drawTemp() {
      Serial.print("Temp ");
      Serial.println(millis());
      display.clearDisplay();
      display.setTextSize(2);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(0, 12);
      display.print("Temp: ");
      display.print("10");
      display.print("F");
      display.display();
      delay(1);
    }

    void drawHum() {
      Serial.print("Hum ");
      Serial.println(millis());
      display.clearDisplay();
      display.setTextSize(2);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(0, 12);
      display.print("Hum: ");
      display.print("20");
      display.print("%");
      display.display();
      delay(1);
    }

I saw **[this post][2]** which recommends running screen update code on the second core but the ESP32-S2 only has 1 core. I'm at odds with how I'd get this to work reliably on a single core ESP32.

    Board: Adafruit ESP32-S2 Feather- 4M Flash and 2M PSRAM
    Display: 128x32 12C OLED - Ox3C

    Arduino Settings:
       - USB CDC on Boot: Enabled
       - CPU Frequency: 240mHz (WiFi)
       - Core Debug Level: None
       - USB DFU on Boot: Disabled
       - Erase All Flash Before Sketch Upload: Disabled
       - Flash Frequency: 80mHz
       - Flash Mode: QIO
       - Flash Size: 4MB (32Mb)
       - USB Firmware MSC on Boot: Disabled
       - Partition Scheme: Minimal SPIFFS 1.9MB APP with OTA/190KB SPIFFS
       - PSRAM: Enabled
       - Upload Mode: Internal USB
       - Upload Speed: 921600

  [1]: https://i.stack.imgur.com/xGYV9.jpg
  [2]: https://arduino.stackexchange.com/questions/83513/why-ssd1306-oled-display-get-scrambled-text-when-printing-messages-from-separate

title: Scrambled Text on SSD1306 Using ESP32-S2

Answers: 0


body:
Kindly seek help. In my project I want to ‘fake’ a smart meter via Modbus rtu server for a solis inverter.

Somehow the solis realizes that I am faking him, so I am wondering which Modbus rtu server library you can recommend to allow me seeing what registers the solis is querying?
As of now I am using Emilianov Modbus-8266 library to run the rtu server/slave and platform is an esp32 with max3485.

---

 So let me elaborate. Mine Solis simply sucks during low-light conditions. It can not decide if it shall charge or discharge, resulting in heavy oscialltion, jumping from feeding to much into grid and then taking to much from grid - peaks are ranging from +800Watt to -800Watt when it starts oscillating.

On the com-port you are true - here the solis acts as slave. But on its RS485 meter-port I understand the Solis acts as master and the smart meter is the slave.

My goal is to fake the smart-meter.

So topology would be:

Solis(master)-----(slave)ESP32(master)-----(slave)smartmeter

So I am looking for a solution that any read-request from the Solis is transparently passed-through to the smart-meter. But I want one register intercpeted (most likely total-active-power, which to mine understanding is the only value the solis want to bring back to zero in its control-loop).

As of now I can read the Solis and ther Seplos BMS via ESP32/RS485 successfully. I even have a running slave which I thought shall be good enough to get accpeted as fake-smart-meter, but it is not. The solis is asking for more register then my fake-solution is providing. hence mine ask, which ESP32 slave/server modbus library can print any request its arriving.

If my view is incorrect, kindly get me corrected.

title: Modbus rtu server library which logs the requests

Answers: 1

body:
Try looking at this as a starting point

https://github.com/straga/Smart-Meter-Gateway

My approach has been different but will come back to this if my current approach fails.


body:
I'm trying to program an Arduino Nano 33 BLE bare-metal to get some precise timing and size measurements. I've managed to upload the code to my card, but I cannot communicate with it. More specifically, when I upload the code, the port 'deactivates' after I upload the code, so the serial monitor prints a `cannot exec '/dev/ttyACM0'` error.

Can someone help me figure out how to make it work? I've seen tutorials online but they're for AVR microcontrollers, and I've been told that this specific board isn't. I've also been told that I must include some code in my `c/cpp` file to produce a USB CDC serial port, but I don't know how to do that.

title: How to produce a USB CDC serial port for Arduino nano 33 BLE?

Answers: 1

body:
The [Nano 33 BLE board][1] uses a [NORDIC nRF52840 processor][2] which contains the USB interface hardware inside the processor. The current Arduino Uno uses an Atmel (now owned by Microchip) processor and uses an external processor for USB communications. So any Arduino USB tutorial will be very different with respect to these two Arduino designs.

Normally, Arduino Sketches (Programs) are only part of all the software running on a processor. The preprogrammed software on a new Arduino board abstracts the more complex part of embedded programming from the average Arduino user. This likely includes a working USB port.

To do [bare metal programming][3] on a NORDIC nRF52840 processor, consider starting with the [NORDIC Software Development Kit (SDK)][4]. Also, most vendors support their own development boards (provide example programs and libraries) better then development boards made else where.  Consider this before committing to learning how to bring up a "bear metal" USB/CDC peripheral device using the Nano 33 BLE board.

An alternative approach: Many ports of Arduino occur on github.com.  The adaptation of the Arduino code may offer insights as to how the host processor's hardware works. The Nano 33 BLE preprogrammed software comes from [this github repository][5].

  [1]: https://content.arduino.cc/assets/NANO33BLE_V4.0_sch.pdf
  [2]: https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf
  [3]: https://en.wikipedia.org/wiki/Bare_machine
  [4]: https://www.nordicsemi.com/Products/Development-software/nRF5-SDK
  [5]: https://github.com/arduino/ArduinoCore-mbed


body:
i have a project where i read two analogue inputs from two sensors and a pro Mini. I have some spikes in my readings that are present when i'm powering the system using a powerbank step-up module. When i use a 7805 and a 9V battery, the results seem clear. The spikes appear every 600-650ms.

Is there any way to filter them out on a hardware level without using code?

The frequency of the spikes is about 1.5HZ, too slow for a typical ripple of a "dirty" dc converter i think.
My first though was that the module was checking for sufficient load to stay powered on. I added a dummy load but nothing changed. The project is a datalogger and unfortunately i don't really want the code to do the filtering, as it's gonna cost me some speed.

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

  [1]: https://i.stack.imgur.com/MOjkt.jpg
  [2]: https://i.stack.imgur.com/pDiU1.jpg

title: Analogue input spikes

Answers: 1

body: On a hardware level, without a substantial delay, you could use active filters, such as active low-pass or band-pass filters, that can provide better control and customization over the filtering process.


body:
I am interested in hooking up a nano to an RC receiver. I want the nano to mirror the PWM input and output on another pin when a specific command is given via serial. I also want to send the received command via serial to a computer(Pi or Jetson) at the same update rate.

I can run pin change interrupt on the input pins to basically enable/disable the pins but I'm wondering if there is a better way.

I also will be updating a motor encoder at pin change interrupt, I'm guessing around 4k interrupts/second.

Do you think the Nano provides enough juice or I should use a Pico?

title: Mirroring PWM input on a pin + Motor Encoder

Answers: 0


body:
Working on a project where I get an input where its a comma delimited string like:
```
"255,10000000,42949672950254,12,22".
```
and then the numbers (no commas), would be split into 6 Long variables
like
```
var1 = 255
var2 = 10000000
...
```
I wanted a function like this:

```
void extractIntegersFromString(String str, int& integer1, int& integer2, int& integer3, int& integer4, int& integer5, int& integer6, int& integer7) {
  int count = 0;
  String temp = "";

  for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);

    if (c == ',') {
      if (count == 0)
        integer1 = String(temp).toInt();
      else if (count == 1)
        integer2 = String(temp).toInt();
      else if (count == 2)
        integer3 = String(temp).toInt();
      else if (count == 3)
        integer4 = String(temp).toInt();
      else if (count == 4)
        integer5 = String(temp).toInt();
      else if (count == 5)
        integer6 = String(temp).toInt();
      else if (count == 6)
        integer7 = String(temp).toInt();

      count++;
      temp = "";
    } else if (c >= '0' && c <= '9') {
      temp += c;
    }
  }

  // Store the last integer if the string doesn't end with a comma
  if (temp != "") {
    if (count == 0)
      integer1 = String(temp).toInt();
    else if (count == 1)
      integer2 = String(temp).toInt();
    else if (count == 2)
      integer3 = String(temp).toInt();
    else if (count == 3)
      integer4 = String(temp).toInt();
    else if (count == 4)
      integer5 = String(temp).toInt();
    else if (count == 5)
      integer6 = String(temp).toInt();
    else if (count == 6)
      integer7 = String(temp).toInt();
  }
}
```
This function makes it work through ints, but I need the larger size of a Long.

P.S. I've tried the `atol()` function (and similar others), but that didn't work...

title: converting comma delimited Serial message to 7 Unsigned Long variables

Answers: 2

body:
String.toInt actually returns a long. See the code:

    long String::toInt(void) const
    {
     if (buffer) return atol(buffer);
     return 0;
    }

---

> I've tried the atol() function (and similar others), but that didn't work

Please post your "try", don't just say that you did it. Maybe you did it incorrectly.

---

Re your entire technique: There is a function [strtok](https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm) that is specifically designed to break up a string into substrings at a delimiter. You could use that rather than re-inventing the wheel.

However that doesn't solve your specific problem of converting the substrings into a long.

body:
First of all, it is worth noting that the third number in you example
message (100000000000, i.e. 1011) is too large to fit in an
`unsigned long`. On AVR-based Arduinos, and most non-64-bit platforms,
an `unsigned long` is 32-bits wide and can only hold numbers up to
4294967295 (about 4.3×109). I do not know of any easy way to
parse such a large number on AVR.

That being said, for parsing this kind of string into `unsigned long`
numbers, I would recommend the [`strtoul()` function][strtoul]. Compared
to `atol()`, it has the benefit that it tells you where the number it
read ended, so you know where to search for the next one: it saves you a
call to `strchr()`. It also allows some error-checking, so you know
whether the message does conform to the expected format.

Here is a tentative implementation:

```c++
/*
 * Parse up to `count` numeric values from `message`,
 * which must be in comma-separated-values format.
 *
 * Return the number of values successfully parsed.
 */
int parse_message(const char *message,
                  unsigned long *values, int count) {
    for (int i = 0; i < count; i++) {
        char *end;  // pointer to next non-digit
        values[i] = strtoul(message, &end, 10);
        if (end == message) return i;  // parsing failed
        if (*end == ',') end++;        // skip comma
        message = end;                 // move to the next field
    }
    return count;
}
```

And a small test sketch:

```c++
void setup() {
    Serial.begin(9600);

    unsigned long values[7];
    int count = parse_message("255,10000000,100000000000,0,255,12,22",
            values, 7);
    Serial.print(count);
    Serial.println(" numbers successfully parsed:");
    for (int i = 0; i < count; i++)
        Serial.println(values[i]);
}

void loop() {}
```

[strtoul]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaea44aa48bda8261f794dcb2d1e7ab2b2


body:
I'm trying to plot the value of the pwm that increases (every 2 sec) then decreases to compare it to the value of an encoder. I was expecting a continued value (like a step ) during 2 seconds but instead I have a triangle signal.
Here is my code
```
const int pwmG = 2;
const int DirG = 8 ;
int a =0;

#define encoder1_CHA 18  //Left encoder
#define pin_channelB_left 6
int b =0;

void setup() {
  Serial.begin(9600);
  pinMode(pwmG,OUTPUT) ;
  pinMode(DirG,OUTPUT) ;
  attachInterrupt(digitalPinToInterrupt(encoder1_CHA),interruptUp,RISING);

  }

void interruptUp(){
  b = !b;

}

void loop() {
  Serial.println(b);
  //Serial.print(" ");
  pwm();

  //Serial.println(a);

  //Serial.println(b);
}

void pwm(){
   for (int i =0; i< 10; i++){
      a = a +5;
      analogWrite(pwmG, a);

      Serial.println(a);
      delay(200);
      }
      //Serial.println(b);

  for (int i =0; i< 10; i++){
    a = a -5;
    analogWrite(pwmG, a);

    Serial.println(a);
    delay(200);
  }
}
```
What I have :

[![][1]][1]

What I expected (exemple found on the internet :
[![What I expected (exemple found on the internet][2]][2]

  [1]: https://i.stack.imgur.com/7NWhO.png
  [2]: https://i.stack.imgur.com/8pept.png

title: Serial plotting a pwm

Answers: 1

body:
The first point here is, that the Serial Plotter will plot the values against time by connecting them with a straight line. This is just how it represents the data in the plot (it is just for ad-hoc visualization, not for detailed plotting and data analysis).

The second point is, that for each step you are sending only one value through the Serial interface, so only one data point per step. The Serial Plotter then plots this data point against time and connects it with the points for the other steps with a straight line. Thus you get sloped lines/triangle signal in the Serial Plotter.

The image, that you expected, looks like from an oscilloscope. This will have many more data points along the x-axis, not just one per step. Thus you can actually see the steps. If you want to reproduce the image with your code, then you can send the current value of `a` more often in each iteration of the for loop (like looping 20 times over sending the value and delaying about 10ms).


body:
I am building a very simple battery powered touch button using a Wemos D1 Mini (it is basically an ESP8266) and a capacitive touch sensor (something like this: https://www.az-delivery.de/en/products/touch-sensor-modul-1).

Since it is battery powered, I need to reduce as much as possible to consumption of the Wemos D1 Mini. I learnt that, in order to obtain minimum power consumption, we need to use the deep sleep mode. In order to do that, we need to connect RST to D0 (being D0 the WAKE PIN) and program the device accordingly.

My question is: will the Wemos D1 Mini wake up when the touch button is activated (aka: when PIN D1 is pulled up)?

---

Could this be the solution? I could use this as a switch to reset the Wemos D1 Mini and program it to send certain instructions when woken up.

https://youtube.com/watch?v=ojcwgxWMAo8

title: Wemos D1 Mini deep sleep

Answers: 0


body:
I'm using arduino-cli to program an ESP32-S2.  If I compile my sketch using the default partition scheme

```
> arduino-cli compile -b esp32:esp32:esp32s2 sketch
```

a lot of space is allocated for SPIFFS and OTA, which I don't use.

```
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.
```

Thus. I'd like to use the `huge_app` scheme, as defined in the boards.txt:

```
esp32s2.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32s2.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32s2.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
```

However, selecting it doesn't have any effect:

```
> arduino-cli compile -b esp32:esp32:esp32s2 sketch --build-property build.partitions=huge_app
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.
```

Is my command line incorrect?  Why is arduino-cli not using the specified partition scheme?

title: How to change partition scheme with arduino-cli

Answers: 1

body:
So, it turns out I have to add another build property:

```
> arduino-cli compile --build-property build.partitions=huge_app --build-property upload.maximum_size=3145728 sketch
```

where the `upload.maximum.size` is from the `boards.txt` file.  Indeed, a maze of twisty little files, all alike.


body:
I'm working on a TinyML project with an Arduino Nicla Vision and I need to store a model with size 608kB in RAM. In the Nicla Vision datasheet, it is stated that 864kB of SRAM are available, but it is segmented in three non contiguous parts (AXI SRAM, SRAM1-3, SRAM4).
[![enter image description here][1]][1]

When I try to load the model in RAM, I get the error 'linker_script.ld:110 cannot move location counter backwards (from 240aa610 to 2407fc00)' because only the AXI SRAM (524kB) is used.

Is there a way to distribute the model over all the available non contiguous RAM?

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

title: Access non contiguous RAM slots in Arduino Nicla Vision

Answers: 0


body:
For context, my first board would contain a motor circuit with an L298N motor driver while my second contains a controlled heating system that uses 2 relays with PTC heating elements, DHT11 sensor, I2C LCD display, and 1 12V exhaust fan.

My input would be a 12V DC power adapter and I'm going to use it to run the motor, the fan, and the 2 heating elements.

Since I want to minimize the chances of my boards from overheating, I want to reduce the input voltage for my board to around 7V, so I want to integrate a voltage regulator circuit.

Should I include 2 voltage regulator circuits or should just utilize 1 for both boards?

title: I'm planning on using 2 arduino boards for my project. Should I use 2 voltage regulators for project or use 1 for both?

Answers: 2

body:
If you want an external voltage regulator, one should be plenty. In that case I would regulate down to 5V (not 7V) and connect that to the 5V pin on the board.

An alternative might be to just run the 12V from the battery through a diode or two, thus dropping 0.7V for each diode. Use a diode that can handle a reasonable amount of current, eg. 1N4004. Then you would still connect it to the normal "power input" socket (not the 5V pin).

I assume that the heating, motors, etc., are not being powered by the Arduino board, but directly from the battery via some sort of switching, like a MOSFET or a relay.

body:
I would use a buck or SEPIC regulator and feed Vin on each of the Arduino with about 7.5V from the one regulator. I prefer using Vin because of the additional filtering I get. Also be sure you are using appropriate drivers for your loads, such as relays or MOSFETs.

Consider replacing the L298N with a newer part, that will lose about 3V on the motor leads which is burnt up as heat in the device. There are many others that use MOSFET outputs which will drop less them 0.2 volts.


body:
I'm using an Arduino Nano 33 BLE and a L293D motor driver to control a three-wheeled RC robot. The sketch I'm using worked fine with my Uno Rev3, but I've moved to the Nano for size/weight reasons, and it's no longer working. Whenever I turn the power on, the motor I'm using to test spins clockwise at what appears to be full-speed, without considering the receiver's signal at all. I actually removed the wires from the receiver and the motor just kept on spinning.

I tried looking at the serial plotter, but it appears that the Nano is disconnecting itself from my laptop whenever I turn the RC transmitter on, so I haven't been able to get any information that way.

I've troubleshooted to the best of my limited ability, and the problem seems to be with the Nano not processing the signals from the receiver. Beyond that, though, I don't have the first clue what the root of the problem is. I'm pretty new to Arduino & coding haha.

I followed [this YouTube tutorial][1] for the process of reading the RC values, and the variables with color names are referring to the motors. Here's the sketch:

    //set the port speed for host communication
    #define SERIAL_PORT_SPEED 115200

    #include <math.h>
    #define RC_NUM_CHANNELS 2
    #define RC_CH1 0 //right stick LR
    #define RC_CH2 1 //right stick UD
    #define RC_CH1_INPUT 2 //pin 2 on arduino
    #define RC_CH2_INPUT 3 //pin 3 on arduino

    // Set up some arrays to store our pulse starts and widths
    uint16_t RC_VALUES[RC_NUM_CHANNELS];
    uint32_t RC_START[RC_NUM_CHANNELS];
    volatile uint16_t RC_SHARED[RC_NUM_CHANNELS];

    const int enable_pink = 13; //pin that enables pink motor
    const int enable_blue = 12;
    const int enable_yellow = 11;

    int dead_zone = 10; //within 10 of 0, motor will not move
    const int error_pin = 4; //this lights up when something unexpected happens
    int UD;
    int RL;
    double pi = 3.1415926;

    int pink; // analog value out of 255 for the pink motor
    const int pink_cw = 5; // pin that signals pink motor to move clockwise
    const int pink_ccw = 6; //pin signals counterclockwise
    int blue;
    const int blue_cw = 7;
    const int blue_ccw = 8;
    int yellow;
    const int yellow_cw = 9;
    const int yellow_ccw = 10;

    void setup() {
      // set the speed to communicate with the host PC:
      Serial.begin(SERIAL_PORT_SPEED);

      //set pin modes to input for reciever
      pinMode(RC_CH1_INPUT, INPUT);
      pinMode(RC_CH2_INPUT, INPUT);
      //attach interrupts to these pins
      attachInterrupt(digitalPinToInterrupt(RC_CH1_INPUT), READ_RC1, CHANGE);
      attachInterrupt(digitalPinToInterrupt(RC_CH2_INPUT), READ_RC2, CHANGE);
      //set pin mode for error pin
      pinMode(error_pin, OUTPUT);

      //set all green wires (motor-enabling wires) to OUTPUT
      pinMode(enable_pink, OUTPUT);
      pinMode(enable_blue, OUTPUT);
      pinMode(enable_yellow, OUTPUT);

      //set all motor signal outputs to OUTPUT
      pinMode(pink_cw, OUTPUT);
      pinMode(pink_ccw, OUTPUT);
      pinMode(blue_cw, OUTPUT);
      pinMode(blue_ccw, OUTPUT);
      pinMode(yellow_cw, OUTPUT);
      pinMode(yellow_ccw, OUTPUT);

      //enable all motors
      digitalWrite(enable_pink, HIGH);
      digitalWrite(enable_blue, HIGH);
      digitalWrite(enable_yellow, HIGH);

    }

    void loop() {
      // read the values from our RC reciever
      rc_read_values();

      //map RC values to analog scale
      UD = map(RC_VALUES[RC_CH1], 800, 2200, -100, 100);
      RL = map(RC_VALUES[RC_CH2], 800, 2200, -100, 100);

      //output raw RC input to serial plotter
      Serial.print(UD); Serial.print(",");
      Serial.println(RL);

      //do the math to calculate wheel vectors
      pink = RL;
      blue = (UD/(cos(pi/3))) + (RL/(sin(pi/3)));
      yellow = -(UD/(cos(pi/3))) - (RL/(sin(pi/3)));

      //now map the wheel vectors to analog scale:
      blue = map(blue, -800, 800, -255, 255);
      yellow = map(yellow, -800, 800, -255, 255);

      //now, output each value to each motor
      set_color(pink, pink_cw, pink_ccw);
      set_color(blue, blue_cw, blue_ccw);
      set_color(yellow, yellow_cw, yellow_ccw);

      //output pink blue and yellow values to serial plotter:
      Serial.print(pink); Serial.print(",");
      Serial.print(blue); Serial.print(",");
      Serial.println(yellow);

    }

    //create function to give the signals to the motors
    void set_color(int color, int color_cw, int color_ccw) {
      if (color > dead_zone) {
        analogWrite(color_cw, color);
      } else if (color <-(dead_zone)) {
        analogWrite(color_ccw, abs(color));
      } else if (color <= dead_zone && color >= -(dead_zone)) {
        return;
      } else {
        digitalWrite(error_pin, HIGH);
      }
    }

    // These functions are called by the interrupts. We send them all to the same place to measure the pulse width
    void READ_RC1() {
       Read_Input(RC_CH1, RC_CH1_INPUT);
    }
    void READ_RC2() {
       Read_Input(RC_CH2, RC_CH2_INPUT);
    }

    // This function reads the pulse starts and uses the time between rise and fall to set the value for pulse width
    void Read_Input(uint8_t channel, uint8_t input_pin) {
      if (digitalRead(input_pin) == HIGH) {
        RC_START[channel] = micros();
      } else {
        uint16_t rc_compare = (uint16_t)(micros() - RC_START[channel]);
        RC_SHARED[channel] = rc_compare;
      }
    }

    // this function pulls the current values from our pulse arrays for us to use.
    void rc_read_values() {
      noInterrupts();
      memcpy(RC_VALUES, (const void *)RC_SHARED, sizeof(RC_SHARED));
      interrupts();
    }

any help would be greatly appreciated, I'm truly stumped here

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

title: nano 33 BLE problems with reading RC signal

Answers: 0


body:
I've been setting up a system using an Arduino Uno board that reads from both an Adafruit MPU6050 6-way gyroscope and accelerometer and an Adafruit NAU7802 connected to a load sensor. I have code for that working, but I would also like to connect an Adafruit FeatherWing OLED to display the results.

Since this is the first time I've used Arduino or any of these parts, I first wrote a sketch to output the readings from my sensors into the serial monitor and a separate sketch to experiment with the display. However, when I try to use the code from the display sketch with my sensor reading script, it completely breaks the working sensor script.

My void setup code for my sensors looks like:
```
#include <Adafruit_MPU6050.h>
#include <Adafruit_NAU7802.h>

Adafruit_MPU6050 mpu;
Adafruit_NAU7802 nau;

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

  Serial.println("\n\nstart test\n");
  delay(10);

  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    } else {
      Serial.println("MPU6050 Found!");
    }
  if (!nau.begin()) {
    Serial.println("Failed to find NAU7802");
    } else {
      Serial.println("NAU7802 Found!");
    }
```

I then tried to add a few lines to power up the display:
```
#include <Wire.h> //for I2C
#include <Adafruit_MPU6050.h> //for 6-way
#include <Adafruit_NAU7802.h> //for ADC
#include <Adafruit_GFX.h> //for display
#include <Adafruit_SH110X.h> //for display

Adafruit_MPU6050 mpu;
Adafruit_NAU7802 nau;
Adafruit_SH1107 display = Adafruit_SH1107(64, 128, &Wire);

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

  Serial.println("\n\nstart test\n");

  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    } else {
      Serial.println("MPU6050 Found!");
    }
  if (!nau.begin()) {
    Serial.println("Failed to find NAU7802");
    } else {
      Serial.println("NAU7802 Found!");
    }

  delay(200); //allows OLED to power up
  display.begin(0x3C, true); // Address 0x3C default
  display.display();
  delay(1000);

  display.clearDisplay();
  display.display();

}
```

Does not turn on the display, but instead causes all of the code in the setup before the display.begin() function is called to loop indefinitely (even though it's not even in the loop part of the sketch.)

I have no idea what is going on here, and any advice would be appreciated! Thank you!

EDIT: Thank you so much for all of the comments! I will try to answer the questions as best as I can here.

I was only powering the device through the USB port. Based on your suggestions, I tried the script again using 9V through the barrel jack to power the device, but it, unfortunately, didn't fix the issue.

I tried reversing the dimensions in the `Adafruit_SH1107(64, 128, &Wire)` function, but that also didn't change anything. Also, all of my libraries are up to date as far as I can tell.

Both the OLED and the sensors successfully run independently while both are attached to the circuit. So -- I can get the OLED to display something while the sensors are attached to the circuit, and I can get the sensors to read into the serial monitor while the display is attached to the circuit. The problem arises when I try to have all of the parts called in the same script.

Here's a picture of the circuit: [![picture of an arduino connected to multiple small sensors, all taped to a cardboard tray][1]][1]

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

Thank you all again for your help!

title: display.begin(); function breaks working code

Answers: 0


body:
I am making a cansat which will be launched on a sugar rocket. The cansat's Arduino nano will be operating sensors which will read the data and store it in an sd card and also a servo to deploy the parachute.

The problem is that I am not able to make code where I want all the sensors to be logging data in the sd card in a loop and a mini servo should perform a sweep angle of 90 degrees after 2 minutes of power supply to the Arduino.

I have made the code for sensors inputting data into sd card but the servo part is confusing me due to no possibility of putting servo code in void setup as the setup will first do the servo sweep after 2 minutes and then record data, neither can I put it in the loop as that also records the data after 2 minutes and I tried to put that into a new function but that's also not working.

Please give me a solution for this.
The code that I have made is below : ( just for sensors logging data in sd card )

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP085_U.h>
    #include <DHT.h>
    #include <SD.h>

    #define DHTPIN 10
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

    Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

    const int MQ2 = A0;

    File dataFile;

    void setup() {
      Serial.begin(9600);
      dht.begin();
      if (!bmp.begin()) {
        Serial.println("Could not find a valid BMP085 sensor, check wiring!");
        while (1) {}
      }
      if (!SD.begin(4)) {
        Serial.println("SD card initialization failed!");
        while (1) {}
      }
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile) {
        dataFile.println("Temperature, Humidity, Pressure, Gas");
        dataFile.close();
      } else {
        Serial.println("Error opening data file!");
      }
    }

    void loop() {
      float temperature = dht.readTemperature();
      float humidity = dht.readHumidity();
      sensors_event_t event;
      bmp.getEvent(&event);
      float pressure = event.pressure;
      float gas = analogRead(MQ2);
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile) {
        dataFile.print(temperature);
        dataFile.print(",");
        dataFile.print(humidity);
        dataFile.print(",");
        dataFile.print(pressure);
        dataFile.print(",");
        dataFile.println(gas);
        dataFile.close();
      } else {
        Serial.println("Error opening data file!");
      }
      delay(1000);
    }

title: Making a servo work for just once after a specific time period without hindering the sensors that are reading the data in a loop

Answers: 1

body:
I assumed you would want to collect the data after you opened the parachute. And as Delta_G suggested, you would want to open the parachute as fast as possible and not gradually.

I also assumed you want to collect the data every second, based on your provided code, because it has a 1000-millisecond delay. With all that here is a code that might work: (I haven't tested it, but it should give an idea of how to get going)

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP085_U.h>
    #include <DHT.h>
    #include <SD.h>

    #define DHTPIN 10
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

    Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

    const int MQ2 = A0;
    const long parachute_timeout_ms = 2 * 60 * 1000;   // Open parachute after two minutes.
    bool parachute_opened = false;

    const long data_collection_interval_ms = 1 * 1000; // Collect data every second.
    bool start_collecting_data = false;
    unsigned long previous_ms = 0;

    File dataFile;

    void setup()
    {
      Serial.begin(9600);
      dht.begin();
      if (!bmp.begin())
      {
        Serial.println("Could not find a valid BMP085 sensor, check wiring!");
        while (1) {}
      }
      if (!SD.begin(4))
      {
        Serial.println("SD card initialization failed!");
        while (1) {}
      }
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile)
      {
        dataFile.println("Temperature, Humidity, Pressure, Gas");
        dataFile.close();
      }
      else
      {
        Serial.println("Error opening data file!");
      }

      previous_ms = millis();
    }

    void loop()
    {

      // Check to see if it's time to open the parachute.
      unsigned long current_ms = millis();

      if ((parachute_opened == false) && (current_ms - previous_ms >= parachute_timeout_ms))
      {
        // Your code to open the parachute
        // ... ... ..

        // Make sure this code doesn't execute again.
        parachute_opened = true;

        //...and then set the flag that tells the other part of the code
        // that it should start collecting data.
        start_collecting_data = true;
      }

      if ((start_collecting_data) && (current_ms - previous_ms >= parachute_timeout_ms))
      {
        collect_data();
        previous_ms = current_ms;
      }
    }

    void collect_data()
    {
      float temperature = dht.readTemperature();
      float humidity = dht.readHumidity();
      sensors_event_t event;
      bmp.getEvent(&event);
      float pressure = event.pressure;
      float gas = analogRead(MQ2);
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile)
      {
        dataFile.print(temperature);
        dataFile.print(",");
        dataFile.print(humidity);
        dataFile.print(",");
        dataFile.print(pressure);
        dataFile.print(",");
        dataFile.println(gas);
        dataFile.close();
      }
      else
      {
        Serial.println("Error opening data file!");
      }
    }


body:
I want to use the ESP32-CAM as a sun sensor, the problem is that I would need to remove the lenses in order to put a membrane with a pinhole (like it's illustrated in the image) upon the CMOS, but I want to know first, will this make unoperable the OV2640? I want it to be working fine without the lenses, the second image is an illustrative of what I want to do.
[![Fig.1][1]][1]

[![Fig.2][2]][2]

  [1]: https://i.stack.imgur.com/hz9ka.png
  [2]: https://i.stack.imgur.com/DP2bP.png

title: ESP32-CAM OV2640 AS A SUN SENSOR

Answers: 1

body:
Consider using the ESP32-CAM as is. Instead use a [pin hole camera][1] box. Put the ESP32-CAM inside the box pointing it at the image of the sun at the back of the box. This approach mitigates problems associated with exposing the sensor to the elements and direct exposure to sun light.

In order to measure azimuth and elevation, consider mounting the device such that it points directly up from the surface of the earth.  And such that it is aligned to true North. Consider using an accelerometer to detect the device is normal to the surface of the earth. And a magnetometer to detect magnetic north.  And a GPS receiver to detect the position on earth.  Combine the GPS data with [ World Magnetic Model (WMM) data][2] to correct for magnetic declination.

  [1]: https://en.wikipedia.org/wiki/Pinhole_camera
  [2]: https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml


body:
I have been powering my WeMos D1 R1 and D1 R2 Arduinos (with ESP8266) using a simple USB cable connected to a standard charger whose rating is 3.1 amps.  Is this sufficient to charge two such Arduino boards (it has two USB slots) simultaneously?

Also, should I be using the other Power Input which I understand is 9V?

All the specs I have seen specify the voltage but not the current usage.

Either way, what is the maximum amperage that the board might need/is rated for?  Is it different for the R1 vs. R2?  Is it possible to measure how much it is using from any of the pins?

title: How much maximum current do the Arduino Wemos D1 (R1 & R2) consume?

Answers: 1

body:
>  It is possible to measure how much it is using from any of the pins?

Put an ammeter (multimeter in current mode) in series with the power supply and measure it, when configured in the way you intend to use it.


body:
I've programmed an Adafruit Feather nRF52840 board to send MIDI signals to my computer via BLE. I can confirm that the board pairs successfully with an Android phone and a Windows PC, but my laptop (MacBook Pro 2021) will not recognize the board; it does not appear in the Bluetooth menu as an option for pairing. I've tried the following troubleshooting options:

1) Turned bluetooth off & on on laptop
2) Turned device off & on
3) Added the name of the board in the code (advertisement.complete_name = "BOARD_NAME")
4) Downloaded Bluefruit Buddy, Bluefruit Connect & Bluetility to find any BLE signals coming from the board (verdict: no trace!)
5) Tried a BLE smart dongle
6) Unpaired/forgot device from Android phone, attempt to re-pair with laptop
7) Attempted to connect the device via Apple’s Audio MIDI setup (https://support.apple.com/guide/audio-midi-setup/set-up-midi-devices-ams875bae1e0/mac)
8) Tried steps 1-7 with two additional MacBooks (2016 & 2022)

I know that the BLE pairing functionality of the board is working, since it consistently pairs with an Android phone and a PC laptop; I just cannot figure out why it won't pair with my MacBook. I want to resolve this issue and ensure that the board can be used across platforms.

Are there any other troubleshooting actions I should try?

title: MacBook + BLE Microcontroller Incompatibility?

Answers: 1

body:
Have you tried [Bluefruit Connect from Adafruit][1]? It is available in the Apple store. Don't quote me on this, but I read a long time ago, that Mac requires encryption for a BLE device to be recognized, whereas, most of the out-of-the-box Adafruit example doesn't use it.

I had a similar issue. And I used Bluefruit Connect to connect my device to my Mac.

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

  [1]: https://apps.apple.com/us/app/bluefruit-connect/id830125974
  [2]: https://i.stack.imgur.com/RWiO5.png


body:
I am currently trying to read an existing canbus (Car) with my ESP32 Rev3.
I got it to work fine with an external MCP2515 shield using a default library.

But when i connect an transceiver and trying to use the internal TWAI controller built into ESP32 i am starting to get troubles. When receiving messages with at least >5ms period, it works fine but as soon the period gets under 5ms, its rapidly filling up the RX buffer and once its full, its starting to drop packets. When i set the RX buffer to a higher value, this only extend the time until the first error appears. It seems like the transceiver works fine but the twai_receive() function can't catch up. Does anyone have an idea, what i can do here.

For receiving, i am using the following, wich works kind of fine for ESP32 Wroom Rev3.
https://github.com/halfroad/TWAIMessager

Before, i was directly accessing the API by using this documentation, but this has the same behaviour:
https://docs.espressif.com/projects/esp-idf/en/release-v4.4/esp32/api-reference/peripherals/twai.html#examples

If the internal limitation is >5ms per message period, the CAN controller is pretty useless as in most modern cars canbus you have periods as low as 0.4ms per message.

To verify, that i'm not missing anything i setup two ESP32 and sending from A to B.

The code/setup of the receiving part is like this:

    #include "driver/twai.h"
    twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_33, GPIO_NUM_32, TWAI_MODE_LISTEN_ONLY);
        twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
        twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();

        //Install TWAI driver
        if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
            Serial.println("Driver installed\n");
        } else {
            Serial.println("Failed to install driver\n");
            return;
        }

        //Start TWAI driver
        if (twai_start() == ESP_OK) {
           Serial.println("Driver started\n");
        } else {
            Serial.println("Failed to start driver\n");
            return;
        }

The processing of ingoing messages in the loop() function is something like this:

    twai_message_t message;

    void loop() {
        while (twai_receive(&message, 0) == ESP_OK) {
            // process message (which will only arrive every 5ms
            Serial.printf(msgString, "STD CAN-ID: 0x%.3lX       DLC:   Data:", message.identifier, message.data_length_code);
                for(byte i = 0; i<message.data_length_code; i++){
                            Serial.printf(" 0x%.2X", message.data[i]);
                }
            Serial.println();
        }

    return;
    }

Here is the receiving side's output when sending in a 5.1ms period:
[![enter image description here][1]][1]

On the left you can see the period between this, and the previous message.
The ID in green on the right side confirms, that the message is a valid follow up to the previous message (data).

As soon as im trying to go <5ms, 3ms in this example it looks like this:
[![enter image description here][2]][2]

Here, it starts to drop messages as soon the RX buffer is filled up.

In the last image, you will see a log of the drivetrain canbus of a 2013 VAG car using the ESP32 and a MPC2515 controller externally.

It has periods between 0.41 and 9ms between each package and its not missing a single one of it.

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

I hope, someone here can actually help with this or had experienced the same behaviour before.

Br Chris

  [1]: https://i.stack.imgur.com/2wfGK.jpg
  [2]: https://i.stack.imgur.com/Z7GY7.jpg
  [3]: https://i.stack.imgur.com/aLydy.jpg

title: ESP32 - TWAI Timing Problems (cant receive messages below 5ms period)

Answers: 0


body: Is it possible to obtain the RSSI value of the connected device to the esp8266 similar to obtaining MAC address?

title: Is it possible to get the RSSI value of the connected client or phone in esp8266 if it is set as an access point

Answers: 0


body:
I have an ESP8266 module which has downloaded a hex file for an Arduino Mega2560. This hex file (call it `mega2560.hex`) is sitting in the ESP's SPIFFS file system. What I want to do is basically emulate the behavior of the Arduino IDE when we press the upload button on a sketch (except in my case here, the sketch is already compiled and ready for transfer). What I need is some library or small code example that can steer me in the right direction. On the Mega's end, the processor will be restarted, and the bootloader will wait for the hex file, receive it from the ESP and flash it to application memory.

Here is the basic structure:

```
// Code for ESP8266

SoftwareSerial mega(D1, D2); // since hardware serial is occupied for serial monitor
// Mega will use its hardware serial (Tx1, Rx1)

void setup()
{
    Serial.begin(115200); // use up hardware serial
    mega.begin(115200); // connect to mega

    SPIFFS.begin();
    File hexfile = SPIFFS.open("mega2560.hex", "r");

    // IDE-like "upload"
    upload(mega, hexfile);
    Serial.println("Done uploading.");

    hexfile.close();
}

// emulate Arduino IDE-like upload behavior
void upload(SoftwareSerial& mega, File& hexfile)
{
    // reset Mega to start bootloader which will first wait to accept new hex file
    reset(mega);

    // send out the hex file for the bootloader to accept and store to Mega's flash
    send(mega, hexfile);

    // reset Mega to start bootloader again, this time so that previously uploaded hex file can be run
    reset(mega);
}
```

I am fairly new to working with bootloaders and would like to know if the above top-down code is correct in trying to achieve what I have in mind. Can I simply reset the Mega and transfer it as per usual via Serial within the bootloader's "waiting window" ? or are there more considerations that I am missing.

I am trying to avoid using ISP or SPI because that would erase the Mega's bootloader as well and I want to keep the bootloader preserved.

title: Turn ESP8266 into an Arduino IDE-like "sketch uploader" (over hardware serial)

Answers: 0


body:
I'm working with a ESP32S3 that will manage 2 I2S ports, so for the cleanness of my code and also because i'll work multiple I2S installations - deinstallations, i want to move all the functions to and ".cpp .h" file.

something like this

 1. I2S_functions.h
    ```
    #ifndef I2S_FUNCTIONS_H
    #define I2S_FUNCTIONS_H
    #include <Arduino.h>
    #include <driver/i2s.h>

    void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
    i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,int buf_count, int buf_len, bool apll);

    #endif

    ```

 2. I2S_functions.cpp
```
#include "I2S_functions.h"

void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,
int buf_count, int buf_len, bool apll)
{
  const i2s_config_t i2s_config =
  {

    .mode = I2S_MODE,
    //.mode = (i2s_mode_t)(I2S_MODE),
    .sample_rate = I2S_SAMPLE_RATE,

    .bits_per_sample = I2S_SAMPLE_BITS,
    .channel_format = I2S_CHANNEL,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),

    .intr_alloc_flags = 0, // default interrupt priority
    .dma_buf_count = buf_count,//cambiado de 8 a 64
    .dma_buf_len = buf_len,
    .use_apll = apll
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
}
```

 3. main.ino

```
#include "I2S_functions.h"

// I2S config //////
#include <driver/i2s.h>

#define I2S_PORT I2S_NUM_0
//#define I2S_SAMPLE_RATE  (44100)
float I2S_SAMPLE_RATE=44100;
int I2S_SAMPLE_BITS=32;
//#define I2S_SAMPLE_BITS  (32)
#define bufferLen 1024
#define I2S_READ_LEN (16*1024)

void setup ()
{
  i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
I2S_BITS_PER_SAMPLE_32BIT,I2S_CHANNEL_FMT_ONLY_LEFT,I2S_COMM_FORMAT_STAND_I2S,8,bufferLen,false);

}
```

But when i compile this, i got errors passing the second argument which is "I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE"

a copy from the error:
```
C:\Users\.ino: In function 'void setup()':
test_10seg_V2:52:39: error: invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]
   i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
                        ~~~~~~~~~~~~~~~^~~~~~~~~~~~
In file included from C:\Users\.ino:2:
C:\Users\I2S_functions.h:6:50: note:   initializing argument 2 of 'void i2s_install(i2s_port_t, i2s_mode_t, float, i2s_bits_per_sample_t, i2s_channel_fmt_t, i2s_comm_format_t, int, int, bool)'
 void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,

exit status 1
invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]

```

**Essentially i have 2 questions**. While i looked in the github from the esp32 i found off that there is some typedef of the I2S config (https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/esp32/include/hal/include/hal/i2s_types.h). I've never worked with this type of structs before so i am guessing how should i use it and specially how should i pass this type of variables to a function.
```
typedef enum {
    I2S_BITS_PER_SAMPLE_8BIT    = 8,            /*!< data bit-width: 8 */
    I2S_BITS_PER_SAMPLE_16BIT   = 16,           /*!< data bit-width: 16 */
    I2S_BITS_PER_SAMPLE_24BIT   = 24,           /*!< data bit-width: 24 */
    I2S_BITS_PER_SAMPLE_32BIT   = 32,           /*!< data bit-width: 32 */
} i2s_bits_per_sample_t;

/**
 * @brief I2S bit width per chan.
 *
 */
typedef enum {
    I2S_BITS_PER_CHAN_DEFAULT        = (0),      /*!< channel bit-width equals to data bit-width */
    I2S_BITS_PER_CHAN_8BIT           = (8),      /*!< channel bit-width: 8 */
    I2S_BITS_PER_CHAN_16BIT          = (16),     /*!< channel bit-width: 16 */
    I2S_BITS_PER_CHAN_24BIT          = (24),     /*!< channel bit-width: 24 */
    I2S_BITS_PER_CHAN_32BIT          = (32),     /*!< channel bit-width: 32 */
} i2s_bits_per_chan_t;
```

my questions are

**1.-** I would like to understand how this structs works. I want to clean my code the most that i could, and that mean passing a lot of functions out of the main file. So any resource is well welcome to improve my coding skill.

**2.-** Why the code fails passing this 2 variables "I2S_MODE_MASTER|I2S_MODE_RX" ?. Is there any special way of passing this variables when are 2 options at once?.

Thanks for your replies!

title: Pass typedef to a function

Answers: 1

body:
Answer to Question 1: The `typedef` code you posted is `enum` and not `struct`. Look up C++ Enumeration and you will find lots of good tutorials. Here is [one video][1].

Answer to Question 2:  You need to typecast the argument for your function to accept it as `i2s_mode_t`.

    i2s_install(I2S_PORT, (i2s_mode_t)(I2S_MODE_MASTER|I2S_MODE_RX), ... ... ...);

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


body:
I started a project using the arduino uno and as a challenge I'm attempting to make it work with the esp32 but I've run into a roadblock. I may not describe it in proper terms, but I noticed that the analog input signal on the esp32 functions *differently* from how analog input works on the uno. After some research I found that the esp32 has a default analog width of 12, instead of the default 10 on the uno. This got me wondering what other analog settings (reference voltage, pin attenuation, width, etc.) on the esp32 are different from the uno and how I might go about getting similar results on the esp32. I found [this][1] useful page detailing some functions to mess around with the adc channels but, other than ```analogSetWidth()```, I haven't been able to figure out what they do. I tried messing around with the functions mentioned in the linked page, but I ultimately made things worse.

tl;dr What analog input settings (analog width, pin attenuation, etc.) on the esp32 are different from the uno?

  [1]: https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/api/adc.html

title: Copy Uno Analog Input Configuration To ESP32

Answers: 1

body:
Per the advice of @6v6gt, I was able to find [this][1] resource and [this][2] resource that told me the following information about the ADC configuration for the Uno's MCU (aka ATmega328P):

 - The analog width defaults to 10 bits (** definitely the most important)
 - The reference voltage is determined by the AVCC (power source) by default
 - The ADC clock defaults to a divisor of 128 (assuming 13 ADC cycles per conversion)

Wasn't able to find anything useful about pin attenuation, though.

  [1]: https://www.best-microcontroller-projects.com/arduino-adc.html
  [2]: https://ece-classes.usc.edu/ee459/library/documents/ADC.pdf


body:
I learned in school that typical servos use a simple PWM system to control a servo. To do this, we would generate a 1000ms pulse to put the servo at 0 degrees and 2000ms pulse to set it at 180 degrees. Simple basics, right?

I recently tried configuring my HS-311 with these values and I found the servo moving less than 90 degrees.
I switched to the ``Servo.h`` library and it worked fine. I peeked at ``Servo.h`` file and found the following:

    #define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo
    #define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo
    #define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached

544? 2400? Where are these numbers coming from?

I looked at an [old datasheet](https://docs.google.com/viewer?url=https://github.com/Arduinolibrary/DFRobot_Hitec_HS311_Standard_Servo_SER0001/blob/master/HS-311%20sch.pdf?raw=true) for this servo and found

    OPERATING TRAVEL: 40�/ONE SIDE PULSE TRAVELING 400usec
    DIRECTION: CLOCK WISE/PULSE TRAVELING 1500 TO 1900usec
A bit hard to tell what does numbers mean but they are definitely not 1000 to 2000!

Then I took a look at the specs on [servocity.com](https://www.servocity.com/hs-311-servo/) and I see:

    Max PWM Signal Range 575-2460μsec
This matches up with the ``Servo.h`` source code!

What's going on here? Do manufacturers normally move outside of the 1000us-2000us range? These values that I see far exceed what I'd think are acceptable tolerances. Please help me figure out where these numbers came from!

title: Why does arduino use a PWM range of 544 to 2400?

Answers: 0


body:
I have an [ESP32-S2-DevKitM-1][1] which is supposed to able to act as USB HID device.

But whatever I try using either ESP-IDF or Arduino-IDE, I can't get any data from it.

I ran [this esp-idf example][2].

I also ran the arduino example.

I [connected][3] GPIO20/19 to D+/D- of a USB cable.

When I plug in that cable, my host computer logs:

```
usb 1-6: new full-speed USB device number 93 using xhci_hcd
usb 1-6: device descriptor read/64, error -71
usb 1-6: device descriptor read/64, error -71
usb 1-6: new full-speed USB device number 94 using xhci_hcd
usb 1-6: device descriptor read/64, error -71
usb 1-6: device descriptor read/64, error -71
usb usb1-port6: attempt power cycle
usb 1-6: new full-speed USB device number 95 using xhci_hcd
usb 1-6: Device not responding to setup address.
usb 1-6: Device not responding to setup address.
usb 1-6: device not accepting address 95, error -71
usb 1-6: new full-speed USB device number 96 using xhci_hcd
usb 1-6: Device not responding to setup address.
usb 1-6: Device not responding to setup address.
usb 1-6: device not accepting address 96, error -71
usb usb1-port6: unable to enumerate USB device
```

The esp-idf example fails to send, because `tud_mounted()` is false, and the arduino-ide example fails on `SendReport(): not ready`.

How can I get the ESP32-S2 to talk USB with my host computer?

  [1]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/hw-reference/esp32s2/user-guide-devkitm-1-v1.html
  [2]: https://github.com/espressif/esp-idf/tree/master/examples/peripherals/usb/device/tusb_hid
  [3]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/peripherals/usb_device.html#hardware-usb-connection

title: USB OTG and ESP32-S2

Answers: 1

body:
This problem went away when I replaced my DIY USB cable connection with an [Adafruit USB-C breakout board][1].

I checked all the connections of my cable, but somehow it would not work, until I replaced it.

  [1]: https://www.adafruit.com/product/4090


body:
Here is my issue:

My code successfully recognizes and accepts $1 (0x40) and $20 bills (0x43), but it fails to recognize, display, process, anything for the $5 bill (0x41), and $10 bills (0x42). Also, when I say "Arduino", I mean TTGO btw...

I have verified that the bill acceptor is indeed sending the correct value (0x41) for the $5, and $10 (0x42) bills using an external monitoring tool like Docklight, and I used an oscilloscope too! All signals from all bill types were near identical and valid. However, the Arduino code does not seem to receive those two values (and ONLY those two values) at all... Meanwhile, it will display every other little thing there is... I have my code setup where it displays all incoming bytes, be it B.A. (bill acceptor) idle signals, rejection signals, everything, but it goes 100% blank, MIA, for 0x41 and 0x42... WHY?!?! So frick'n random...

===================================================

**Just so you all know, this is how the bill acceptor (B.A.) works:**

 1. Insert a bill into BA
 2. BA sends the corresponding HEX value (ex. 0x40) of the bill to my Arduino (Using RS232 cables and an RS232 to TTL converter (the converters are confirmed to be 100% operational BTW))
 3. Once the Arduino "sees" the HEX value for a bill of N value, it will then send 0x02 to the BA to accept the bill.
 4. If 0x02 is NOT sent to the BA within 5 seconds, then it will reject the bill and spit it back out the front.
 5. Code then adds that value to "total count"

OFC, my code is setup where the only way an accept (0x02) signal is sent is IF 0x4N is received... So, the fact that 0x41 and 0x42 disappear into thin air means 0x02 is never sent so those two values are always rejected... Very, very, simple stuff, so the fact that it consistently is unable to ONLY NOT read 0x41 and 0x42 while clearly displaying all other sent HEX values is causing me unlimited headaches and conniptions... Programming... YAY! -_-

So, anyone... please, do you know what's going on? The signal is 100% being generated, and my code, below, is setup to display all incoming bytes, but it acts like 0x41 and 0x42 do not exist at all! Nothing. Nada. Zilch. WTF? It literally handles everything I can throw at it... except 0x41 and 0x42!!! FUUUUUUUUUUUU!!! So mad...

**HERE IS THE ICT RS232 PROTOCL FOR MY BILL ACCEPTOR - [http://tdmegalit.ru/upload/iblock/401/ict_protocol.pdf][1]**

**ALSO, I HAVE ALL DIP SWITCHES CORRECTLY SET, POWER SUPPLY IS PERFECT, ALL WIRES ARE TESTED AND PERFECT, RS232 TO TTL CONVERTERS ARE PERFECT. I GUESS IT IS SOFTWARE SERIAL, OR THE TTGO**

So with all that said, **below is my code**. It is a part of a much great whole of a program, so to remove the possibilities of the rest of the code causing the error, I reduced it to what you see below, but the problem persist... bruh

Also, I have included the **Serial Monitor LOG**. The LOG below shows startup, and then a 1, 5, 10, and 20 dollar bill being inserted...

**SERIAL MONITOR LOG:**

    PLZ NOTE, I ADDED SPACES TO SHOW WHATS GOING ON...
    ====================================================================

    ... Received: 0x80       //IDLE SIGNALS (BA POWERED ON BEFORE "SETUP" SENT)
    ... Received: 0x8F
    ... Received: 0x80
    ... Received: 0x8F
    ... Received: 0x80
    ... Received: 0x8F

    SETUP - ...Sent: STX     //SETUP TO INITALIZE BA
    SETUP - ...Sent: DLE
    SETUP - ...Sent: ETX
    =======================
                             //INSERTED $1 (0x40) SUCCESS!!!
    ... Received: 0x40
    $1 accepted
    ... Sent: 0x02
    ... Received: 0x10
                             //INSERTED $5 and 5 seconds later 0x29>>0x29>>0x2F = Rejection
    ... Received: 0x29
    Bill rejected
    ... Received: 0x29
    Bill rejected
    ... Received: 0x2F
                             //INSERTED $10 and 5 seconds later 0x29>>0x29>>0x2F = Rejection
    ... Received: 0x29
    Bill rejected
    ... Received: 0x29
    Bill rejected
    ... Received: 0x2F
                             //INSERTED $20 (0x43) SUCCESS!!!
    ... Received: 0x43
    $20 accepted
    ... Sent: 0x02
    ... Received: 0x10

**BILL ACCEPTOR CODE:**

    #include <SoftwareSerial.h>

    SoftwareSerial BA(32, 33);  // RX, TX

    int billCounter = 0;

    void setup() {
      Serial.begin(9600);
      BA.begin(9600);
      delay(3000); //WAIT BC TRESH

      BA.write(0x02); // Send the initialization command (STX)
      Serial.println("SETUP - ...Sent: STX");
      BA.write(0x10); // Send the command to enable the bill acceptor
      Serial.println("SETUP - ...Sent: DLE");
      BA.write(0x03); // Send the end of text character (ETX)
      Serial.println("SETUP - ...Sent: ETX");
      Serial.println("=======================");
    }

    void loop() {
      if (BA.available()) {
        byte receivedByte = BA.read();
        Serial.print("... Received: 0x");
        Serial.println(receivedByte, HEX);

        if (receivedByte == 0x29) {
          delay(200);
          Serial.println("Bill rejected");
          // Handle bill rejection here (e.g., display message or perform necessary actions)

        } else if (receivedByte == 0x40) {
          delay(200);
          Serial.println("$1 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $1
          billCounter += 1;

        } else if (receivedByte == 0x41) {
          delay(200);
          Serial.println("$5 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $5
          billCounter += 5;

        } else if (receivedByte == 0x42) {
          delay(200);
          Serial.println("$10 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $10
          billCounter += 10;

        } else if (receivedByte == 0x43) {
          delay(200);
          Serial.println("$20 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $20
          billCounter += 20;

        } else if (receivedByte == 0x44) {
          delay(200);
          Serial.println("$50 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $50
          billCounter += 50;

        } else if (receivedByte == 0x45) {
          delay(200);
          Serial.println("$100 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $100
          billCounter += 100;
        }
      }
    }

  [1]: http://tdmegalit.ru/upload/iblock/401/ict_protocol.pdf

title: Arduino unable to read 0x41 and 0x42 (reads others just fine (ICT bill acceptor)

Answers: 2

body:
The default for Arduino Serial is `8 data bits, no parity, one stop bit`. The first page of your linked documents says: `Start bit 1, Data bit 8, Parity bit Even, Stop bit 1`. The mismatched parity parameter could explain a partial failure of this communication. The documentation for the Serial begin() method describes the various configuration options.

However, see also this thread: https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535
It appears that the various software serial libraries do not support EVEN parity settings. Use a hardware serial port on your TTGO Arduino instead. This may mean using SoftwareSerial for the debug printing (maybe with a USB/UART adapter) and dedicating the hardware serial port to your bank note reader.

body:
> The default for Arduino Serial is 8 data bits, no parity, one stop
> bit. The first page of your linked documents says: Start bit 1, Data
> bit 8, Parity bit Even, Stop bit 1. The mismatched parity parameter
> could explain a partial failure of this communication. The
> documentation for the Serial begin() method describes the various
> configuration options.
>
> However, see also this thread:
> https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535
> It appears that the various software serial libraries do not support
> EVEN parity settings. Use a hardware serial port on your TTGO Arduino
> instead. This may mean using SoftwareSerial for the debug printing
> (maybe with a USB/UART adapter) and dedicating the hardware serial
> port to your bank note reader.

Thank you 6v6gt! Using HardwareSerial was the answer and setting the parity bit to EVEN was the answer too :D Here is what I did to fix it if anyone ever needs to see this answer in the future...

**Also note, here is the logic:**

The default for hardware serial is SERIAL_8N1, but I needed to use SERIAL_8E1 for the even parity because:

SERIAL_8N1 means "8" bits, "N"o parity, and "1" stop bit (hence 8N1)

SERIAL_8E1 means "8" bits, "E"ven parity, and "1" stop bit (hence 8E1)

**Here is the chart I used to get the protocol format I needed:**

    /* Baud-rates available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200, 256000, 512000, 962100
     *
     *  Protocols available:
     * SERIAL_5N1   5-bit No parity 1 stop bit
     * SERIAL_6N1   6-bit No parity 1 stop bit
     * SERIAL_7N1   7-bit No parity 1 stop bit
     * SERIAL_8N1 (the default) 8-bit No parity 1 stop bit
     * SERIAL_5N2   5-bit No parity 2 stop bits
     * SERIAL_6N2   6-bit No parity 2 stop bits
     * SERIAL_7N2   7-bit No parity 2 stop bits
     * SERIAL_8N2   8-bit No parity 2 stop bits
     * SERIAL_5E1   5-bit Even parity 1 stop bit
     * SERIAL_6E1   6-bit Even parity 1 stop bit
     * SERIAL_7E1   7-bit Even parity 1 stop bit
     * SERIAL_8E1   8-bit Even parity 1 stop bit
     * SERIAL_5E2   5-bit Even parity 2 stop bit
     * SERIAL_6E2   6-bit Even parity 2 stop bit
     * SERIAL_7E2   7-bit Even parity 2 stop bit
     * SERIAL_8E2   8-bit Even parity 2 stop bit
     * SERIAL_5O1   5-bit Odd  parity 1 stop bit
     * SERIAL_6O1   6-bit Odd  parity 1 stop bit
     * SERIAL_7O1   7-bit Odd  parity 1 stop bit
     * SERIAL_8O1   8-bit Odd  parity 1 stop bit
     * SERIAL_5O2   5-bit Odd  parity 2 stop bit
     * SERIAL_6O2   6-bit Odd  parity 2 stop bit
     * SERIAL_7O2   7-bit Odd  parity 2 stop bit
     * SERIAL_

**CODE SOLUTION:**

    #include <HardwareSerial.h>

    HardwareSerial BA(1);  // Use Hardware Serial on TTGO

    void setup() {
      Serial.begin(9600);
      BA.begin(9600, SERIAL_8E1, 32, 33);  // (Baud rate, Protocol, RX, TX)
      ...  //rest of my code


body:
Code:
```
#include <Mouse.h>
#include <hiduniversal.h>
#include "hidmouserptparser.h"
#include <USBController.h>

USBController controller;
USB Usb;
HIDUniversal Hid(&Usb);
HIDMouseReportParser Mou(nullptr);
String x;
String y;
boolean isX;
int recv;

void setup() {
 Mouse.begin();
 Usb.Init();
 delay(200);

 if (!Hid.SetReportParser(0, &Mou))
  ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
}

void loop() {
   Usb.Task();
 recv = controller.read();
   if ((recv-48)==29){ // recv = M
  // , : -4
  // /n : -38
  x="";
  y="";
  isX = true;
  while (true){
   recv = controller.read();
   if (recv!=0 && recv!=2){ // filter out 0 and 2
    if ((recv-48)==-38){ // -38 is a line break
     break;
    }
    else if ((recv-48)==-4){ // switch to y value after comma
     isX = false;
     continue;
    }

    if (isX){
     x+=String(recv-48);
    }
    else{
     y+=String(recv-48);
    }
   }
  }
  Mouse.move(x.toInt(),y.toInt());
   }
}

void onButtonDown(uint16_t buttonId) {
 Mouse.press(buttonId);
}

void onButtonUp(uint16_t buttonId) {
 Mouse.release(buttonId);
}

void onMouseMove(int8_t xMovement, int8_t yMovement, int8_t scrollValue) {
 Mouse.move(xMovement, yMovement, scrollValue);
}

```
I'm using an Arduino leonardo with a usb host shield. My goal is to move my cursor to a specific location based on the data read in. Format of the data read in is "MX,Y" and a line break.

In the main loop,
- I read the data and subtract 48 because that's the real number.
- Then I check if the first character is M because that is where the beginning of my data starts.
- Then I filter out 0 and 2 because those values are useless to me and randomly appear.
- I loop to add the integer values as strings to x then switch to y after the comma appears.
- Then I convert the `string` values to `int` and `mouse.move`.

The problem is the mouse movement is slow and jittery and I think it's because the `toInt` and `String()` methods are slowing it down. How could I improve my algorithm?

title: Improving moving mouse loop to optimize speed

Answers: 1

body:
This:

> ```c++
> while (true){
>     recv = controller.read();
>     // ...
> }
> ```

is a _blocking_ loop. This means that, while executing this part of the
code, the Arduino is stuck for an indeterminate amount of time, and can
do nothing else. Specifically, it cannot run `Usb.Task()`, which could
well be the cause of the jittery behavior you are experiencing.

I would recommend reading the incoming data in a _non blocking_ fashion:
each time there is a byte to be read, read it and move on. Do not wait
for the subsequent bytes. Only when you find an end of line would you
handle the data you received. For example:

```c++
// Parse and execute a command received through USB.
executeCommand(String &command) {
    // Implementation left as an exercise to the reader.
}

// Whether we are presently receiving characters from a command.
bool receivingCommand = false;

// Received command, may be incomplete.
String command;

void loop() {
    Usb.Task();
    if (controller.available()) {
        char c = controller.read();
        if (!receivingCommand && c == 'M') {  // start of command
            receivingCommand = true;
        } else if (receivingCommand && c == '\n') {  // end of command
            executeCommand(command);
            command = "";
            receivingCommand = false;
        } else if (receivingCommand) {  // body of command
            command += c;  // buffer the received character
        }
    }
}
```

A better approach would be to avoid the `String` class, which is not
friendly to your Arduino's memory, and use a plain C string, as
explained in [Reading Serial on the Arduino][majenko]. This, however, is
likely unrelated to your jitter issue.

[majenko]: https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27


body:
Python/Arduino Beginner here...

I have a DFplayer I am trying to hook to my Arduino and I want to hook it up through the regular pins instead of the RX and TX pins, but I've not been able to find detailed information on if I can do that and how to set it up... Is this possible to do?

title: Can I use regular pins (Example: D2, A3, etc...) as serial (RX, TX)?

Answers: 0


body: Im creating a project where i need to set one of my esp as a hotspot or access point but i would like to put a function where i could control the connected esp8266 client using the esp8266 that set as access point. I wonder if could use the acces point as a remote to control the client. Thank you in advance.

title: is it possible for a client esp8266 to control the esp8266 that set as an access point?

Answers: 0


body:
I have set up a very simple test program to blink an builtin LED using PWM. Following the [mbed example][1] and setting the period to 4 seconds (0.25 Hz) and duty cycle to 0.5, the expected behaviour is for the LED to be on for 2 seconds and off for 2 seconds. However, the actual behaviour is that the LED flashes extremely quickly (almost imperceptable to the eye).

```arduino
#include "mbed.h"

mbed::PwmOut ledPin = mbed::PwmOut(P0_13); //builtin led pin

void setup() {
  ledPin.period(4.0f);
  ledPin.write(0.0f);
}

void loop() {
  // put your main code here, to run repeatedly:
  ledPin.write(0.5f);
}
```

I have tried adding `delay()` and `wait_ns()` with different times in the main loop, tried having the main loop empty and setting the duty cycle in the `setup()` function as well as changing the period to larger numbers just in case it was in milliseconds all to no avail. Not quite sure what I'm missing from this extremely simple example.

  [1]: https://os.mbed.com/handbook/PwmOut

title: Why does a simple LED Blink not work using mbed.h PWM and Arduino Nano BLE?

Answers: 1

body:
The example you linked has an infinite, but empty, loop - `while(1);` - following setting up the PWM.

Your loop repeatedly executes `ledpin.out(0.5f);`

I didn't find the .out() member function to know what it does but my first thought would be comment out the contents of your loop() function and let it also run as an empty infinite loop. Then I'd look at the .out member function and find out what its action is. Output to a pin is usually a boolean. If that is the case with .out(), then 0.5f will be converted to an integer 0 which is identical to boolean 'false', and this loop would repeatedly turn off the LED, and at around a megahertz.


body:
I want to build my first barebones AVR circuit.

I plan on NOT having a RESET button. For this reason, is it valid if I connect the ATMEGA's `RESET` pin to `Vcc` directly?

What I mean by this, is that in this scenario, I will not be using a pull-down resistor as well. Just straight to `Vcc`.

EDIT: This is a part of the schematic:

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

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

title: Barebones AVR - Connecting RESET pin to Vcc

Answers: 2

body:
According to the datasheet linked to by hcheung in their comment, [datasheet][1], on page 41 it states "Figure 10-2. MCU Start-up, RESET Tied to VCC".

I believe it would be OK to tie the pin directly to Vcc.

I also believe the graphical data presented in "Figure 10-2" could be miss-leading if the reader didn't know what Vcc meant, and also because there is no horizontal axis to specify that they are talking about elapsed time, not voltage change.

**EDIT**

Regarding your comment "Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.".

Looking at page 40 of the datasheet, a internal pull-up resistor is built into the MCU.

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

You could leave the reset pin not connected and see if it still works as expected. Perhaps a high impedance DVOM would show Vcc on that pin. Some people say leave it disconnected if there are no issues from EMI. [EEV Blog - Is it ok to leave atmega328p reset pin floating?][3]

The data sheet also mentions the power on reset timeout which may allow you to program the MCU with your programmer once it first starts, (assuming you have tied the reset pin to Vcc and you leave the reset pin disconnected on your programmer).

Another option would be to program the MCU, then connect the reset pin to Vcc through a couple of solder pads you can bridge with a blob of solder.

Once the reset pin is tied to Vcc, using a programmer connected to that pin will likely result in the magic smoke being released from the MCU, your programmer, or both.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [2]: https://i.stack.imgur.com/Nl1Rq.jpg
  [3]: https://www.eevblog.com/forum/beginners/is-it-ok-to-leave-atmega328p-reset-pin-floating/

body:
>  I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

Then don't tie /RESET to VCC. The programming won't work. What are you doing? Trying to save one resistor? If you have J2 as a programming interface, then /RESET needs to be able to be pulled low to start the programming sequence. Either remove J2 altogether and program the chip in advance of going on the board, or use the pull-up resistor. Don't tie it to VCC.


body:
I'm trying to connect a ESP32 client using `SocketIO` with a `Flask-SocketIO` server and it's not getting connected.
The server uses SSL. The local server address is `https://192.168.1.137:3000`.Is the `https` causing issue here?

The following is the output from the ESP32 in the serial monitor. Note that esp32 successfully connects to the wifi.

    > ["myEvent",{"now":95506}]
    > [IOc] Disconnected!
    > [IOc] Disconnected!
    > [IOc] Disconnected!
    > ...

Esp32 code:

    /*
    * WebSocketClientSocketIOack.ino
    */

    #include <Arduino.h>

    #include <WiFi.h>
    #include <WiFiMulti.h>
    #include <WiFiClientSecure.h>

    #include <ArduinoJson.h>

    #include <WebSocketsClient.h>
    #include <SocketIOclient.h>

    WiFiMulti WiFiMulti;
    SocketIOclient socketIO;

    #define USE_SERIAL Serial

    void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
        switch(type) {
            case sIOtype_DISCONNECT:
                USE_SERIAL.printf("[IOc] Disconnected!\n");
                break;
            case sIOtype_CONNECT:
                USE_SERIAL.printf("[IOc] Connected to url: %s\n", payload);

                // join default namespace (no auto join in Socket.IO V3)
                socketIO.send(sIOtype_CONNECT, "/");
                break;
            case sIOtype_EVENT:
            {
                char * sptr = NULL;
                int id = strtol((char *)payload, &sptr, 10);
                USE_SERIAL.printf("[IOc] get event: %s id: %d\n", payload, id);
                if(id) {
                    payload = (uint8_t *)sptr;
                }
                DynamicJsonDocument doc(1024);
                DeserializationError error = deserializeJson(doc, payload, length);
                if(error) {
                    USE_SERIAL.print(F("deserializeJson() failed: "));
                    USE_SERIAL.println(error.c_str());
                    return;
                }

                String eventName = doc[0];
                USE_SERIAL.printf("[IOc] event name: %s\n", eventName.c_str());

                // Message Includes a ID for a ACK (callback)
                if(id) {
                    // creat JSON message for Socket.IO (ack)
                    DynamicJsonDocument docOut(1024);
                    JsonArray array = docOut.to<JsonArray>();

                    // add payload (parameters) for the ack (callback function)
                    JsonObject param1 = array.createNestedObject();
                    param1["now"] = millis();

                    // JSON to String (serializion)
                    String output;
                    output += id;
                    serializeJson(docOut, output);

                    // Send event
                    socketIO.send(sIOtype_ACK, output);
                }
            }
                break;
            case sIOtype_ACK:
                USE_SERIAL.printf("[IOc] get ack: %u\n", length);
                break;
            case sIOtype_ERROR:
                USE_SERIAL.printf("[IOc] get error: %u\n", length);
                break;
            case sIOtype_BINARY_EVENT:
                USE_SERIAL.printf("[IOc] get binary: %u\n", length);
                break;
            case sIOtype_BINARY_ACK:
                USE_SERIAL.printf("[IOc] get binary ack: %u\n", length);
                break;
        }
    }

    void setup() {
        //USE_SERIAL.begin(921600);
        USE_SERIAL.begin(115200);

        //Serial.setDebugOutput(true);
        USE_SERIAL.setDebugOutput(true);

        // USE_SERIAL.println();
        // USE_SERIAL.println();
        // USE_SERIAL.println();

          // for(uint8_t t = 4; t > 0; t--) {
          //     USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
          //     USE_SERIAL.flush();
          //     delay(1000);
          // }

        WiFiMulti.addAP("ssid", "mypass");

        //WiFi.disconnect();
        while(WiFiMulti.run() != WL_CONNECTED) {
            delay(100);
        }

        String ip = WiFi.localIP().toString();
        USE_SERIAL.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

        // server address, port and URL
        socketIO.begin("192.168.1.137", 3000, "/socket.io/?EIO=4");

        // event handler
        socketIO.onEvent(socketIOEvent);
    }

    unsigned long messageTimestamp = 0;
    void loop() {
        socketIO.loop();

        uint64_t now = millis();

        if(now - messageTimestamp > 2000) {
            messageTimestamp = now;

            // creat JSON message for Socket.IO (event)
            DynamicJsonDocument doc(1024);
            JsonArray array = doc.to<JsonArray>();

            // add event name
            // Hint: socket.on('event_name', ....
            array.add("myEvent");

            // add payload (parameters) for the event
            JsonObject param1 = array.createNestedObject();
            param1["now"] = (uint32_t) now;

            // JSON to String (serializion)
            String output;
            serializeJson(doc, output);

            // Send event
            socketIO.sendEVENT(output);

            // Print JSON for debugging
            USE_SERIAL.println(output);
        }
    }

Server code (Removed unrelated parts):

 from flask import Flask, render_template, Blueprint, current_app, request, session, url_for, render_template
 from flask_socketio import SocketIO, emit

    from threading import Thread
    from queue import Queue
    import logging

    loggerPath = baseUrl + "logs/appLog.log"
    os.makedirs(os.path.dirname(loggerPath), exist_ok=True)
    with open(loggerPath, "a") as f:
     logging.basicConfig( level=logging.INFO,
      # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
      format='%(levelname)s - %(message)s',
      filename=loggerPath
     )
 bp = Blueprint('audio', __name__, static_folder='static',
    template_folder='templates')
 app = Flask(__name__)

 async_mode = "threading"

 socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)

    @socketio.on('myEvent')
    def test_connect(data):
     logging.info("receiving")

 def runApp():
  try:
   certificatePath = os.getenv('BASE_URL')+"SSL/"
   key = certificatePath+"localhost.key"
   certificate = certificatePath+"localhost.crt"
   context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
   context.load_cert_chain(certificate, key)
   ip = socket.gethostbyname(socket.gethostname())
   socketio.run(app, host=ip, port=3000,ssl_context=context)
  except Exception as e:
   logging.error("Exception occurred in: "+__file__, exc_info=True)

 q = Queue()
 t = Thread(target=wrapper, args=(q, runApp), daemon=True)
 t.start()

title: ESP32 SocketIO Client is not connecting to Flask-SocketIO Server

Answers: 1

body:
This is version Socketio issue,I have successfully connected .
This installed version
Werkzeug 2.0.0
Flask 2.3.3
Flask-SocketIO 4.3.1
python-engineio 3.13.2
python-socketio 4.6.0


body:
I am trying to test functionality of strtok() on a new piece of hardware, as I ran out of memory to develop on my Nano. This is a basic example from the internet involving tokenizing the string and reporting the tokenized entries via SerialUSB. I'm running a [Rocketscream V3][1] (Arduino Zero ATSAMD21G18A).

    #include <string.h>

    void setup() {
      char *token;
      char *mystring = "apples,pears,bananas";

      SerialUSB.begin(9600);
      while (!SerialUSB) { }

      SerialUSB.print("Serial established");

      token = strtok(mystring, ",");

      while (token != NULL) {
        SerialUSB.println(token);
        token=strtok(NULL, ",");
      }
    }

The code works as expected on my Nano (with Serial instead of SerialUSB), but while it does compile for the Arduino Zero, the Zero never makes it past printing "Serial established". I have confirmed this by including code (serial print, LED flashing) past the tokenization parts, and these are never executed. The loop() function is never reached, it seems to halt at "token = strtok(mystring, ",");".

I cannot think of a simpler possible way to test strtok(), but it's just not working. Any help would be appreciated.

  [1]: https://www.rocketscream.com/blog/product/mini-ultra-pro-v3-with-radio/

title: Strtok operations on Arduino Zero seem to fail in runtime

Answers: 1

body:
`strtok` works by modifying the source string. Your test string points to a constant string.

```
  char *mystring = "apples,pears,bananas";
```

This particular platform may put that into read-only memory. Try instead as your test string:

```
  char mystring [] = "apples,pears,bananas";
```

I don't have a Zero to test it on, but in any case using `strtok` on a const string is <s>not recommended</s> forbidden.

---

If you turn warnings on for the compiler (File -> Preferences) you see this:

     In function 'void setup()':
     warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
       char *mystring = "apples,pears,bananas";

If you are doing something "forbidden" then don't expect good results.


body:
I am new to arduino and I am wondering if it is possible to store image data on my computer and send it to my arduino over the USB cable (which is also used for power) to display on a TFT LCD display I have hooked up. All the tutorials I see involve using an SD card to preload the image data on there beforehand.

Still, my display doesn't have an sd card slot, nor is it practical for my application as the images I want to display will be determined during runtime. I have sent small pieces of data over the COM port to my arduino from my PC but I don't know how I could do it with potentially large image data. The arduino will be plugged into my computer 24/7. If this is possible could I get a little guidance on where to start?  Thank you

title: Display images on Arduino LCD screen from PC

Answers: 3

body:
You could "stream" the data from the PC to the LCD, which means you wouldn't need to store it (or maybe store a line or so).

Without knowing which Arduino and which LCD it is hard to give more advice than that.

body:
There are so many different LCDs that with out specifying a specific LCD only very general answers can be provided that may be of limited value.

* Just about all Arduinos can handle an [Alpha Numeric LCDs][1]. But these have very limited graphics, if any.

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

* Most can handle low resolution [B&W Graphics LCDs][3].

[![enter image description here][4]][4]

 * Most can handle sending geometric shapes and alpha numeric to [(smart) Serial Port Color LCDs][5]. Only some Arduinos will be able to handle sending arbitrary images (like a photograph) to (smart) Serial Port Color LCDs.

[![enter image description here][6]][6]

And few will be able to handle sending data to a common TTL or [LVDS][7] Color LCDs.

[![enter image description here][8]][8]

  [1]: https://www.adafruit.com/product/772
  [2]: https://i.stack.imgur.com/bOL0K.jpg
  [3]: https://www.sparkfun.com/products/710
  [4]: https://i.stack.imgur.com/HTh7G.jpg
  [5]: https://www.adafruit.com/product/1770
  [6]: https://i.stack.imgur.com/jPLFa.jpg
  [7]: https://www.adafruit.com/product/4337
  [8]: https://i.stack.imgur.com/KcsVd.jpg

body:
Since you don't give a clue about the TFT you have in mind, I'll try to describe the process using the following assumptions about the TFT that have to be true for the rest to work:

* one full frame of pixel data for the TFT used would not fit into the Arduinos RAM, but one line of that frame will,
* the pixel data can be sent line by line to the TFT without a need to start the next line inside a certain timeframe (i.e. you could, in theory, just tell the TFT to update line 42 out of order, as an example),
* the TFT has its own way of remembering its display data (i.e. does not need a continuous refresh 60 times per second).

In this scenario, your image processing pipeline looks like this:

 * A program running on your PC decompresses (and possibly resizes) the image file in order to get access to the raw pixel data as it would be displayed on the TFT. This means that this program needs to know the resolution and "data feeding order" of your TFT.
 * This process then takes one line of the raw pixel data and converts it into a data package to be sent over the serial port. You will need to devise a communication protocol here that your Arduino sketch can work with. The easiest, but not most efficient, way would be to convert it into Base64, because libraries for that exist in practically every language and platform and you are then able to use text-based delimiters like a line break to mark the end of a pixel data line. (Sending binary data is more efficient, but harder and more prone to sychronization errors, because you have no in-band signalling of "end of data line".)
 * Your Arduino sketch reads that data package (if Base64-encoded: by using `Serial.read` until you encounter a line break) and converts it back to raw pixel data, in whatever format your TFT (or library for that TFT) needs the data (it might require the color format in e.g. GRB instead of RGB).
 * This raw pixel data line is then sent to the TFT.

You will have to determine the baud rate you can send over your serial link (determined by maximum baud rates of both PC and Arduino, and sometimes the cable quality in between). Keep in mind that a serial connection is slow; you probably will be able to watch the image rendering on the TFT line by line.

You may be able to make this more efficient by employing something like RLE (Run-Length Encoding) on the pixel data sent over the serial line, but that would be another iteration of your protocol.


body:
The idea was to create a bluetooth device on the arduino to read data from the machine (ELM327 v2.1) using the HC-05 bluetooth module.

In this code the bluetooth module is switched to MASTER mode and connected to ELM327 using its MAC address. The responses of the module in the code are in the comments.

```
#include <SoftwareSerial.h>
SoftwareSerial bluetoothSerial(4, 5);

void setup() {
  Serial.begin(9600);
  Serial.print("READY");
  bluetoothSerial.begin(38400);
  delay(1000);
  getSetAtCommand("AT");                         //OK
  getSetAtCommand("AT+CMODE=0");                 //OK
  getSetAtCommand("AT+PSWD=1234");               //OK
  getSetAtCommand("AT+ROLE=1");                  //OK
  getSetAtCommand("AT+BIND=0010,CC,4F3603");     //OK
  getSetAtCommand("AT+LINK=0010,CC,4F3603");     //OK
  delay(1000);
  getSetAtCommand("AT+STATE?");  // OK: CONNECTED
  delay(1000);
  getSetAtCommand("ATZ");      //no answer, the buffer is empty
  getSetAtCommand("AT015B");//no answer, the buffer is empty
  getSetAtCommand("015B");      //no answer, the buffer is empty
  getSetAtCommand("ATRV");   //no answer, the buffer is empty
  getSetAtCommand("0105");    //no answer, the buffer is empty
  getSetAtCommand("at i");   //no answer, the buffer is empty
  getSetAtCommand("at rv");   //no answer, the buffer is empty
  getSetAtCommand("ati");    //no answer, the buffer is empty
  getSetAtCommand("atrv");   //no answer, the buffer is empty
}

void loop() {
}

void getSetAtCommand(String command) {
  Serial.println(command);
  String added_command = command + "\r\n";
  bluetoothSerial.print(added_command);
  delay(500);
  while (bluetoothSerial.available()) {
    Serial.write(bluetoothSerial.read());
  }
}
```

Since the State returns CONNECTED, I assume that it is connected to the ELM.

To the command ```AT+PAIR=0010,CC,4F3603,20\r\n``` the module does not respond. The module also does not respond to commands such as ```ATZ\r\n, AT015B\r\n, 015B\r\n, ATRV\r\n, 0105\r\n, at i\r\n, at rv\r\n, ati\r\n, atrv\r\n```. Sometimes the answer is ```ERROR[0]```, as I understand it means that there is no such command.

It seems to me that these commands don't reach the ELM at all. What can be the problem?

The ELM327 itself works, connects to the phone without any problems and shows the data.

Tried through the simulator on a laptop, the connected bluetooth model is displayed in the bluetooth devices on the laptop and also does not work as with the ELM.

title: Problem with reading data from ELM327

Answers: 0


body:
I am using Arduino UNO with a DM556 Micro step driver to control the Stepper motor.

PUL+ --> pin 3

DIR+ --> pin 5

RC receiver --> pin 2

Using CH2 of receiver

With out the RC receiver (R9SX) everything works fine, the motor works perfectly. However I cannot figure out how to control it with RC. I tried to find a tutorial using Micro step driver but everybody appears to use Arduino Nano or some other equipment.

The code I am using makes the motor work extremely slow and only in one direction.

I'd really appreciate it if some one can point error in my code or provide me with a suitable one for my use case.

CODE:

    // Define Pins
    #define RCPin 2
    #define DIR 5
    #define STEP 3

    // Set up time variables for Stepper motor
    unsigned long previousMotorTime = millis();
    long MotorInterval;

    // Set up time variables for RC Read
    volatile long Pulses = 0;
    int PulseWidth = 0;

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

      // RC Read Setup
      pinMode(RCPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(RCPin), PulseTimer, CHANGE);

      // Set DIR and STEP pins to OUTPUT
      pinMode(DIR, OUTPUT);
      pinMode(STEP, OUTPUT);

      // Set initial direction (LOW = one direction, HIGH = the other direction)
      digitalWrite(DIR, LOW);
    }

    void loop() {
      digitalWrite(STEP, LOW);

      // Only save HIGH pulse lengths
      if (Pulses < 2000){
        PulseWidth = Pulses;
      }

      // Stepper motor speed, bigger MotorInterval is a slower speed.
      if (PulseWidth >= 1400 && PulseWidth <= 1600) {
        digitalWrite(STEP, LOW); // Motor doesn't move if the joystick is near the midpoint
      } else if (PulseWidth < 1400) {
        digitalWrite(DIR, LOW);
        MotorInterval = map(PulseWidth, 1000, 1400, 1, 25); // Map the RC signal to the motor speed in reverse when the joystick is pulled down
      } else if (PulseWidth > 1600) {
        digitalWrite(DIR, HIGH);
        MotorInterval = map(PulseWidth, 1600, 1984, 25, 1); // Map the RC signal to the motor speed when the joystick is pushed forward.
      }

      // Check if the MotorInterval time has elapsed and step the motor.
      unsigned long currentMotorTime = millis();
      if (currentMotorTime - previousMotorTime > MotorInterval) {
        digitalWrite(STEP, HIGH);
        previousMotorTime = currentMotorTime;
      }
    }

    // Function to measure the length of the pulses from the remote control
    void PulseTimer() {
      static long StartTime = 0;
      long CurrentTime = micros();
      if (CurrentTime > StartTime) {
        Pulses = CurrentTime - StartTime;
        StartTime = CurrentTime;
      }
    }

title: Controlling Stepper motor using RC receiver

Answers: 0


body:
I have the following situation. When I power my DHT22 with the 3.3V from the Arduino UNO (and Ground it there), then I can read the data perfectly fine using the DHT library from Adafruit.

However, when I connect the DHT22 to my own external power supply (and respective ground), it fails. The reason for using this external power supply is so I can hook it up to a ESP8266 later.

The power supply I build uses a 5V adapter, then an LD33V converter and (just for experimentation) an 100nF capacitor to reduce any noise on the line.
I measured this external power supply and it indeed gives off 3.3V after the LD33V. I check the datasheet of the LD33V and it should be able to 'give' 5mA, whereas the DHT22 needs less than 1mA for operation.

I don't know where to look at this moment. Can someone point me in the right direction? Much appreciated :)

Cheers

title: Reading from DHT22 with Arduino, powered by external source

Answers: 1

body: Have you connected the external power supply ground to the Arduino's ground? If not, one is "floating" with respect to the other. But they need to have the same reference - the ground sides of their power supplies.


body:
I have been trying to get a mini microphone module with an inbuilt microphone module I got from AliExpress to my Arduino to confirm if it is working. It was a four pin microphone with pins labeled V, L, and two G pins. The V represents voltage in and the L represents audio output positive.

Here is the link to the microphone:
<https://www.aliexpress.com/item/1005004277353392.html?spm=a2g0o.productlist.main.23.61e36f2fBMHvFk&algo_pvid=15b05576-cd73-4eb7-a476-4503b8a706a7&algo_exp_id=15b05576-cd73-4eb7-a476-4503b8a706a7-11&pdp_npi=3@dis!USD!0.54!0.39!!!!!@211bf3f716869249882567444d07ba!12000028601598840!sea!NG!4345576938&curPageLogUid=plaZEQWq7SRB>

However, when I ran the code to check whether it works the value does not change that much, Is there something I'm doing wrong (I'm a beginner btw) or is the microphone not just working?

My code
```
const int audioPin = A0; // Analog input pin connected to the microphone module output

void setup() {
  Serial.begin(9600); // Initialize the Serial Monitor
}

void loop() {
  int audioValue = analogRead(audioPin); // Read the analog value from the microphone module

  Serial.println(audioValue); // Print the analog value to the Serial Monitor

  // Add a small delay to control the rate of readings
  delay(10);
}
```

I connected the output (L) to A0 and connected both the G pins to the arduino ground, I connected the V pin to the 3.3V pin on the Arduino Uno.

title: Issues using mini microphone module off AliExpress

Answers: 1

body: Have you checked to see if it is a hardware problem? It could be the fact that it is just off AliExpress. Usually, the display images are better than the actual product and if this is true, you can see a few bad soldering connections. I might want to go over some of them with a soldering iron.