text:
How to reset flow control that prevents me from reading data from ESP8266?
I have a ESP8266 module (like this).
I ran a command AT+UART_DEF=115200,8,1,0,3 as mentioned in documentation of ESP8266 SDK to change the baud rate of my ESP8266 module.
It seems like by running this command I bricked my ESP because now the module does not respond to any command (tried 9600, 74880, 115200 baud rates) and all the data that is sent after the bootloader messages on 74880 baud rate is garbage. The last argument of the above command sets the flow control to "both RTS and CTS" (3), but I don't have those pins.
The module's pinout:

So I suppose on my ESP I can't use hardware flow control. (Or I can?)
I still can receive bootloader's message that is sent on boot on baud rate 74880 bps:
ets Jan  8 2013,rst cause:1, boot mode:(3,6)

load 0x40100000, len 6960, room 16
tail 0
chksum 0x4f
load 0x3ffe8008, len 24, room 8
tail 0
chksum 0xc6
load 0x3ffe8020, len 3196, room 8
tail 4
chksum 0x3a
csum 0x3a
user code done

But all the data that is sent after the bootloader is garbage:

To clarify, before running the AT+UART_DEF command I could receive meaningful data and execute commands on baud rate 115200 bps.
I'm not sure if the command I ran is the problem, so please point me out if I'm wrong.
As per documentation:
The configuration changes will be saved in the NVS area, and will still be valid when the chip is powered on
again.

The new UART settings along with the flow control settings are stored in NVS area.
Is it possible to reset it? Or any other way to reset the flow control?
What have I tried?
I tried to erase all the flash memory of the module using esptool: erase_region 0x0 0x1000000 and then tried to flash the latest AT firmware again. Didn't help. It still receives bootloader messages and some garbage data.
How can I unbrick my ESP?
Hope for your help! Thanks in advance!

please do not post pictures of text ... add the text itself

@jsotola, What pictures are you talking about? The picture of garbage data? Is that useful to post the text of that garbage data?

You can't brick an ESP8266 through software.
You can confirm this by flashing a different, very simple program to it, like this:
#include <Arduino.h>

void setup() {
  Serial.begin(74880);
  delay(1000);
  Serial.println("hello world");
}

loop() {
}

With the serial monitor set to 74880 bits per second, you should see the bootloader messages as well as a single line of "hello world".
You also should completely erase the contents of the flash chip, not just a particular region.
esptool.py erase_flash

Afterwards you'll need to reinstall the firmware you were trying to run.


text:
avrdude: usbdev_open(): cannot open device: Permission denied
I'm trying to upload anything to my Arduino Uno Wifi Rev2, I'm on Arch Linux, but I'm failing with the following error be it via IDEv2 or arduino-cli:

avrdude: usbdev_open(): cannot open device: Permission denied
avrdude: jtag3_open_common(): Did not find any device matching VID 0x03eb and PID list: 0x2145

The device permissions:
crw-rw-rw- 166,0 root uucp  9 Jan 23:22 /dev/ttyACM0

My udev rule:
KERNEL=="ttyACM[0-9]",MODE="0666",GROUP="uucp",TAG+="uaccess"

lsusb:
Bus 001 Device 005: ID 03eb:2145 Atmel Corp. ATMEGA328P-XMINI (CDC ACM)

First two entries from udevadm info -a -n /dev/ttyACM0:
  looking at device '/devices/pci0000:00/0000:00:14.0/usb1/1-3/1-3:1.1/tty/ttyACM0':
    KERNEL=="ttyACM0"
    SUBSYSTEM=="tty"
    DRIVER==""
    ATTR{power/control}=="auto"
    ATTR{power/runtime_active_time}=="0"
    ATTR{power/runtime_status}=="unsupported"
    ATTR{power/runtime_suspended_time}=="0"

  looking at parent device '/devices/pci0000:00/0000:00:14.0/usb1/1-3/1-3:1.1':
    KERNELS=="1-3:1.1"
    SUBSYSTEMS=="usb"
    DRIVERS=="cdc_acm"
    ATTRS{authorized}=="1"
    ATTRS{bAlternateSetting}==" 0"
    ATTRS{bInterfaceClass}=="02"
    ATTRS{bInterfaceNumber}=="01"
    ATTRS{bInterfaceProtocol}=="01"
    ATTRS{bInterfaceSubClass}=="02"
    ATTRS{bNumEndpoints}=="01"
    ATTRS{bmCapabilities}=="6"
    ATTRS{iad_bFirstInterface}=="01"
    ATTRS{iad_bFunctionClass}=="02"
    ATTRS{iad_bFunctionProtocol}=="01"
    ATTRS{iad_bFunctionSubClass}=="02"
    ATTRS{iad_bInterfaceCount}=="02"
    ATTRS{physical_location/dock}=="no"
    ATTRS{physical_location/horizontal_position}=="left"
    ATTRS{physical_location/lid}=="no"
    ATTRS{physical_location/panel}=="top"
    ATTRS{physical_location/vertical_position}=="upper"
    ATTRS{supports_autosuspend}=="1"

I feel like I've tried everything so far:

sudo chmod a+rw /dev/ttyACM0
sudo usermod -a -G uucp $USER
adding udev rule with all different configs (although if chown/chmod doesn't work what will it change??)
changing ownership to my user...
I checked the process for the IDE to make sure it runs on my user and it does
After all these steps I always either restarted and/or reloaded everything with sudo udevadm control --reload-rules && sudo udevadm trigger
Went through plethora of similar topics, no clues

I feel like I must be doing something awfully stupid here, it doesn't make any sense to me why it wouldn't work even after I chown'ed it to my user...

Looking at the board definition for the UNO WIFI R2, it doesn't use the serial port for upload. It's using an mdbg chip that it speaks to over a non-cdcacm USB protocol. Getting yourself into the group-owner for the serial device is good for communicating to the board through the serial monitor though.
The megaavr board package seems to come with a file for creating your udev rules that you should find at:
"${USER}/.arduino15/packages/arduino/hardware/megaavr/1.8.8/scripts/create_dfu_udev_rule"

The 1.8.8 subdirectory of megaavr is current as of writing. It will no doubt change. I still have 1.8.7 on my system.
Running it should create the necessary udev rule for allowing avrdude to speak directly to the USB device. Specifically they're adding this:
SUBSYSTEM=="usb", ATTR{idVendor}=="03eb", ATTR{idProduct}=="2145", MODE="0666", ENV{ID_MM_DEVICE_IGNORE}="1"

They seem to be creating a udev rule for the tty device as well, though that shouldn't strictly be necessary given what you've already done with becoming a member of the serial device's group. Basically you're doing it by becoming a member of the owning group where what they did was just open the device up to RW permissions for everyone.

It worked! Thank you so much for that insight, I wouldn't have figured it out in a reasonable time on my own for sure, I just ran the script to add both tty and usb rules, and removed the one I made previously. I haven't tested if adding just the usb rule works but afair the perms on the tty device were alright (rw for the owner group)

could u send the exact commands u used to fix the error?
@nieomylnieja

You can try sudo "${USER}/.arduino15/packages/arduino/hardware/megaavr/1.8.8/scripts/create_dfu_udev_rule" It may work. I can't practically do that for every version of every distribution of Linux in combination with every core version and executed from every command shell. In case this isn't clear, "${USER}" will evaluate to your user name. Or rather it will in bash. 1.8.8 is current as of this comment.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Arduino Nano R3 & Deek-Robot datalogging shield
Whilst I am much more at home programming PIC ISR's in assembler, I am building a data logger using a DS1307 to interrupt every second to write data to a USB SD card.
There does not appear to be a connection or even a pad from the DS1307 SQW for interrupts and feel I must be missing something, as this would be a remarkable designer/manufacturer oversight?

what is your question? ... are you asking if it would be a remarkable oversight?

is it so important to track the real time seconds in your project? using millis() function is not good enough?

Thanks and no worries.

I can't find any official source for information about "Deek-Robot datalogging shield" but what I do find indicates it is the same or similar design as an Adafruit Datalogging shield. The DS1307 (or other RTC) square wave out signal is routed to a through-hole on the interior of the board indicated in this image:

It does not appear to be routed anywhere else an any of these boards. Note: the picture here is of a board (Current Adafruit logging shield apparently) that uses an NXP RTC that has the same pinout as the DS1307, but uses a different register layout. But in any case places the SQ output on a header in the same basic location. So you would need to solder a header to accept a jumper. Or solder a wire from there to one of the through holes for a digital pin, probably pin 2 or 3 if you're on an UNO (you have tagged) since those are the pins compatible with attachInterrupt()

Thanks, once I put my glasses on I was able to find it.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Bluetooth Serial is unavailable `SerialBT.available()` returns False on Macbook after a successful bluetoooth connection
I am trying to send and receive messages between my mac and esp32 board. I am currently using the Bluetooth classic interface. After a successful connection. I however have observed that there is no data being received on my Macbook.
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup()
{
  Serial.begin(9600);
  SerialBT.begin("ESP32test");
  Serial.println("Setup initalised");
  delay(1000);
}

void loop()
{
  String inputFromOtherSide;
  Serial.println("Loop has started");
  if (SerialBT.available())
  {
    Serial.println("SerialBT is available");
    inputFromOtherSide = SerialBT.readString();
    SerialBT.println("You had entered: ");
    SerialBT.println(inputFromOtherSide);
  }
}

The above-attached images show the output that I currently receive. After some debugging, I noticed that
SerialBT.available() returns false. I am not sure how to proceed from here.
I do know that this above code should work as I have tested this on windows and it works.

I however need to replicate this on the MacBook any guidance on the reason why this fails here would be appreciated. Or is there a way for me to create a Bluetooth serial link on a mac

available returns count of characters available to read.

Does this mean that if I type something in the serial then it would later fill the buffer for me to read from? which then gets printed again?

SerialBT.available() will be more than zero only if something is received over SerialBT (which I guess is not connected to Serial Monitor). in this version of the sketch you have no reason to condition printing to SerialBT. (I saw your post om Arduino forum with a different version of the sketch, which first reads the received cata)


text:
Why is the watchdog biting to quickly?
currently trying to implement a watchdog into my project. I am using the WDTZero library for controlling the watchdog on my MKR NB 1500. The program is trying to measure data, send it to a server, go to sleep, wake up, and repeat the process. Sometimes the code can hang if it can't connect to the NTP server or the server on which the data is being stored, I want the watchdog to reset the program in cases in which this happens.
A sketch of the program is below. The reason why the NB network is often after different connections is that the NB 1500 is not able to connect to another server if the GPRS connection is already open, so I always reset it before trying another connection.
void setup()
{
    setup_watchdog(); //Sets up the watchdog timer
    delay(1000);
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    request_NTP(); //Requests epoch1970 from the NTP server and then closes the connection
    timezone_adjustment(); //Adjusts the epoch time to my timezone (in Norway)
    set_RTC(); //Activates the SAMD21 RTC with this timezone adjusted time
    disconnect_NB(); //Disconnects from the NB network
    delay(2000);
    MyWatchDoggy.clear(); //Resets the watchdog timer
    }

void loop()
{
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    get_ENV_data(); //Takes measurements using the MKR NB ENV shield
    connect_to_server(); //Connects to the server in which the data will be stored
    write_to_server(); //Writes the data on the server
    disconnect_from_server(); //Disconnects from the server
    disconnect_NB(); //Disconnects from the NB network

    LowPower.deepSleep(300000); //Goes to deep sleep for 5 minutes
    delay(3000);
    MyWatchDoggy.clear(); //Resets the watchdog timer
}

All the functions above are written in other .cpp files and imported thru header files into the main file. Here is the code for activating and configuring the watchdog:
#include "watchdog.hpp"
#include "GPRS_NB_connection.hpp"

WDTZero MyWatchDoggy;

void setup_watchdog()
{
    MyWatchDoggy.attachShutdown(NVIC_SystemReset); //calls reset function
    MyWatchDoggy.setup(WDT_SOFTCYCLE8M); //8 minute watchdog timer
}

The program works fine in the way described at the top of the post when the watchdog is not included. But when including the watchdog, it bites after 30 seconds when the dog only should have bit after 8 minutes. I see this because data is being sent about every 25-30 seconds to the server.
At first, I thought I had not activated the watchdog in the right way, so I wrote another program to test it:
#include <Arduino.h>
#include <WDTZero.h>
#include <RTCZero.h>

WDTZero MyWatchDoggy;
RTCZero rtc;

void set_RTC()
{
    rtc.begin();
    rtc.setYear(0);
    rtc.setMonth(0);
    rtc.setDay(0);
    rtc.setHours(0);
    rtc.setMinutes(0);
    rtc.setSeconds(0);
}

void shutdown()
{
    Serial.println("Shutting down");

}

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

    }
    Serial.println("Starting up Arduino");
    MyWatchDoggy.attachShutdown(shutdown);
    MyWatchDoggy.setup(WDT_SOFTCYCLE8M);
    set_RTC();

}

void loop()
{
    Serial.print(rtc.getMinutes());
    Serial.print("/");
    Serial.print(rtc.getSeconds());
    Serial.println("");
    delay(1000);
}

But in this program the watchdog bites after about 8 minutes as it should.
I have not included the code for the functions described in the first code since I know they work without the watchdog and the code itself is very long. But if you think the problem could be caused by these functions for some reason, I will edit the post and include all the function codes.

In the WDTZero library the long watchdog times are achieved by restarting the watchdog timer in watchdog interrupt until the required time is reached.
This doesn't work if the MCU sleeps.

What would be a workaround to this? Is there a way to completely disable the WDT before going into sleep mode and then reenabling it at the start of the loop?

@5TableLegs wdt.setup(WDT_OFF);

Ok, thank you. I can't find any WDT_ON on the resource page on GitHub. So I am guessing the watchdog will automatically be enabled when doing MyWatchDoggy.setup(cycleOfChoice)?


text:
AD7768-1 library " Arduino "
I am working on a project and I need an AD7768-1 library to make this analog-digital-converter talk to my Arduino using SPI.
" The AD7768-1" doesn't exist in Arduino's library.
Thanks in advance.

There doesn't seem to be a ready to use Arduino library for this part. Though I found one for AD7705/6. If the parts are similar enough you might be able to make this library work with AD7768 with only few changes. Also AnalogDevices provides a no-OS code (general code for devices without an OS like microcontrollers), though you would need to find out how to use it and how to provide it with its needed SPI hardware routines. And depending on your project it might be easier to just write your own SPI code for it without a thirdparty library

please add a clear, answerable question to your post

At present, there is no Arduino library available for this device. As suggested by @chrisl, the easiest way to proceed would be to develop your own driver. However, if you wish to leverage all the advanced features of the device, you could use the drivers provided by Analog Devices. The AD7768-1 differs significantly from the AD7705/6!!!. Having personally interfaced with this device (and AD7768/AD7768-4) using STM32 microcontrollers and Xilinx FPGAs, I would recommend using the no-OS drivers provided by Analog Devices. This approach has worked well for me using an STM32:

Please read this article first: Understanding and Using the No-OS and Platform Drivers.
And this one:No-OS Overview.
Gather all the necessary files you would need from the Analog Devices Github repository no-OS:
Get AD7768-1 drivers from the "/drivers" folder.
Get Platform Drivers from "drivers/platform/". Since we are using STM32, then pick one of these three (STM32, MBED or Generic):/STM32: suitable for STM32CubeIDE or similar. I will use this one. MBED: for MBED platforms. Check this out AD7768-1 IIO Application. Generic: With this one, you need to fill-in platform peripheral calls manually (in the case of Arduino platforms, this would be something like SPI.beginTransaction, etc.).
All the associated source and header files are available in the same repository.
To simplify, I would assume you are using STM32CubeIDE and you just want to configure and read data from the device. Then,
Configure the STM32 Microcontroller as an SPI Master-Full-Duplex MODE 3 [MOSI, MISO, CLK].
Slave select PIN software-controlled [SS].
[Optional] One Pin for data-ready interrupts [DRDY].
Place the required source and header files in their respective
folders. At a minimum, you need (ad77681.c/h, no_os_spi.c,
stm32_spi.c, no_os_gpio.c, stm32_gpio.c) and all their linked header
files.
Initialize No-OS drivers and platform drivers. It would be
something like this:

struct stm32_spi_init_param stm32_init = {
      .chip_select_port = 1,
      .get_input_clock = &HAL_RCC_GetPCLK1Freq
  };

struct no_os_spi_init_param spi_init_param = {
      .device_id = 1,
      .max_speed_hz = 64000000,
      .chip_select = 6,
      .mode = NO_OS_SPI_MODE_3,
      .bit_order = NO_OS_SPI_BIT_ORDER_MSB_FIRST,
      .platform_ops = &stm32_spi_ops,
      .extra = &stm32_init ,
      .parent = NULL
  };

 struct ad77681_init_param ad77681_init = {
      .spi_eng_dev_init = spi_init_param,
      .power_mode = AD77681_MEDIAN,
      .mclk_div = AD77681_MCLK_DIV_8,
      .conv_mode = AD77681_CONV_CONTINUOUS,
      .diag_mux_sel = AD77681_AIN_SHORT,
      .conv_diag_sel = false,
      .conv_len = AD77681_CONV_24BIT,
      .crc_sel = AD77681_NO_CRC,
      .status_bit = 0,
      .VCM_out = AD77681_VCM_2_05V,
      .AINn = AD77681_AINn_ENABLED,
      .AINp = AD77681_AINp_ENABLED,
      .REFn = AD77681_BUFn_ENABLED,
      .REFp = AD77681_BUFp_ENABLED,
      .filter = AD77681_SINC5,
      .decimate = AD77681_SINC5_FIR_DECx32,
      .sinc3_osr = 0,
      .vref = AD77681_VOLTAGE_REF,
      .mclk = AD77681_MCLK,
      .sample_rate = AD77681_DEFAULT_SAMPLING_FREQ,
      .data_frame_byte = AD77681_DECIMATION_RATE,
  };

Finally setup the Device like this:

struct ad77681_dev *device = NULL;
struct ad77681_status_registers *status = NULL;
int32_t init_status = ad77681_setup(&device, ad77681_init, &status);

If the init_status is 0 then you’ve successfully initialized the device!! You would read data like this:

ad77681_spi_read_adc_data(device, data_buffer, AD77681_REGISTER_DATA_READ);

I hope this is helpful.


text:
Will an Arduino Nano work instead of Teensy 3.2?
I hope this is ok to post here and I appreciate any suggestions or help and opinions/facts to make this work.
First off I’ve Never programmed an Arduino device!
I was looking at this project:
https://learn.adafruit.com/pinball-controll-ipad/duo-pinball-teardown
I would like to use the cheaper Arduino nano type board, and use the provided code to program it.
I have the same device (pinball Duo controller as in the project) just wanted to know if I attempt this will the atmega328P Nano achieve the same results?
Thank you,
Shlade

No, Nano doesn't have native USB so it can't emulate the keyboard like teensy does. You can use Arduino Micro/Leonardo/Pro Micro or similar.

@KIIV ;-) I'd love to see answers written as answers... Isn't this site supposed to be helpful right on the front page?

No, you can't use Adruino Nano, because in this project the Teensy board has been used as an USB Keayboard and Nano has separate communication chip (FTDI or CH430) that can't emulate USB keyboard.
However you don't have to use Teensy boards, you can use any board that has native USB support. For example Arduino Micro, Arduino Pro Micro, Arduino Leonardo. All are using Atmega32u4.
You can probably find many more boards with different MCUs (usually they don't have any dedicated communication chip). I think for example RPi Pico, Seeed studio xiao BLE (on this one you might be able to pull even bluetooth mouse emulation), ...
If you want further infos here is the pinmap for you :


text:
Wemos C3 Mini (ESP32-C3) does not run firmware unless connected to pc
I've been using ESP32s and ESP8266 for a few years now and I thought I'd give these little boards a shot, they were cheaper for Bluetooth/WiFi combo, and I don't need all the bells and whistles of a full ESP32.
I have my firmware all debugged and working, it's been stable for a few months now. All it does is read a temperature from an Inkbird Bluetooth temperature sensor and log that info into a spreadsheet online for me via WiFi.
Up until this point I had the board connected via usb cable to my PC. Well I got a new PC and wanted to save a usb port so I moved it to a usb cable with an Apple AC wall adapter (5V 500mA). The board now never powers on.
Does anyone know what's happening here? It seems to not like booting unless it has a serial connection with the PC??? It doesn't like to power on if the PC is off either even though the usb port has power still.
I thought maybe this weird usb C port doesn't like 5V. So, I got it 3.3V via a breadboard power adapter rig. Nothing...

Does anyone know what's happening here? ... no ... you are the only one in a position to know ... we can guess that your code has a bug ... possibly something to do with waiting for a serial port connection

Well there you have it. That's exactly what was happening! Thank you!

next time, if you have a question, please include all info ... do not withhold important things like the code

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


text:
Processing doesn't respond to arduino
First of all if I make a wrong sentence this is because my main language isn't english.
I have a homework so i am trying to make a radar with Arduino IDE and Processing. I found and wrote the codes from internet but processing does not respond to ultrasonic sensor and i tought maybe it isn't detecting the serial port.
Code from Processing:
import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;

Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup() {

 size (1600, 900); // ***CHANGE THIS TO YOUR SCREEN RESOLUTION***
 smooth();
 myPort = new Serial(this,"COM3", 9600); // starts the serial communication
 myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
 orcFont = loadFont("Calibri-Bold-48.vlw");
}

void draw() {

  fill(98,245,31);
  textFont(orcFont);
  // simulating motion blur and slow fade of the moving line
  noStroke();
  fill(0,4);
  rect(0, 0, width, height-height*0.065);

  fill(98,245,31); // green color
  // calls the functions for drawing the radar
  drawRadar();
  drawLine();
  drawObject();
  drawText();
}

void serialEvent (Serial myPort) { // starts reading data from the Serial Port
  // reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
  data = myPort.readStringUntil('.');
  data = data.substring(0,data.length()-1);

  index1 = data.indexOf(","); // find the character ',' and puts it into the variable "index1"
  angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
  distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance

  // converts the String variables into Integer
  iAngle = parseInt(angle);
  iDistance = parseInt(distance);
}

void drawRadar() {
  pushMatrix();
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  noFill();
  strokeWeight(2);
  stroke(98,245,31);
  // draws the arc lines
  arc(0,0,(width-width*0.0625),(width-width*0.0625),PI,TWO_PI);
  arc(0,0,(width-width*0.27),(width-width*0.27),PI,TWO_PI);
  arc(0,0,(width-width*0.479),(width-width*0.479),PI,TWO_PI);
  arc(0,0,(width-width*0.687),(width-width*0.687),PI,TWO_PI);
  // draws the angle lines
  line(-width/2,0,width/2,0);
  line(0,0,(-width/2)*cos(radians(30)),(-width/2)*sin(radians(30)));
  line(0,0,(-width/2)*cos(radians(60)),(-width/2)*sin(radians(60)));
  line(0,0,(-width/2)*cos(radians(90)),(-width/2)*sin(radians(90)));
  line(0,0,(-width/2)*cos(radians(120)),(-width/2)*sin(radians(120)));
  line(0,0,(-width/2)*cos(radians(150)),(-width/2)*sin(radians(150)));
  line((-width/2)*cos(radians(30)),0,width/2,0);
  popMatrix();
}

void drawObject() {
  pushMatrix();
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  strokeWeight(9);
  stroke(255,10,10); // red color
  pixsDistance = iDistance*((height-height*0.1666)*0.025); // covers the distance from the sensor from cm to pixels
  // limiting the range to 40 cms
  if(iDistance<40){
    // draws the object according to the angle and the distance
  line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),(width-width*0.505)*cos(radians(iAngle)),-(width-width*0.505)*sin(radians(iAngle)));
  }
  popMatrix();
}

void drawLine() {
  pushMatrix();
  strokeWeight(9);
  stroke(30,250,60);
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  line(0,0,(height-height*0.12)*cos(radians(iAngle)),-(height-height*0.12)*sin(radians(iAngle))); // draws the line according to the angle
  popMatrix();
}

void drawText() { // draws the texts on the screen

  pushMatrix();
  if(iDistance>40) {
  noObject = "Out of Range";
  }
  else {
  noObject = "In Range";
  }
  fill(0,0,0);
  noStroke();
  rect(0, height-height*0.0648, width, height);
  fill(98,245,31);
  textSize(25);

  text("10cm",width-width*0.3854,height-height*0.0833);
  text("20cm",width-width*0.281,height-height*0.0833);
  text("30cm",width-width*0.177,height-height*0.0833);
  text("40cm",width-width*0.0729,height-height*0.0833);
  textSize(40);
  text("Obje: " + noObject, width-width*0.875, height-height*0.0277);
  text("Açı: " + iAngle +" °", width-width*0.48, height-height*0.0277);
  text("Mesafe: ", width-width*0.26, height-height*0.0277);
  if(iDistance<40) {
  text("        " + iDistance +" cm", width-width*0.225, height-height*0.0277);
  }
  textSize(25);
  fill(98,245,60);
  translate((width-width*0.4994)+width/2*cos(radians(30)),(height-height*0.0907)-width/2*sin(radians(30)));
  rotate(-radians(-60));
  text("30°",0,0);
  resetMatrix();
  translate((width-width*0.503)+width/2*cos(radians(60)),(height-height*0.0888)-width/2*sin(radians(60)));
  rotate(-radians(-30));
  text("60°",0,0);
  resetMatrix();
  translate((width-width*0.507)+width/2*cos(radians(90)),(height-height*0.0833)-width/2*sin(radians(90)));
  rotate(radians(0));
  text("90°",0,0);
  resetMatrix();
  translate(width-width*0.513+width/2*cos(radians(120)),(height-height*0.07129)-width/2*sin(radians(120)));
  rotate(radians(-30));
  text("120°",0,0);
  resetMatrix();
  translate((width-width*0.5104)+width/2*cos(radians(150)),(height-height*0.0574)-width/2*sin(radians(150)));
  rotate(radians(-60));
  text("150°",0,0);
  popMatrix();
}

Code from Arduino IDE:
#include <Servo.h>   // servo motor kütüphanesi
#define trigPin 4    // ultrasonik sensör trig pini
#define echoPin 3    // ultrasonik sensör echo pini
Servo servoMotor;     // servo motor nesnesi
int angle = 0;        // servo motor açısı
long duration, distance;  // ultrasonik sensör mesafesi

void setup() {
  Serial.begin(9600);  // seri haberleşme hızı
  servoMotor.attach(9); // servo motor pin numarası
}

void loop() {
  for(angle = 0; angle < 180; angle += 10){  // servo motor açıları
    servoMotor.write(angle);  // servo motoru hareket ettir
    delay(200);               // bekleme süresi
    distance = getDistance(); // mesafe ölçümü
    Serial.print(angle);      // açıyı yazdır
    Serial.print(",");
    Serial.println(distance); // mesafeyi yazdır
  }
}

long getDistance(){ // ultrasonik sensör mesafe ölçümü
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58.2;
  return distance;
}

Thank you for the help!

the processing sketch is irrelevant here ... open the Arduino IDE serial monitor to determine if the correct data is being sent by the Arduino

can you give me more details. Like i said i don't know english too much and i am new to arduino ide. And there is only the angle in the serial monitor

Your processing code is looking for something that ends in a '.'
Your arduino code is sending angle,distnace[new line]
So either change your processing code to look for '\n' (the new line character) rather than '.' or change your arduino code to add a . to the end:
Serial.print(angle);      // açıyı yazdır
Serial.print(",");
Serial.print(distance); // mesafeyi yazdır
Serial.print(".");


text:
How to connect a ps/2 keyboard to an arduino?
I want to connect an old hp ps/2 keyboard to my arduino (nucleo 64 F303RE). The keyboard has a power rating of 5v and 50mA, I guess this is milliamps.
The ps/2 connector has 4 connecting cables:
GND
VCC
CLK
DATA
I have wired up the GND to the ground of the arduino and the VCC. However, the keyboard does not properly light up or respond to the caps key being pressed. I am able to measure suppodly 5v coming out of the clock pin.
What could be the issue?
I would have expected that the keyboard would display some leds and when the caps lock would be pressed at least the caps light would turn on or off.

You'll need (very old) documentation about the PS/2 protocol. If I remember correctly, the protocol requires pulling down the clock to start the communication. And send some "A"s to initialize the device.

https://www.eecg.utoronto.ca/~jayar/ece241_08F/AudioVideoCores/ps2/ps2.html#:~:text=for%20sending%20commands-,PS%2F2%20Keyboard%20protocol,the%20host%20and%20the%20keyboard.

there is a library https://playground.arduino.cc/Main/PS2Keyboard/ . use 5V to power the keyboard and use 5 V tolerant pins on the STM32


text:
How to produce multiple DC voltages for a single project with different dc requirements
I have a project that has 2 12V .2 amp fans, and 1 30 3 amp LED COB panel, and a 5 V Arduino. I was wondering if there was a simple method to power all of these devices from a 120 V wall outlet?
As of right now considering a 30 volt AC to DC power supply. Then a series of switch buck converters. Or something along these lines.
Thanks for the help.(also I realize there was a similar post before but wanted some additional insight)

what is a 1 30 3 amp LED COB panel?

Assume "1 30 3 amp" is actually "1 30 volt 3 amp".  You can do what you said.  You can use 3 independent power supplies ... as long as you connect the grounds together (nitty gritty: As long as they are either all floating or the negative lead is ground).  But, wow, 30 volt 3 amp LED???  You sure that's a voltage regulated power supply?  Or is that a current regulated power supply?  If the latter ... well, that puts into question all our assumptions and solutions.

This is better asked on Electronics Stack Exchange

If it wasn't for the LED panel then I'd say use a mains to 12V DC power supply. You can then get small off the shelf switching regulator modules that with the addition of a couple of capacitors will reduce that down to 5V for the arduino.
If you genuinely need 3A at 30V (90 Watts of LEDs? That's a LOT of light) then use a compatible mains supply for that.
You can get off the shelf switching modules that will drop from ~30V down to 12V 1A, they are a little more expensive than 12V to 5V parts, mainly because it's a less common requirement, but a quick search on RS shows up some options for around $15.


text:
Arduino Nano not recieving MIDI Message
I'm building an MIDI to CV converter using an Arduino nano along with a MIDI input circuit, however, when uploading the code and connecting the MIDI to a laptop via USB, the Arduino doesn't recognize any input signals. Also, I'm confused on how to code for MIDI notes if anyone can offer guidance. I've followed building the circuit in the following link:
MIDI Input Circuit
Below is also the code I'm using:
/*

* Connections:

* (1) Midi Connector

* (2) DAC MCP4728:

* SDA pin to A4/SDA (Arduino Nano)

* SCL pin to A5/SCL (Arduino Nano)

* GND to GND

* VCC to +5V

* (3) Clock Rate Potentiometer

*

* Outputs:

* DAC OUT

*   Channel A-C to Drum Kit and Channel D to VCO

* Clock output with LED

* Gate 1 and 2 with LEDs

*/

#include <MIDI.h>

#include <Wire.h> // Include the Wire to talk I2C

#include <Adafruit_MCP4728.h>

// This is the I2C address of the MCP4728

#define MCP4728_ADDR 0x64

MIDI_CREATE_DEFAULT_INSTANCE();

Adafruit_MCP4728 dac;

#define GATE1 4   // pin D4 for Gate 1

#define GATE2 3   // pin D3 for Gate 2

#define G1LED 7   // pin D7 for signaling LED of Gate 1

#define G2LED 6   // pin D6 for signaling LED of Gate 2

#define CLOCK_OUT 5 // pin D5 (PWM) for Clock Out

#define CLED 8      // pin D8 for signaling LED of Clock out

float refVoltage = 5.04;  // Note cannot be higher than reference voltage

int previousNotePlayed1;

int previousNotePlayed2;

int previousNotePlayed3;

int previousNotePlayed4;

int clockRate = A0; // Potentiometer connected

int clockSpeed; // current clock speed, in milliseconds per beat

void setup() {

  // put your setup code here, to run once:

  pinMode(CLED, OUTPUT);

  pinMode(G1LED, OUTPUT);

  pinMode(G2LED, OUTPUT);

  pinMode(CLOCK_OUT, OUTPUT);

  pinMode(GATE1, OUTPUT);

  pinMode(GATE2, OUTPUT);

  MIDI.setHandleNoteOn(doThisNoteOn); // calls the function on note on

  MIDI.setHandleNoteOff(doThisNoteOff); // calls the function on note off

  MIDI.begin(MIDI_CHANNEL_OMNI);  // Listen to all midi channels

  Serial.begin(250000);

  Wire.begin();

  dac.begin(0x64);

} // end of setup

void loop() {

  // put your main code here, to run repeatedly:

  MIDI.read();  // Read incoming messages

  // Read the value of the tempo potentiometer and map it to a range of reasonable clock speeds

  int clockValue = analogRead(clockRate);

  clockSpeed = map(clockValue, 0, 1023, 1000, 250); // tempo range from 60 BPM to 240 BPM

  // send a clock pulse every clockSpeed milliseconds

  static unsigned long lastClockTime = 0;

  if (millis() - lastClockTime >= clockSpeed){

    digitalWrite(CLOCK_OUT, HIGH);

    digitalWrite(CLED, HIGH);

    delayMicroseconds(clockValue);    // initially had delayMicroseconds(10);

    digitalWrite(CLOCK_OUT, LOW);

    digitalWrite(CLED, LOW);

    lastClockTime = millis();

  }

} // end of loop

void doThisNoteOn(byte channel, byte note, byte velocity){

  if (channel == 1){  // Listen to channel 1 to set CV1

    previousNotePlayed1 = note;

    float voltPerOctave = (note - 24) * 0.0833;

    int dacInput = (voltPerOctave / refVoltage) * 4096;

    dac.setChannelValue(MCP4728_CHANNEL_A, dacInput);

    digitalWrite(GATE1, HIGH);

    digitalWrite(G1LED, HIGH);

  }

  if (channel == 2){  // Listen to channel 2 to set CV2

    previousNotePlayed2 = note;

    float voltPerOctave = (note - 24) * 0.0833;

    int dacInput = (voltPerOctave / refVoltage) * 4096;

    dac.setChannelValue(MCP4728_CHANNEL_B, dacInput);

    digitalWrite(GATE1, HIGH);

    digitalWrite(G1LED, HIGH);

  }

  if (channel == 3){  // Listen to channel 3 to set CV3

    previousNotePlayed3 = note;

    float voltPerOctave = (note - 24) * 0.0833;

    int dacInput = (voltPerOctave / refVoltage) * 4096;

    dac.setChannelValue(MCP4728_CHANNEL_C, dacInput);

    digitalWrite(GATE1, HIGH);

    digitalWrite(G1LED, HIGH);

  }

  if (channel == 4){  // Listen to channel 4 to set CV4... this CV will be used for the VCO

    previousNotePlayed4 = note;float voltPerOctave = (note - 24) * 0.0833;

    int dacInput = (voltPerOctave / refVoltage) * 4096;

    dac.setChannelValue(MCP4728_CHANNEL_D, dacInput);

   digitalWrite(GATE2, HIGH);

    digitalWrite(G2LED, HIGH);

  }

} // end of doThisNoteOn

void doThisNoteOff(byte channel, byte note, byte velocity){ //Handles note off correctly for previously played noted

  if (note == previousNotePlayed1){

    MIDI.sendNoteOff(1, note, 0);

    // velocity = 0;

    digitalWrite(GATE1, LOW);

    digitalWrite(G1LED, LOW);

  }

  if (note == previousNotePlayed2){

    MIDI.sendNoteOff(2, note, 0);

    // velocity = 0;

    digitalWrite(GATE1, LOW);

    digitalWrite(G1LED, LOW);

  }

  if (note == previousNotePlayed3){

    MIDI.sendNoteOff(3, note, 0);

    // velocity = 0;

    digitalWrite(GATE1, LOW);

    digitalWrite(G1LED, LOW);

  }

  if (note == previousNotePlayed4){

    MIDI.sendNoteOff(4, note, 0);

    // velocity = 0;

    digitalWrite(GATE2, LOW);

    digitalWrite(G2LED, LOW);

  }

} // end of doThisNoteOff

Also an image of the module:

What is the purpose of the Serial.begin call? Doesn't it use the same pins as the MIDI object?


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

are you asking if the Arduino is able to output 125 kHz signal at one of its pins? ... what diagram are you talking about?

The communication between MCU (Arduino) and IC (PCF7991AT) can work at any frequency (like SPI or I2C). The 125khz antenna frequency is generated in the IC internally. But you need to set the divider of the clock source (your crystal hooked up to the IC)
https://datasheet.lcsc.com/lcsc/2208260930_NXP-Semicon-PCF7991AT-1081-M_C5143533.pdf
See
page 7 -> 8.4 short explanation
page 13 -> to set the register
Hope this helps!

The Arduino is indeed capable of generating a 125kHz signal.
This example generates a 125kHz signal (50% duty cycle) on digital pin 3 of an Arduino Uno/Nano using Timer 2.
const int pulsePin = 3;  // note OC2B Pin D3 ! ! !
volatile uint32_t pulseCount = 0;

void setup(){

  pinMode(pulsePin, OUTPUT);

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

void loop() {
}

and how i check rising of the timer?, i need to read a particular register to see if timer is rised and eventually set to 0 after?


text:
Connect ESP32 cam to the Nodemcu motor shield
Is it possible to connect ESP32 cam to the Nodemcu motor shield? I already have a ESP8266 chip connected to the Nodemcu motor shield.
In get this error after connecting this ESP32 cam to the Nodemcu motor shield like this
VCC: Connect to 5V on the NodeMCU motor shield
GND: Connect to GND on the NodeMCU motor shield
UnR: Connect to TX on the NodeMCU motor shield
U0T: Connect to RX on the NodeMCU motor shield

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


text:
Using library functions in timer ISR ESP32
I'm trying to use a library function in my ISR function that uses the internal timer to trigger every 1 ms. The chip that I'm using is an ESP32-C3-MINI. Here is my current code:
main.cpp
#include <Arduino.h>
hw_timer_t *_timer = NULL;
myClass a();

void IRAM_ATTR isr()
{
    a.incrementCount();
}

void setup()
{
    coin_timer = timerBegin(0, 80, true);
    timerAttachInterrupt(_timer, &isr, true);
    timerAlarmWrite(_timer, 1000, true);
    timerAlarmEnable(_timer);
}

myClass.h
#include <Arduino.h>

class myClass
{
private:
    unsigned long count;

public:
    myClass();
    ~myClass();

    void incrementCount();
}

myClass.cpp
#include <Arduino.h>
#include "myClass.h"

myClass::myClass(){

}

void myClass::incrementCount(){
    count++;
}

This is just an example of the code that I wrote. In reality, the incrementCount function is a little more complicated and involves multiple variables and arrays within the library. This current code compiles and works without an issue. However, I would like to know if this method is bad practice or can cause problems in certain situations. Secondly, I notice if I declare count variable as volatile, the MCU just crashes and enters a reboot cycle.


text:
How to create 2 individual daisy chains using the MAX7219 Module and Mega2560
I am using MAX7219 8 digit 7 segment displays with Arduino Mega2560. Now, I have to physically space out the displays far from each other. Hence, after a certain distance the displays on the far end start flickering. So, can we setup 2 individual daisy chains using the MAX7219 module with Arduino Mega2560.
Thanks for helping out in advance.


text:
Serial plotting a pwm
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 :

What I expected (exemple found on the internet :

Look at the output of your sketch on the serial monitor, not on the plotter. It should become immediately clear what is going on.

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).


text:
Problem with reading data from ELM327
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.

Do you have a manual or doc for ELM327 v2.1 that you can share?

@Fahad unfortunately not if you find on the Internet

I can't seem to find it. How do you know of the AT commands? Is there an instruction somewhere?

try AT$ ... it worked on old modems to display the available command set ... maybe the command is also implemented in your device

ELM has closed down, but as a curtesy have kept their documentation site available.  Here's the link to the last version published, V2.3 in 2020 -
https://www.elmelectronics.com/DSheets/ELM327DSL.pdf
The following is what I think the doc says -

ELM's external data exchange mechanism uses 4 bit hexadecimal 'nibbles', with 2 payload nibbles in each 8 bit 'byte' which may be 'padded' with a leading, empty, '0000' high nibble when only a single 4 bit low nibble is output.

ELM327 directives are text characters that start with 'AT' (or 'at', they are not case sensitive); these always have at least 1 bit set in their first high nibble.  OBDII request nibbles start with a single hexidecimal 0 digit that never has any of the high nibble bits set, making it easy for the ELM327 to differentiate between directives and OBDII requests by examining just the first byte of any new message sent to it.

All exchanges are terminated with a Carriage Return , which is represented as ASCII code 13; 0xD, or C char '\r'.  But Arduino (& C) Strings expect a 'nul terminator = '\0'.  Take care to use commands that correctly terminate Strings.

A timeout period is used when awaiting a reply from the OBDII.  After receipt a new timeout period is applied in case of additional responses (up to a '\r').  Only after a timeout does occur will the ELM327 pass the data out and prepare to become ready to accept a new directive or request.  It will often do some internal housekeeping before sending the '\r' end of reply or the '>' ready prompt.  [The timeout period is adaptive and will be automatically reduced to the shortest possible, safe time]
[Sending a single nibble 'count' value at the end of a request returns as soon as it gets just that many data bytes from the OBDII]

The ELM327 uses '>' as a ready or prompt symbol.  Do not attempt communication until a prompt has been received.

Incomplete or un-terminated commands will still be sent from the ELM327 to the OBDII after a timeout.  The ELM327 will return a single '?' to indicate that the directive or request was either garbled, did not end in '\r' or no data was returned.

OBDII requests and data returns are defined as bytes.  ELM327 exchanges are performed via nibbles.  UARTs use char bytes.
So OBDII requests must be converted from the byte form (shown in the docs) to padded nibbles to be sent/returned to/from the ELM327.

ELM327 Requests start with a 2 nibble Mode value from 0 1 to 0 B, then a 4 to 8 nibble Parameter IDentity (PID) and finally a 2 nibble representation of '\r' (0 D).

ELM327 Replies add 0x40 to the first Mode nibble, then pass out the modified Mode byte, the PID and returned data terminated with '\r'.  This raw data stream needs to be re-assembled into separate bytes before interpreting.

The Mode & PID echo may be turned off, if desired, with the directive 'AT E0 \r'.  Spaces are optional, 'ATE0\r' works fine.
[Some older ELM327 devices may occasionaly return a '\0' = null charactor, these should be stripped from the raw data stream]

Sending a bare '\r' to the ELM327 is interpreted as 'repeat' the last directive or request.  The fastest repeat data collecting method requires a request with a return data length nibble sent first, then a new '\r' as soon as the prompt appears.

OBDII data exchanges -

Headers, Mode, PID and checksums must be created/assembled by an external device then passed into an OBDII system using whichever protocol the vehical manufacturer has chosen (from the types defined in the OBDII specifications).  Replies need to be verified (using returned Mode, PID and a return checksum); the ELM327 does all this pre- and post data encoding and verification internally.  If you choose to do this in your own code then 'good luck'.

Returned data can be bit encoded, single bytes or a string of byte values.  Some values are offset to extend the data range to include a negative portion within the bounds of a single, unsigned byte (0 to 255).

OBDII bytes are little-endian, and when combined into data words, whole data words are in little-endian order too.

The maximum returned 'standard' data payload is 41 bytes for various elapsed times, but most are much, much shorter.

Vehicle manufactures may return data of any desired length, so watch out for the '>' from the ELM327.

Data may be returned in multiple blocks.  For example the 17 byte Vehical Identification Number (VIN) is returned as 5 off 4 byte words.  Request Mode 09 PID 02 returns "0 1 2 3", "4 5 6 7", "8 9 10 11", "12 13 14 15", "16 x x x"  with no '\r' between them, just the one at the end; this should be assembled into  "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 x x x".

Example ELM327 request - RPM is Mode 01, PID 12.  Convert from decimal to hex - 01, 0C.  Pad from 4 nibbles to 4 bytes - 00 01 00 0C.
Add '\r'.  Wait for '>', then send.  Wait for reply to fully arrive ('\r' received).
Example ELM327 reply - 40 01 00 0C 1A F8 '\r'.  Discard the modified request echo and header (if left On), then convert the returned hex to decimal 1A F8 -> 26 248, assemble the 2 byte word (26 * 256) + 248 = 6904.  Divide /4 to convert to 1726 rpm.
Wait till a '>' is received before sending a new request.
Note little-endian byte order - 248 little end sent first, then big end (26 * 256).


text:
Problem when coding 4x4 keypad's key detection (without library)
Part of my current assignment involves reading the input from a 4x4 keypad connected to an Arduino UNO. While this may be done easily using <Keypad.h>, the project is being done with Tinkercad's online simulator, meaning I don't have access to that library. I have to do it the manual way.
This is the code I've got so far:
#include <Wire.h>
#define DIMENSIONS 4
const unsigned long period = 50;
unsigned long prevMillis = 0;
byte modo = 0;
const byte rowsPins[DIMENSIONS] = {11, 10, 9, 8};
const byte columnsPins[DIMENSIONS] = {7, 6, 5, 4};
char keys[DIMENSIONS][DIMENSIONS] = {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};

void setup()
{
    Serial.begin(9600);// debug
    for(byte i = 0; i < DIMENSIONS; i++){
        pinMode(columnsPins[i], INPUT);
        digitalWrite(columnsPins[i], HIGH);
        pinMode(rowsPins[i], INPUT_PULLUP);
    }
    Wire.begin();
}

void loop()
{
    switch(modo){
        case 0:
            Serial.print("Master (2) boot up\n");
            modo++;
            break;
        case 1:
            if(millis() >= 1000){
                modo++;
            }
            break;
        case 2:
            if (millis() - prevMillis > period){
                prevMillis = millis();
                for(byte c = 0; c < DIMENSIONS; c++){
                    pinMode(columnsPins[c], OUTPUT);
                    digitalWrite(columnsPins[c], LOW);
                    for(byte r = 0; r < DIMENSIONS; r++){
                        if(digitalRead(columnsPins[r]) == LOW){
                            Serial.println(keys[r][c]);
                        }
                    }
                    digitalWrite(columnsPins[c], HIGH);
                    pinMode(columnsPins[c], INPUT);
                }
            }
            break;
        default:
            break;
    }
}

(the "modes" and Wire.h are a different part of the assignment and not related to my issue)
This code should, in theory, read the input from the connected 4x4 keypad and then print on the serial monitor which key was pressed. I've done a fair bit of searching, and other solutions for detecting key presses without the Keypad library aren't super different from what I've done here. However, for some reason, what I wrote is not working properly for me.
On starting the simulation, the serial monitor prints 1, 5, 9, D continuously and repeatedly on a loop. Pressing the keys does sometimes print the appropriate character, but it does not stop the flood of 1s, 5s, 9s and Ds.
I know for a fact that it's not a matter of the pins being misconnected, I've checked for that at least a dozen times by now. It's most certainly a matter of code... but I can't figure out where the problem lies.

you could add a 4x4 array to store button state ... then do a 50 ms debounce delay whenever the button state changes

In case 2:
digitalWrite(columnsPins[c], LOW);
for(byte r = 0; r < DIMENSIONS; r++){
   if(digitalRead(columnsPins[r]) == LOW){
   Serial.println(keys[r][c]);
   }
}

Since you just wrote one of the column pins low, you can guarantee that one is going to read low.  Did you mean to read the row pins?

I can't believe I did not notice such an obvious mistake. Thanks for the save, Delta_G.

Post a annotated schematic as to how you have actually wired the keyboard, be sure to show all resistors and diodes.

@Gil not a keyboard, just a humble 4x4 keypad. Here you go. It's extremely simple, the pins on the Arduino are connected directly to the keypad, so I didn't feel it was necessary to include it in the OP.

@Maf95 "When a programmer has a hard time finding a bug, it's because he's looking in the wrong place."


text:
Instructables "Omnibot" -- using the "real" Uno R3 board
Step 4 of this instructable uses what seems to be a "knock-off" development version of the Uno R3 board, where an RF receiver is soldered to pads that don't exist on the R3 or R3 SMD boards:
https://www.instructables.com/OmniBot-Easy-Arduino-RC-Robots/

...

Locate available Gnd, Vcc, and Rx holes on your Arduino. (if using the recommended Arduino they can be found all near each other just below the ICSP pins.)
Insert the tinned wires through their respective holes and solder on the back side. White to RX, red to 5V, black to GND.

...

I am completely new to Arduino, so I'm a little puzzled by the lack of VCC. Sounds like this is just power. Is there any reason I can't hook the RF receiver to the D0 (RX) pin, 5v out, and GND headers?

Vcc is positive voltage supply ... 5 V

your question becomes useless when the instructables link dies ... please add the necessary diagrams to your question

Yes, the holes they are showing it connected to are physically connected to the pins you mention.  Connecting directly to those pins would be equivalent.


text:
arduino nano fried (TWICE!!)
Having the skill to be stupid has managed to fry not one but 2 Arduino nano boards in the same place (I think it is because this part that smoke came out from of has a lump on it that was not there before). I have heard that Arduino boards are open source, but I have not found anything explaining which part I have fried. Therefore, I don't know the function, so I cannot replace it. It would be greatly appreciated if anyone could point out the part name or a link to a shop with it in stock so I could purchase it or give me a copy of the PCB schematics to make my own Arduino.
I think the part is called the "usb diode"
Thanks

what exactly is your question?

is there a way to fix it without getting a new one?

From the several Arduino Nano schematics I've found, the "fried" part you identify as the USB diode, might be a MBR0520 Schottky diode or a similar diode with a low forward voltage drop. These parts are polarized and should be replaced in the same orientation as the original part.
There is no guarantee that this is the only damaged component on your Nano.

would the anwser change if i mentioned that this is an arduino clone

The clones that I've found schematics for, have similar Schottky diodes. Still, no guarantees.

somehow, one still works! I don't know how, and don't want to question it!


text:
Sounds are being played at the same time
I'm making a school project that allows plants to 'talk'. As in when the plant is in an un-ideal environment (low or high soil moisture, not ideal temperature or humidity and not enough light). I have currently made some demo code for my presentation as the real code has real thresholds and is hard to trigger instantly during the presentation.
The problem im facing is that the sound is almost always cut off by another one, how can i stop this, also the recordings are all 7 seconds or less.
#include <DHT.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>
#include <LiquidCrystal_I2C.h>
//-----------------DEMO---CODE-------
#define DHTPIN 3
#define DHTTYPE DHT22
#define SOIL_MOISTURE_PIN A0
#define LIGHT_SENSOR_PIN 2
#define TEMP_THRESHOLD 25.0
#define HUMIDITY_THRESHOLD 60
#define LIGHT_THRESHOLD 1  // 1 for dark, adjust as needed
#define LOWER_SM_THRESHOLD 20 // Adjust as needed
#define UPPER_SM_THRESHOLD 50 // Adjust as needed
#define LCD_ADDR 0x27  // I2C address of the LCD
#define LCD_COLUMNS 16
#define LCD_ROWS 2
#define MESSAGE_INTERVAL 20000  // 20 seconds in milliseconds

DHT dht(DHTPIN, DHTTYPE);
SoftwareSerial mySoftwareSerial(10, 11);  // RX, TX for DFPlayer
DFRobotDFPlayerMini myDFPlayer;
LiquidCrystal_I2C lcd(LCD_ADDR, LCD_COLUMNS, LCD_ROWS);

unsigned long lastTempTrigger = 0;
unsigned long lastHumidityTrigger = 0;
unsigned long lastSoilMoistureTrigger = 0;
unsigned long lastLightTrigger = 0;

void setup() {
  dht.begin();
  Serial.begin(9600);
  mySoftwareSerial.begin(9600);
  myDFPlayer.begin(mySoftwareSerial);

  myDFPlayer.volume(30);

  // Initialize the LCD
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");
  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Plantastic!");
  lcd.setCursor(0, 1);
  lcd.print("System Ready");
  delay(2000);
  lcd.clear();
}

void loop() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  int lightValue = digitalRead(LIGHT_SENSOR_PIN);
  int soilMoistureValue = analogRead(SOIL_MOISTURE_PIN);
  int soilMoisturePercentage = 100 - (map(soilMoistureValue, 0, 1023, 0, 100));

  if (temperature > TEMP_THRESHOLD && millis() - lastTempTrigger >= MESSAGE_INTERVAL) {
    myDFPlayer.play(3);  // Play "Too Hot" message
    lastTempTrigger = millis();
  } else if (temperature < TEMP_THRESHOLD && millis() - lastTempTrigger >= MESSAGE_INTERVAL) {
    myDFPlayer.play(1);  // Play "Too Cold" message
    lastTempTrigger = millis();
  }

  if (round(humidity) < HUMIDITY_THRESHOLD && millis() - lastHumidityTrigger >= MESSAGE_INTERVAL) {
    myDFPlayer.play(2);  // Play "Low Humidity" message
    lastHumidityTrigger = millis();
  }

  if (soilMoisturePercentage < LOWER_SM_THRESHOLD && millis() - lastSoilMoistureTrigger >= MESSAGE_INTERVAL) {
    myDFPlayer.play(6);  // Play "Thirsty" message
    lastSoilMoistureTrigger = millis();
  } else if (soilMoisturePercentage > UPPER_SM_THRESHOLD && millis() - lastSoilMoistureTrigger >= MESSAGE_INTERVAL) {
    myDFPlayer.play(5);  // Play "Enough Water" message
    lastSoilMoistureTrigger = millis();
  }

  if (lightValue == 1 && millis() - lastLightTrigger >= MESSAGE_INTERVAL) {
    myDFPlayer.play(4);  // Play "It's dark in here" message
    lastLightTrigger = millis();
  }

  // Update the LCD display
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("T: ");
  lcd.print(temperature, 2);
  lcd.print(" H: ");
  lcd.print(humidity, 2);
  lcd.setCursor(0, 1);
  lcd.print("SM: ");
  lcd.print(soilMoisturePercentage);
  lcd.print("% L: ");
  lcd.print(lightValue == LIGHT_THRESHOLD ? "Dark" : "Light");

  delay(1000);
}

You could check, if something is playing before executing play()

no the first bit of sound plays, like the first second or half second but it is then cut off by another sound so you can't hear t completely

Can't you just wait for the sound to end before continuing? If you loose an iteration because of the sound being played is probably not an issue (you're updating at most every second anyway)

I'm not talking of the user waiting the sounds to be finished. What you describe indicates that you execute the play() function, before the last sound ended. The dfplayer should also have a command, which will return the play status. If you insert an if clause for every call of play() to check if something is already playing, then you can prevent this interruption

There are 2 approaches which address the problem of not playing a sound to completion.

Place a delay loop after each call to myDFPlayer.play() designed to last as long as the played sound. This is likely the most straight forward solution.  However, adding delays where no other code is able to run is considered bad programming form.  It also creates problem when adding new features to the program.
Create a finite state machine where the loop() function has no delays.  Instead use a variable to track the state the state machine is in and only change that variable when the conditions to go to the next state have been satisfied.  For instance, do nothing until a threshold (dryness, light, ect) has been crossed.  At which point switch to the state where you play back the associated sound & clear that threshold flag.  Do not exit that state until millis() has increased past the duration of the played sound.  Finally, repeat these state transitions for any other thresholds that have been crossed.  Complex behaviors dealing with how long before repeating a sound can then be added with additional states.


text:
Arduino and Arduino-Cli how to specify include paths?
While this might appear to be a duplicate of this question Loading local libraries it isn't, and for one very simple reason.  That question deals with libraries that are expected to be used by multiple sketches, while the problem I have is to do with the architecture of a single sketch.
I have a sketch where it makes a lot of sense to divide the source into multiple subdirectories.  To give some idea of the scale I'm talking about it's ~20,000 LOC spread over ~100 .cpp/.h files, along with the obligatory .ino.  So I have the following layout:
sketch/
    sketch.ino
    src/
        module/
            module.h
            module.cpp

which while much smaller than the actual project is enough to demonstrate the problem.
Forget about "flattening" it all out into the sketch folder, no sane minded software engineer should ever consider doing that, not with a project the size I've outlined.
If I place the line
#include "module.h"

in sketch.ino I get the following error from the Arduino IDE:
C:\path\to\sketch\sketch.ino:3:10: fatal error: module.h: No such file or directory
    3 | #include "module.h"
      |          ^~~~~~~~~~
compilation terminated.

exit status 1

Compilation error: module.h: No such file or directory

I get the same error when using Arduino-Cli.exe to compile the sketch.
EVERY other C/C++ compiler on planet Earth offers an option akin to the -I of GCC and MSVC to allow me to specify other folders to include in the header search.
How is this done with Arduino, so that I can get module to compile correctly?  As noted in the linked question, I could use a full path, but that's (A) ugly, and (B) unnecessary.
Header search paths are a thing, how do I do them with the Arduino toolchain?

It's not in the same folder is it? How about trying: #include "src/module/module.h". However I'm not convinced that will work. The IDE copies your files into a working directory.

my guess would be #include "module/module.h". src is searched. src/module isn't. https://arduino.github.io/arduino-cli/0.35/sketch-specification/#src-subfolder

Looking at the arduino-cli doc, can't the flag --libraries do the job?

@nickb That's a bit of a hack, and might be able to solve the problem for arduino-cli, but it does nothing for the ide itself.

@dgnuff Then Platformio might better fits your needs. IIRC, you can setup multiple include and libraries per project.

@NickB That's a good suggestion.  I finally bit the bullet, and did the transition over to PlatformIO.  There were a few teething troubles as I got everything set up, but the end result is a development environment that's vastly superior to the Arduino IDE.  I'm able to use Visual Studio as my IDE, and just use an NMAKE project configuration with a call to pio run to build the project.  Since GCC does the heavy lifting, adding a -I option  is trivial ...

...  and the icing on the cake is that I can have metadata in platformio.ini that allws me to build for multiple target platforms.  Another project I have can be built for either ESP32-S2 or Pi Pico W.  PlatformIO handles this flawlessly, while Arduino trips over it's own feet trying to do such a simple thing.


text:
Pn532 doesnt detect sometimes
Im using ESP32 with PN532 NFC module with I2C
And Im using this library https://github.com/elechouse/PN532
And using this documents https://www.elechouse.com/elechouse/images/product/PN532_module_V3/PN532_%20Manual_V3.pdf
Normally, it finds the PN532 and reads the card successfully when I scan it. However, sometimes after starting, it doesn't detect the PN532 and never finds it.It say PN53x card not found!. When I unplug and plug in the sensor cable, the ESP32 can detect the sensor, but I shouldn't have to do it this way. Therefore, if it can't find the PN532 twice, I wanted to reset it as follows:
void resetPN532() {
digitalWrite(PNP532_IRQ_Pin, LOW);
delay(100);
digitalWrite(PNP532_IRQ_Pin, HIGH);
delay(100);
digitalWrite(PNP532_RSTO_Pin, LOW);
delay(100);
digitalWrite(PNP532_RSTO_Pin, HIGH);
 }

This is code for the find:
`  uint32_t versiondata = nfc.getFirmwareVersion();

  if (Serial.available() > 0) {
  processCommand("command");
  }

  if (!versiondata) {
    Serial.println("PN53x card not found!");
    resetCounter++;
    if (resetCounter >= 2) {
      Serial.println("Reset PNP");
      resetPN532();
      resetCounter = 0;
    }

    return false;
  }

`

This is my connections:
enter image description here
Why I faced with this issue I dont know but how can I solve this problem ?
. When I unplug and plug in the sensor cable, the ESP32 can detect the sensor, but I shouldn't have to do it this way. Therefore, if it can't find the PN532 twice, I wanted to reset it as follows:

the code does not compile without error

I share the part of the code. Not all of them

@jsotola what you mean?

" PN53x card not found" basically means it can't establish a communication with PN53x. You need to check your wiring, your power supply, your noise, and your code. to find out the root cause. If the sensor can't be found, how can you be sure that you can reset it via software? You got one problem in establishing a communication, instead of finding the root cause, now you got two problems.


text:
Diecimila with firmata standard not working
Hi would like to use an old Diecimila with home-assistant, and that seems to imply installing firmata-standard.
That fails since there is not enough space on the board.
Is there a workaround (I only need inputs, maybe even only digital)?
What would be a good way forward otherwise? Is there an alternative to firmata for homeassistant?  Or should I just buy a newer board?

You could try ConfigurableFirmata instead. I haven't tried it with such old boards, but when you only need digital I/O, it could even be smaller than StandardFirmata.

The error message was:
Sketch uses 13172 bytes (91%) of program storage space. Maximum is 14336 bytes.
Global variables use 1113 bytes (108%) of dynamic memory, leaving -89 bytes for local variables. Maximum is 1024 bytes.

Huh. I thought I got it compiling but I'm getting a similar message now, although with a different memory number, still not enough memory though.  So, I'm going vote up your comment and delete my own. You should edit that detail into your question because it's important. It may be good to mention which board core and firmata library versions are in use. And even though the error message kind of contains this information, you may want to be explicit about ATmega168. And, I'll see what I can do locally with what I have.

Is there a workaround (I only need inputs, maybe even only digital)?

OldStandardFirmata
I don't know enough about homeassistant to know what you need exactly. But it seems very likely that you can and probably should use OldStandardFirmata. And it is so similar to the modified StandardFirmata (below) that it will probably just work for you. It uses 505 (reported) bytes of RAM.
AllInputsFirmata may also work, but it's RAM usage is only a percent smaller.
Modifying StandardFirmata
That said, it looks like you can get StandardFirmata.ino from current version 2.5.9 to be within limits by removing everything associated with I2C and Servo. It is probably worth trying OldStandardFirmata first, because much of these changes are what makes the difference between the Old and not-Old examples.
Under AVR support version 1.8.7.
Sketch uses 7978 bytes (55%) of program storage space. Maximum is 14336 bytes.
Global variables use 522 bytes (50%) of dynamic memory, leaving 502 bytes for local variables. Maximum is 1024 bytes.

So, slightly larger than OldStandardFirmata.

Action
Reported Global variables

Nothing
1079 bytes

Removing only I2C
650 bytes

Removing servo
951 bytes

Removing both I2C and SERVO
522 bytes

Removing servo-related stuff doesn't lower the ram using
that much but it does remove some lines from this post.
Removing analogWrite, analogRead can remove nontrivial amounts of code, but doesn't affect the memory footprint much. The final size is similar to OldFirmataStandard's size.
The following may work for you. It's the example in entirety after removing I2C and Servo related parts. I would have changed the formatting a bit, but leaving it as is you should be able to diff it against the original to see the changes if you care to.
/*
  Firmata is a generic protocol for communicating with microcontrollers
  from software on a host computer. It is intended to work with
  any host computer software package.

  To download a host software package, please click on the following link
  to open the list of Firmata client libraries in your default browser.

  https://github.com/firmata/arduino#firmata-client-libraries

  Copyright (C) 2006-2008 Hans-Christoph Steiner.  All rights reserved.
  Copyright (C) 2010-2011 Paul Stoffregen.  All rights reserved.
  Copyright (C) 2009 Shigeru Kobayashi.  All rights reserved.
  Copyright (C) 2009-2016 Jeff Hoefs.  All rights reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  See file LICENSE.txt for further informations on licensing terms.

  Last updated August 17th, 2017
*/

#include <Firmata.h>

// the minimum interval for sampling analog input
#define MINIMUM_SAMPLING_INTERVAL   1

/*==============================================================================
 * GLOBAL VARIABLES
 *============================================================================*/

#ifdef FIRMATA_SERIAL_FEATURE
SerialFirmata serialFeature;
#endif

/* analog inputs */
int analogInputsToReport = 0; // bitwise array to store pin reporting

/* digital input ports */
byte reportPINs[TOTAL_PORTS];       // 1 = report this port, 0 = silence
byte previousPINs[TOTAL_PORTS];     // previous 8 bits sent

/* pins configuration */
byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else

/* timer variables */
unsigned long currentMillis;        // store the current value from millis()
unsigned long previousMillis;       // for comparison with currentMillis
unsigned int samplingInterval = 19; // how often to run the main loop (in ms)

/* i2c data */
struct i2c_device_info {
  byte addr;
  int reg;
  byte bytes;
  byte stopTX;
};

boolean isResetting = false;

// Forward declare a few functions to avoid compiler errors with older versions
// of the Arduino IDE.
void setPinModeCallback(byte, int);
void reportAnalogCallback(byte analogPin, int value);
void sysexCallback(byte, byte, byte*);

/*==============================================================================
 * FUNCTIONS
 *============================================================================*/

void outputPort(byte portNumber, byte portValue, byte forceSend)
{
  // pins not configured as INPUT are cleared to zeros
  portValue = portValue & portConfigInputs[portNumber];
  // only send if the value is different than previously sent
  if (forceSend || previousPINs[portNumber] != portValue) {
    Firmata.sendDigitalPort(portNumber, portValue);
    previousPINs[portNumber] = portValue;
  }
}

/* -----------------------------------------------------------------------------
 * check all the active digital inputs for change of state, then add any events
 * to the Serial output queue using Serial.print() */
void checkDigitalInputs(void)
{
  /* Using non-looping code allows constants to be given to readPort().
   * The compiler will apply substantial optimizations if the inputs
   * to readPort() are compile-time constants. */
  if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false);
  if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false);
  if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false);
  if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false);
  if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false);
  if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false);
  if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false);
  if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false);
  if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false);
  if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false);
  if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false);
  if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false);
  if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false);
  if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false);
  if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false);
  if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false);
}

// -----------------------------------------------------------------------------
/* sets the pin mode to the correct state and sets the relevant bits in the
 * two bit-arrays that track Digital I/O and PWM status
 */
void setPinModeCallback(byte pin, int mode)
{
  if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE)
    return;

  if (IS_PIN_ANALOG(pin)) {
    reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting
  }
  if (IS_PIN_DIGITAL(pin)) {
    if (mode == INPUT || mode == PIN_MODE_PULLUP) {
      portConfigInputs[pin / 8] |= (1 << (pin & 7));
    } else {
      portConfigInputs[pin / 8] &= ~(1 << (pin & 7));
    }
  }
  Firmata.setPinState(pin, 0);
  switch (mode) {
    case PIN_MODE_ANALOG:
      if (IS_PIN_ANALOG(pin)) {
        if (IS_PIN_DIGITAL(pin)) {
          pinMode(PIN_TO_DIGITAL(pin), INPUT);    // disable output driver
#if ARDUINO <= 100
          // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6
          digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
#endif
        }
        Firmata.setPinMode(pin, PIN_MODE_ANALOG);
      }
      break;
    case INPUT:
      if (IS_PIN_DIGITAL(pin)) {
        pinMode(PIN_TO_DIGITAL(pin), INPUT);    // disable output driver
#if ARDUINO <= 100
        // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6
        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
#endif
        Firmata.setPinMode(pin, INPUT);
      }
      break;
    case PIN_MODE_PULLUP:
      if (IS_PIN_DIGITAL(pin)) {
        pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP);
        Firmata.setPinMode(pin, PIN_MODE_PULLUP);
        Firmata.setPinState(pin, 1);
      }
      break;
    case OUTPUT:
      if (IS_PIN_DIGITAL(pin)) {
        if (Firmata.getPinMode(pin) == PIN_MODE_PWM) {
          // Disable PWM if pin mode was previously set to PWM.
          digitalWrite(PIN_TO_DIGITAL(pin), LOW);
        }
        pinMode(PIN_TO_DIGITAL(pin), OUTPUT);
        Firmata.setPinMode(pin, OUTPUT);
      }
      break;
    case PIN_MODE_PWM:
      if (IS_PIN_PWM(pin)) {
        pinMode(PIN_TO_PWM(pin), OUTPUT);
        analogWrite(PIN_TO_PWM(pin), 0);
        Firmata.setPinMode(pin, PIN_MODE_PWM);
      }
      break;
    case PIN_MODE_I2C:
      if (IS_PIN_I2C(pin)) {
        // mark the pin as i2c
        // the user must call I2C_CONFIG to enable I2C for a device
        Firmata.setPinMode(pin, PIN_MODE_I2C);
      }
      break;
    case PIN_MODE_SERIAL:
#ifdef FIRMATA_SERIAL_FEATURE
      serialFeature.handlePinMode(pin, PIN_MODE_SERIAL);
#endif
      break;
    default:
      Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM
  }
  // TODO: save status to EEPROM here, if changed
}

/*
 * Sets the value of an individual pin. Useful if you want to set a pin value but
 * are not tracking the digital port state.
 * Can only be used on pins configured as OUTPUT.
 * Cannot be used to enable pull-ups on Digital INPUT pins.
 */
void setPinValueCallback(byte pin, int value)
{
  if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) {
    if (Firmata.getPinMode(pin) == OUTPUT) {
      Firmata.setPinState(pin, value);
      digitalWrite(PIN_TO_DIGITAL(pin), value);
    }
  }
}

void analogWriteCallback(byte pin, int value)
{
  if (pin < TOTAL_PINS) {
    switch (Firmata.getPinMode(pin)) {
      case PIN_MODE_PWM:
        if (IS_PIN_PWM(pin))
          analogWrite(PIN_TO_PWM(pin), value);
        Firmata.setPinState(pin, value);
        break;
    }
  }
}

void digitalWriteCallback(byte port, int value)
{
  byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0;

  if (port < TOTAL_PORTS) {
    // create a mask of the pins on this port that are writable.
    lastPin = port * 8 + 8;
    if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS;
    for (pin = port * 8; pin < lastPin; pin++) {
      // do not disturb non-digital pins (eg, Rx & Tx)
      if (IS_PIN_DIGITAL(pin)) {
        // do not touch pins in PWM, ANALOG, SERVO or other modes
        if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) {
          pinValue = ((byte)value & mask) ? 1 : 0;
          if (Firmata.getPinMode(pin) == OUTPUT) {
            pinWriteMask |= mask;
          } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) {
            // only handle INPUT here for backwards compatibility
#if ARDUINO > 100
            pinMode(pin, INPUT_PULLUP);
#else
            // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier
            pinWriteMask |= mask;
#endif
          }
          Firmata.setPinState(pin, pinValue);
        }
      }
      mask = mask << 1;
    }
    writePort(port, (byte)value, pinWriteMask);
  }
}

// -----------------------------------------------------------------------------
/* sets bits in a bit array (int) to toggle the reporting of the analogIns
 */
//void FirmataClass::setAnalogPinReporting(byte pin, byte state) {
//}
void reportAnalogCallback(byte analogPin, int value)
{
  if (analogPin < TOTAL_ANALOG_PINS) {
    if (value == 0) {
      analogInputsToReport = analogInputsToReport & ~ (1 << analogPin);
    } else {
      analogInputsToReport = analogInputsToReport | (1 << analogPin);
      // prevent during system reset or all analog pin values will be reported
      // which may report noise for unconnected analog pins
      if (!isResetting) {
        // Send pin value immediately. This is helpful when connected via
        // ethernet, wi-fi or bluetooth so pin states can be known upon
        // reconnecting.
        Firmata.sendAnalog(analogPin, analogRead(analogPin));
      }
    }
  }
  // TODO: save status to EEPROM here, if changed
}

void reportDigitalCallback(byte port, int value)
{
  if (port < TOTAL_PORTS) {
    reportPINs[port] = (byte)value;
    // Send port value immediately. This is helpful when connected via
    // ethernet, wi-fi or bluetooth so pin states can be known upon
    // reconnecting.
    if (value) outputPort(port, readPort(port, portConfigInputs[port]), true);
  }
  // do not disable analog reporting on these 8 pins, to allow some
  // pins used for digital, others analog.  Instead, allow both types
  // of reporting to be enabled, but check if the pin is configured
  // as analog when sampling the analog inputs.  Likewise, while
  // scanning digital pins, portConfigInputs will mask off values from any
  // pins configured as analog
}

/*==============================================================================
 * SYSEX-BASED commands
 *============================================================================*/

void sysexCallback(byte command, byte argc, byte *argv)
{
  byte mode;
  byte stopTX;
  byte slaveAddress;
  byte data;
  int slaveRegister;
  unsigned int delayTime;

  switch (command) {
    case SAMPLING_INTERVAL:
      if (argc > 1) {
        samplingInterval = argv[0] + (argv[1] << 7);
        if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) {
          samplingInterval = MINIMUM_SAMPLING_INTERVAL;
        }
      } else {
        //Firmata.sendString("Not enough data");
      }
      break;
    case EXTENDED_ANALOG:
      if (argc > 1) {
        int val = argv[1];
        if (argc > 2) val |= (argv[2] << 7);
        if (argc > 3) val |= (argv[3] << 14);
        analogWriteCallback(argv[0], val);
      }
      break;
    case CAPABILITY_QUERY:
      Firmata.write(START_SYSEX);
      Firmata.write(CAPABILITY_RESPONSE);
      for (byte pin = 0; pin < TOTAL_PINS; pin++) {
        if (IS_PIN_DIGITAL(pin)) {
          Firmata.write((byte)INPUT);
          Firmata.write(1);
          Firmata.write((byte)PIN_MODE_PULLUP);
          Firmata.write(1);
          Firmata.write((byte)OUTPUT);
          Firmata.write(1);
        }
        if (IS_PIN_ANALOG(pin)) {
          Firmata.write(PIN_MODE_ANALOG);
          Firmata.write(10); // 10 = 10-bit resolution
        }
        if (IS_PIN_PWM(pin)) {
          Firmata.write(PIN_MODE_PWM);
          Firmata.write(DEFAULT_PWM_RESOLUTION);
        }
        if (IS_PIN_DIGITAL(pin)) {
          Firmata.write(PIN_MODE_SERVO);
          Firmata.write(14);
        }
        if (IS_PIN_I2C(pin)) {
          Firmata.write(PIN_MODE_I2C);
          Firmata.write(1);  // TODO: could assign a number to map to SCL or SDA
        }
#ifdef FIRMATA_SERIAL_FEATURE
        serialFeature.handleCapability(pin);
#endif
        Firmata.write(127);
      }
      Firmata.write(END_SYSEX);
      break;
    case PIN_STATE_QUERY:
      if (argc > 0) {
        byte pin = argv[0];
        Firmata.write(START_SYSEX);
        Firmata.write(PIN_STATE_RESPONSE);
        Firmata.write(pin);
        if (pin < TOTAL_PINS) {
          Firmata.write(Firmata.getPinMode(pin));
          Firmata.write((byte)Firmata.getPinState(pin) & 0x7F);
          if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F);
          if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F);
        }
        Firmata.write(END_SYSEX);
      }
      break;
    case ANALOG_MAPPING_QUERY:
      Firmata.write(START_SYSEX);
      Firmata.write(ANALOG_MAPPING_RESPONSE);
      for (byte pin = 0; pin < TOTAL_PINS; pin++) {
        Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127);
      }
      Firmata.write(END_SYSEX);
      break;

    case SERIAL_MESSAGE:
#ifdef FIRMATA_SERIAL_FEATURE
      serialFeature.handleSysex(command, argc, argv);
#endif
      break;
  }
}

/*==============================================================================
 * SETUP()
 *============================================================================*/

void systemResetCallback()
{
  isResetting = true;

  // initialize a defalt state
  // TODO: option to load config from EEPROM instead of default

#ifdef FIRMATA_SERIAL_FEATURE
  serialFeature.reset();
#endif

  for (byte i = 0; i < TOTAL_PORTS; i++) {
    reportPINs[i] = false;    // by default, reporting off
    portConfigInputs[i] = 0;  // until activated
    previousPINs[i] = 0;
  }

  for (byte i = 0; i < TOTAL_PINS; i++) {
    // pins with analog capability default to analog input
    // otherwise, pins default to digital output
    if (IS_PIN_ANALOG(i)) {
      // turns off pullup, configures everything
      setPinModeCallback(i, PIN_MODE_ANALOG);
    } else if (IS_PIN_DIGITAL(i)) {
      // sets the output to 0, configures portConfigInputs
      setPinModeCallback(i, OUTPUT);
    }
  }
  // by default, do not report any analog inputs
  analogInputsToReport = 0;

  /* send digital inputs to set the initial state on the host computer,
   * since once in the loop(), this firmware will only send on change */
  /*
  TODO: this can never execute, since no pins default to digital input
        but it will be needed when/if we support EEPROM stored config
  for (byte i=0; i < TOTAL_PORTS; i++) {
    outputPort(i, readPort(i, portConfigInputs[i]), true);
  }
  */
  isResetting = false;
}

void setup()
{
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);

  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.attach(SYSTEM_RESET, systemResetCallback);

  // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
  // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
  // Serial1.begin(57600);
  // Firmata.begin(Serial1);
  // However do not do this if you are using SERIAL_MESSAGE

  Firmata.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101
  }

  systemResetCallback();  // reset to default config
}

/*==============================================================================
 * LOOP()
 *============================================================================*/
void loop()
{
  byte pin, analogPin;

  /* DIGITALREAD - as fast as possible, check for changes and output them to the
   * FTDI buffer using Serial.print()  */
  checkDigitalInputs();

  /* STREAMREAD - processing incoming messagse as soon as possible, while still
   * checking digital inputs.  */
  while (Firmata.available())
    Firmata.processInput();

  // TODO - ensure that Stream buffer doesn't go over 60 bytes

  currentMillis = millis();
  if (currentMillis - previousMillis > samplingInterval) {
    previousMillis += samplingInterval;
    /* ANALOGREAD - do all analogReads() at the configured sampling interval */
    for (pin = 0; pin < TOTAL_PINS; pin++) {
      if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) {
        analogPin = PIN_TO_ANALOG(pin);
        if (analogInputsToReport & (1 << analogPin)) {
          Firmata.sendAnalog(analogPin, analogRead(analogPin));
        }
      }
    }
  }

#ifdef FIRMATA_SERIAL_FEATURE
  serialFeature.update();
#endif
}

Upgrading the board

Or should I just buy a newer board?

You probably don't need to because of the above. But you also have the option of upgrading it to an ATmega328P version with just the chip and burning the bootloader or having that done for you. Some hobby places will sell them burned with optiboot.


text:
UCSR0B equivalent for ESP2866
I'm trying to convert an Arduino Uno program for use with the ESP2866. I've converted most of the program successfully, but there are a few lines I can't seem to figure out. For example,
  UCSR0B = 0b10011101;
  UCSR0B = 0b10011100;

These lines result in the following error:
Compilation error: 'UCSR0B' was not declared in this scope

My understanding is that these lines modify parameters within one of the Uno's serial registers. Is it possible to do the equivalent action on the ESP? I have tried researching this but have found very little info online. I am using Arduino IDE v2.2.1. Thank you!

When porting software from one target to another, especially if it accesses hardware directly, always needs reading and understanding the documentation of both targets. Before you post a question here, you are supposed to do this homework, which you apparently did not.

UCSR0B is the UART Control and Status Register on an ATMEGA328, the processor used on many Arduino models. This is extract from the ATMEGA328 datasheet shows what the bits do:

Setting it to 0b10011101 enables RXCIE, RXEN,TXEN, UCSZ2 and TXB, and setting to the 0b10011100 sets all of the bits except TXB. Setting UCSZ2 enables 9-bit mode, and setting or clearing TXB sets or clears the ninth bit for transmitted data.
Taking a quick look at the ESP8266 UART config, the UART supports a maximum of 8 bits, so if your app definitely requires 9 bits, you won't be able to do it on an ESP8266.
typedef enum {
    UART_DATA_5_BITS = 0x0,    /*!< word length: 5bits*/
    UART_DATA_6_BITS = 0x1,    /*!< word length: 6bits*/
    UART_DATA_7_BITS = 0x2,    /*!< word length: 7bits*/
    UART_DATA_8_BITS = 0x3,    /*!< word length: 8bits*/
} uart_word_length_t;


text:
ESP32 Preferences on partition `app1`
My Arduino ESP32 project needs a lot of space for on-device string storage and the default nvs partition is not enough. I'd like to use app1 partition for preferences via pref.begin("ns1", false, "app1") but the device doesn't boot if I do that:
21:01:54.643 -> ESP-ROM:esp32s3-20210327
21:01:54.643 -> Build:Mar 27 2021
21:01:54.643 -> rst:0x3 (RTC_SW_SYS_RST),boot:0x2b (SPI_FAST_FLASH_BOOT)
21:01:54.643 -> Saved PC:0x403cdada
21:01:54.643 -> SPIWP:0xee
21:01:54.643 -> mode:DIO, clock div:1
21:01:54.643 -> load:0x3fce3808,len:0x44c
21:01:54.643 -> load:0x403c9700,len:0xbd8
21:01:54.660 -> load:0x403cc700,len:0x2a80
21:01:54.660 -> entry 0x403c98d0
21:01:54.660 -> ESP-ROM:esp32s3-20210327
... repeats

Any ideas on how to make it work?
I'd like to avoid defining a new partition since the code will be used by other people and ideally I'd avoid having them deal with another piece of complexity of redefining partitions.


text:
Arduino board with StandardFirmata doesn't respond to C# and Python client
I have a Seeeduino XIAO board with Firmata running on it. I'm currently trying to write C# client to communicate with this board.
I have tried using Iot.Device.Arduino, SolidSolis.Arduino and pyfirmata for that purpose but I'm struggling with problem - board doesn't respond to any requests sent by my apps.
However, when I use Windows Remote Arduino Experience app, board is being successfuly found and I can control pins, retrieve info etc.

I use these programs to communicate with board:

using Iot.Device.Arduino;

var arduino = new ArduinoBoard("COM3", 57600);
Console.WriteLine(arduino.FirmataVersion.Major); // This throws System.TimeoutException

import pyfirmata
port = 'COM3'
board = pyfirmata.Arduino(port)
print(board.firmata_version) # prints 'None'

StandardFirmata runs on Arduino.

This was added into Boards.h:

#elif defined(SEEED_XIAO_M0)
#define TOTAL_ANALOG_PINS 11
#define TOTAL_PINS 17 // 11 digital / analog + 1 DAC output + 2 i2c + 3 spi
#define VERSION_BLINK_PIN LED_BUILTIN
#define PIN_SERIAL1_RX 7
#define PIN_SERIAL1_TX 6
#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 10)
#define IS_PIN_ANALOG(p) ((p) >= 0 && (p) <= 10)
#define IS_PIN_PWM(p) ((p) >= 1 && (p) <= 10)
#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4
#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) // SDA = 4, SCL = 5
#define IS_PIN_SPI(p) ((p) == 4 || (p) == 10 || (p) == 9 || (p) == 8) // SS = A4
#define IS_PIN_SERIAL(p) ((p) == 6 || (p) == 7)
#define PIN_TO_DIGITAL(p) (p)
#define PIN_TO_ANALOG(p) (p)
#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p)
#define PIN_TO_SERVO(p) (p) // deprecated since v2.4

I've tried to rebuild Windows Remote Arduino Experience app with modifications - I've made it log every bytes it sends to Arduino or receives from Arduino. Then I've tried sending those bytes manually but result was still the same - board was not responding
There is a device in Device manager:

USB device with Serial port (COM3) (ID - USB\VID_2886&PID_802F&REV_0104&MI_00)

P.S. How do I know that the board is not responding and it's not the app that doesn't work? The board has RX and TX leds, RX one blinks always but TX blinks only when I use Windows Remote Arduino Experience app.
What I am doing wrong? Is there any error in setup or code I've written?

does the serial monitor in the Arduino IDE show  data from the arduino?

@jsotola Yes, when I connect the board I receive long capability message, starting with F0 6B F7

When using Iot.Device.Arduino I strongly recommend to use ConfigurableFirmata, as it is optimized for that. StandardFirmata may not support some features the library expects. Do note that the standard link speed has been changed to 115200 baud.

The problem was in serial port connection settings. When I used these i was finally able to get response from board:
var port = new SerialPort("COM3", 115600);

port.Open();

port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Encoding = Encoding.UTF8;
port.RtsEnable = true;
port.DtrEnable = true;
port.BreakState = false;