body:
I'm trying to make a hc_06 Bluetooth controller work on the attiny85-20pu.
In the end, I want to control a stepper motor through Bluetooth.
But for now to keep it simple I'm searching for a working code that can turn a simple LED on and off or something like that.

I've searched for a code like that, and I found a few, but they all don't seem to work when I try it.
I checked if the hc_06 maybe wasn't receiving any data or maybe that my wiring was wrong, but at this point I doubt it since I've tried so many different codes and re-wired it so much that I feel like at least 1 should've worked by now

For reference, here are 2 codes I've tried so far but didn't seem to work

source1: https://community.appinventor.mit.edu/t/attiny85-microcontroller-bluetooth-hc-06-arduino-ide/20252/2

source2: https://community.appinventor.mit.edu/t/attiny85-microcontroller-bluetooth-hc-06-arduino-ide/20252/2

```c++
#include <SoftwareSerial.h> //Software Serial Port
#define TxD 0 //pin 5 de l'ATtiny à relier au pin RXD du module bluetooth (pin5)
#define RxD 1 //pin 6 de l'ATtiny à relier au pin TXD du module bluetooth (pin4)

SoftwareSerial blueToothSerial(RxD,TxD);
int relais = 4; // pin 3 de l'ATtiny qui commande le relais

void setup()
{
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  blueToothSerial.begin(9600);
  //delay(2000); // délai nécessaire
  blueToothSerial.print("Bluetooth connecté !\n");
  delay(4000); //Vérifie que tous les relais sont bien inactifs après un reset
  pinMode(relais, OUTPUT);
  digitalWrite(relais, LOW); // ouvre le relais
}

void loop()
{
  char recvChar;
  while (1) {
    //vérifie s'il y a des données envoyées à partir du module bluetooth
    if (blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      if (recvChar == '1')
        digitalWrite(relais, HIGH);
      else
        digitalWrite(relais, LOW);
    }
  }
}
```

Or this one

```c++
// Tiny85 y Bluetooth HC-06
// Juan A. Villalpando
// kio4.com

#include <SoftSerial.h>
#include <TinyPinChange.h>
#define LED4 4

SoftSerial Bluetooth(2, 3);
char caracter;

void setup()
{
  Bluetooth.begin(9600);
  pinMode(LED4, OUTPUT);
}

void loop()
{
  while (Bluetooth.available() > 0) {
    caracter = Bluetooth.read();
    if (caracter == '1') {
      digitalWrite(LED4, HIGH);
      Bluetooth.println('E');
    }
    if (caracter == '0') {
      digitalWrite(LED4, LOW);
      Bluetooth.println('A');
    }
  }
}
```

**UPDATE**

With this code it works but only if I disconnect TX from the HC_06 to RX to the attiny85. If I do that the LED will turn on after a few seconds
and if I then send a 0 it works fine.
hopefully this helps?

```c++ #include <SoftwareSerial.h>  //Software Serial Port
#define RxD 1
#define TxD 0

#define DEBUG_ENABLED  1

SoftwareSerial blueToothSerial(RxD,TxD);

int led = 4 ;

void setup()
{
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  setupBlueToothConnection();

  pinMode(led,OUTPUT);

}

void loop()
{
  char recvChar;
  while(1){
    //check if there's any data sent from the remote bluetooth shield
    if(blueToothSerial.available()){
      recvChar = blueToothSerial.read();

        if(recvChar==0)
          digitalWrite(4,HIGH);

        else
          digitalWrite(4,LOW);
    }
  }
}

void setupBlueToothConnection()
{
  blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400
  blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
  blueToothSerial.print("\r\n+STNA=MAVA_bluetoothcr\r\n"); //set the bluetooth name as "HC-05"
  blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
  blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here

  delay(2000); // This delay is required.
  //blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
  blueToothSerial.print("bluetooth connected!\n");

  delay(2000); // This delay is required.
  blueToothSerial.flush();
}```

title: Bluetooth (HC_06) on the Attiny85

Answers: 0


body:
I tried to sketch code to make an encoder to generate a number by each step and show it on OLED display. The OLED will connect with I2C, working on in Arduino Nano Every ATmega4809.

I separately made them for both encoder and OLED, they all work in separate code, encoder to generate Number and OLED display the text on screen.

But after combining them together, it seems to work only the OLED display. The encoder is not responding at all. The encoder will work again when I disable `OLED.display()` in loop section.

Anyone Please help me to them work together?

This is my sketch

```c++
//Display
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

// กำหนดขาต่อ I2C กับจอ OLED
#define OLED_RESET     -1
Adafruit_SSD1306 OLED(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

//Encoder
#define R_START 0x0
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
#define DIR_NONE 0x0
#define DIR_CW 0x10
#define DIR_CCW 0x20

const byte pin1 = 10;  // DT
const byte pin2 = 11;  // CLK
int state = R_START;
int counter = 0;
int counter_ini = 0;
int potstep = 0;

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 0x30;
}

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);

  //Display
  if (!OLED.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("SSD1306 allocation failed");
  } else {
    Serial.println("ArdinoAll OLED Start Work !!!");
  }
OLED.clearDisplay();
OLED.setTextSize(2);
OLED.setTextColor(WHITE);
OLED.setCursor(5, 10);
OLED.println("   TEST   ");
OLED.println();
  OLED.display();
  delay(5000);
}

void loop(){

  unsigned char result = process();
  if(result == DIR_CW){
    counter++;
    //Serial.println(counter);
  }
  else if(result == DIR_CCW){
    counter--;
    //Serial.println(counter);
  }
  if(counter > counter_ini){
    potstep++;
    Serial.println(potstep);
    counter_ini=counter;
  }
  else if(counter < counter_ini){
    potstep--;
    Serial.println(potstep);
    counter_ini=counter;
  }
  if(potstep > 255){
    potstep = 255;
    //Serial.println(potstep);

  }
  else if(potstep < 0){
    potstep = 0;
    //Serial.println(potstep);
  }
//Display
    OLED.clearDisplay();
    OLED.drawRect(3,3,125,47,WHITE);
    OLED.setTextSize(4);
    OLED.setTextColor(WHITE, BLACK);
    OLED.setCursor(27,12);
    OLED.println(potstep);

    OLED.display();
}
```

title: Make encoder work together with OLED display in Arduino Nano Every

Answers: 0


body:
Ignore direction of the motors(for now).

This is my connection diagram. Any and all improvements to this are welcome.

Bottom left motor seems to run at 210-224 rpm
Bottom right motor runs at 160-180 rpm
Top right motor runs at 210-224 rpm
Top left motor runs at 160-180 rpm
[![enter image description here][1]][1]

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

Code for running the below setup:
```

// Motor A connections

int enA = 7;

int in1 = 4;

int in2 = 5;

// Motor B connections

int enB = 6;

int in3 = 3;

int in4 = 2;

//Motor c

int enC = 9;

int in5 = 12;

int in6 = 13;

// Motor d connections

int enD = 8;

int in7 = 10;

int in8 = 11;

void setup() {

// Set all the motor control pins to outputs
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(enC, OUTPUT);
pinMode(enD, OUTPUT);
pinMode(in5, OUTPUT);
pinMode(in6, OUTPUT);
pinMode(in7, OUTPUT);
pinMode(in8, OUTPUT);

  // Turn off motors - Initial state
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
digitalWrite(in5, LOW);
digitalWrite(in6, LOW);
digitalWrite(in7, LOW);
digitalWrite(in8, LOW);
}

void loop() {
  moveForward();
  delay(3000);
  motorOff();
  delay(1000);
}

void moveForward(){

  analogWrite(enA, 200);
  analogWrite(enB, 200);
  analogWrite(enC, 200);
  analogWrite(enD, 200);

  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  digitalWrite(in5, HIGH);
  digitalWrite(in6, LOW);
  digitalWrite(in7, HIGH);
  digitalWrite(in8, LOW);
}

void motorOff(){
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  digitalWrite(in5, LOW);
  digitalWrite(in6, LOW);
  digitalWrite(in7, LOW);
  digitalWrite(in8, LOW);
}
```
Any change to the code is also welcome.

title: I would like to know why my four gear motors are rotating at different speeds when connected to 2 L293D motor drivers, controlled by the arduino

Answers: 1

body:
Pins 7 and 8 aren't PWM pins on the UNO.  So when you call analogWrite on them with a value greater than 127 it defaults to digitalWrite and just writes those pins HIGH.  Pins 6 and 9 are PWM pins, so they are responding as expected to the analogWrite.  Since they are outputting PWM and the signal to the other motors is constantly high, they run slower.

You should change your wiring so that all of the enable pins are connected to PWM capable pins.  On the Arduino UNO those are pins 3, 5, 6, 9, 10, and 11.


body:
I'm attempting to print several rows of text, at certain Y-values, on an [SSD1306 128x64 LCD display][1].

I'm using the [`ssd1306` library by Alexey Dynda][2]. I initially wanted to use the more common LCD libraries out there, such as the [Adafruit SSD1306 LCD library][3], however it unfortunately does not appear I can set custom I2C pins for most such libraries out there, which is required as I'm using a custom board with an ESP32-WROOM-DA chip. The `ssd1306` by Dynda appears to be able to do so.

I have the following example code, which prints 6 lines of text:

```c++
#include "ssd1306.h"
#include "nano_gfx.h"

const int PIN_I2C_SCL = 16;
const int PIN_I2C_SDA = 13;

void LCDTextDraw(int x, int y, const char* text)
{
  EFontStyle fontStyle;

  ssd1306_printFixed(x, y, text, fontStyle);
}

void LCDRectDraw(int x, int y, int w, int h)
{
  ssd1306_fillRect(x, y, x + w, y + h);
}

void LCDScreenClear(bool fill)
{
  ssd1306_clearScreen();

  if (fill)
    LCDRectDraw(0, 0, 128, 64);
}

void LCDInit()
{
  ssd1306_setFixedFont(ssd1306xled_font6x8);
  ssd1306_128x64_i2c_initEx(PIN_I2C_SCL, PIN_I2C_SDA, 0);
}

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

  pinMode(PIN_I2C_SCL, OUTPUT);
  pinMode(PIN_I2C_SDA, OUTPUT);

  LCDInit();
  LCDScreenClear(true);

  LCDTextDraw(30, 0, "TEST 1");
  LCDTextDraw(30, 10, "TEST 2");
  LCDTextDraw(30, 20, "TEST 3");
  LCDTextDraw(30, 30, "TEST 4");
  LCDTextDraw(30, 40, "TEST 5");
  LCDTextDraw(30, 50, "TEST 6");
}

void loop()
{}
```

With which I wish to print out 6 lines of text, each line evenly vertically spaced out by 10 pixels.

Which produces the following output on my LCD:

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

As you can see, the text rows are not evenly vertically spaced out as I wish them to be, with a large space between the `TEST 4` and `TEST 5` strings.

After looking at the definition of the `ssd1306_printFixed` function I'm using to print out my text in the example above, it turns out that it can only print rows of text at certain fixed Y-positions:

>@warning ssd1306_printFixed() can output chars at fixed y positions: 0, 8, 16, 24, 32, etc.\
         If you specify [10,18], ssd1306_printFixed() will output text starting at [10,16] position.

Hence, I also tried using the `ssd1306_print` function (which uses a cursor to delineate its printing location on the screen), which doesn't have that warning in its header declaration. I replaced my `LCDTextDraw` function with:

```c++
void LCDTextDraw(int x, int y, const char* text)
{
  ssd1306_setCursor8(x, y);
  ssd1306_print(text);
}
```

However, that still produced the exact same output on my LCD, with the same spacing issues.

What is the proper way to print text rows at any Y-value on an LCD?

Thanks for reading my post, any guidance is appreciated.

  [1]: https://www.amazon.com/AZDelivery-Display-kompatibel-Raspberry-inklusive/dp/B074N9VLZX/ref=asc_df_B074N9VLZX/?tag=hyprod-20&linkCode=df0&hvadid=652510459651&hvpos=&hvnetw=g&hvrand=5571274269721607156&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9031168&hvtargid=pla-435201366413&psc=1
  [2]: https://github.com/lexus2k/ssd1306
  [3]: https://github.com/adafruit/Adafruit_SSD1306
  [4]: https://i.stack.imgur.com/yI4gvm.jpg

title: Print text at any Y-value on SSD1306?

Answers: 1

body:
Turns out using the [Adafruit SSD1306 library][1] is much easier than I first thought. One just must specify the I2C pins used with `Wire`, and pass it as reference to the `Adafruit_SSD1306` constructor. Additionally, the Adafruit library doesn't appear to have the uneven vertical spacing issue.

The equivalent code below using the Adafruit library:
```
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const int PIN_I2C_SCL = 16;
const int PIN_I2C_SDA = 13;

Adafruit_SSD1306 LCD(128, 64, &Wire);

void LCDTextDraw(int x, int y, const char* text, byte size)
{
  LCD.setCursor(x, y);
  LCD.setTextSize(size);
  LCD.print(text);
  LCD.display();
}

void LCDRectFill(int x, int y, int w, int h, int color)
{
  LCD.fillRect(x, y, w, h, color);
}

void LCDScreenClear(bool fill)
{
  LCD.clearDisplay();
  LCD.display();
  LCD.setTextColor(WHITE, BLACK);

  if (fill)
    LCDRectFill(0, 0, 128, 64, 1);
}

void LCDInit()
{
  LCD.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}

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

  pinMode(PIN_I2C_SCL, OUTPUT);
  pinMode(PIN_I2C_SDA, OUTPUT);

  Wire.setPins(PIN_I2C_SDA, PIN_I2C_SCL);
  Wire.begin();

  LCDInit();
  LCDScreenClear(true);

  LCDTextDraw(30, 0, "TEST 1", 1);
  LCDTextDraw(30, 10, "TEST 2", 1);
  LCDTextDraw(30, 20, "TEST 3", 1);
  LCDTextDraw(30, 30, "TEST 4", 1);
  LCDTextDraw(30, 40, "TEST 5", 1);
  LCDTextDraw(30, 50, "TEST 6", 1);
}

void loop()
{}
```

Now produces the desired result:

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

  [1]: https://github.com/adafruit/Adafruit_SSD1306
  [2]: https://i.stack.imgur.com/V76dEm.jpg


body:
I have an application polling 4 ADCs by I2C. The application shall also write on some ADC registers. In order to test it, I'd like to use a single Arduino UNO, enabling it for receiving I2C messages over 4 different addresses by masking the TWAMR register. In this way I can have 4 ADCs "emulated" on a single Arduino.

When the application asks for a read to Arduino at some address, I'm able to get the value of the required address by reading the TWDR register:
```cpp
void requestEvent(){
  byte addr = TWDR >> 1;
  if (0x4A == addr){ // do something }
  else if (0x4B == addr){ // do something }
  // ...
}

void setup(){
  // ...
  Wire.onRequest(requesEvent);
}
```

However, when the application requests to write something to a certain ADC (with its own address), I'm not able to get the address value in the `onReceive(int)` callback:
```cpp
void receiveEvent(int howMany){
  byte addr = TWDR >> 1; // returns the first byte AFTER the address in the I2C message
}
```

Am I doing something wrong? Is there a way to reach my goal?

Thanks.

Luca

**Edit:**

Reading the ATmega datasheet (sec. 22.9.4, p. 241), the problem with reading the TWDR register is that it contains the last byte received, that in slave receiver mode is not the address but the last data sent by the master.

Anyway, is there any workaround for this problem?

title: Get address of a I2C transaction when multiple addresses are registered

Answers: 1

body:
Reading the TWDR register in the `onReceive()` callback doesn't give you the address because of the time, that it is called at. The `onReceive()` callback is called when all bytes have already been received and put in the `Wire` libraries internal buffer. Thus in that callback TWDR will still hold the last received data byte.

The `onRequest()` callback on the other hand is called right after the address was received. Thus TWDR still holds the received address.

You will need to modify the Wire library to achieve your goal. Similar to the `onRequest()` callback you can introduce a third kind of callback function, which will be executed after receiving the slave address to save the received address for later use (the address matching is still done via hardware, so you still need to mask the address via TWAMR).

You can find the files for the Wire library inside your used core (for me the Uno uses the path ~/.arduino15/packages/arduino/hardware/avr/1.8.5/libraries/Wire). Look at line 581 of src/utility/twi.c. This is inside the TWI ISR, the `case` clause `TW_SR_SLA_ACK`, which will be executed on address receive/match. Here you can insert your callback function.

If you want to do this in a similar handy way, that the `Wire` library does with the other callbacks, then you need to change a few other things:

1. Insert a function pointer for this at the start of the twi.c file, right besides the other function pointers:

        static void (*twi_onSlaveAddressMatch)(uint8_t);

2. Add the execution of that function to the case in the ISR described above and provide the content of TWDR (shifted to eliminate the direction bit) as a parameter:

        twi_onSlaveAddressMatch(TWDR >> 1);

3. Add a function to set the callback function pointer in twi.c:

        void twi_attachSlaveAddressMatchEvent( void (*function)(uint8_t) ){
            twi_onSlaveAddressMatch = function;
        }

4. Add the callback set function as a function prototype to twi.h:

        void twi_attachSlaveAddressMatchEvent( void (*function)(uint8_t) );

5. In Wire.h  add a function pointer for the new callback and the corresponding service function inside the `private:` section:

        static void (*user_onSlaveAddressMatch)(uint8_t);
        static void onSlaveAddressMatchService(uint8_t);

6. In Wire.h add a function to set the user callback function to the `public:` section:

        void onSlaveAddressMatch( void (*)(uint8_t) );

7. In Wire.cpp add the implementation of the service function:

        void TwoWire::onSlaveAddressMatchService(uint8_t address){
            if(!user_onSlaveAddressMatch){
                return;
            }
            user_onSlaveAddressMatch(address);
        }

8. In Wire.cpp add the implementation of the callback setter function:

        void TwoWire::onSlaveAddressMatch( void (*function)(uint8_t) ) {
            user_onSlaveAddressMatch = function;
        }

Now you should be able to set a callback for the address receive in your main code and save the address for later use:

    uint8_t received_address = 0;

    void getAddress(uint8_t address){
        received_address = address;
    }

    void setup(){
        ...
        Wire.onSlaveAddressMatch(getAddress);
    }

In the `onReceive()` callback you can then check for that global variable.

Note: I have not tested or compiled this. I just looked at the logic of the Wire library and copied the way it already defines its existing callback functions.


body:
I'm working on a project to implement an attitude controller for a quadcopter. Loop times are extremely important as you can imagine.

I already have tested code for a cascading controller (inner loop does angular rate, outer does attitude) for a single-axis on a see-saw-like physical setup.

My worry was that implementing for 3-axis would slow loop times to lead to system instability. Thus, I purchased a Giga R1 which features two cores to share the load.

One way I could implement the code is to collect all sensor/RC signals on the co-processor, while the main processor does all the PID computation and generates PWM signals for the motors.

This obviously means sharing data between the two cores. I tried using the RPC method the Arduino guide suggests to share data. However, I timed how long a remote call to return an integer takes and I'm getting around 20 milliseconds. This is far too slow.

Is there a faster way to share data between the cores? I'm open to changing how the system is configured (i.e. which core does what) if that helps.

title: Sharing data between M4 and M7 on a Giga R1 at high speeds

Answers: 0


body:
I use esp32 devkit v1 .
I code follwing this picture.
[![enter image description here][1]][1]

```c++
const int vavle = 1;
int d = 1;

void setup()
{
  Serial.begin(115200);
  delay(2000);
  while (!Serial);
  Serial.println();
  pinMode(vavle,OUTPUT);
  Serial.println(d);
}

void loop()
{
  Serial.print("Open Vavle");
  digitalWrite(vavle,HIGH);
  delay(3000);
  digitalWrite(vavle,LOW);
  delay(1000);
  Serial.print("Close Vavle");
}
```

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

but serial monitor has error when use serial monitor it show me square .
I confirm select true board rate.
you can solve this problem .

title: ESP32 cannot serial monitor

Answers: 1

body:
The GPIO1 pin you are trying to use with  `const int vavle = 1;` ... `pinMode(vavle, OUTPUT);` *is* the same pin that carries serial data to the PC.

From [the pinout](https://github.com/playelek/pinout-doit-32devkitv1/commit/afa2c642a8e63d73bce5ae93a75672a7755fe363):

[![DOIT ESP32 DEVKIT V1 PINOUT with TX0/GPIO1/U0TXD pin highlighted.][1]][1]

Their schematic link is broken, but if you find schematic for pretty much any similar board using this module you'll see GPIO1/U0TXD connected to a serial transceiver chip which is then connected to the USB port.

You need choose some other pin. There are [pin guides](https://randomnerdtutorials.com/esp32-pinout-reference-gpios/) and [official documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html) containing the same details that you can use to figure out which GPIO to use.
GPIO numbers 16 through 33 inclusive are all output-capable and seem to have no special requirements, so they make sense to choose from.

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


body:
I have designed a device based on classical common ESP32 boards (without micro SD slot).

I'd like (non tech-savvy) end-users to be able to modify some settings of the device, such as their home router WiFi SSID, some other constants, etc.

Obviously I can't ask them to: open the Arduino IDE, modify some consants in the code, re-compile, re-upload, this is not possible for the target audience.

TL;DR: **How to offer end-users the possibility of modifying some parameters (e.g. Wifi SSID), without asking them to compile/upload with the IDE?**

Example of what could be possible:

* ask them to plug the ESP32 with USB to a PC
* see a new storage device appear in the Explorer
* browse in F:\ (for example), and modify a file named `settings.txt`

Is there a way to enable this "simple configuration" on a ESP32?

title: How to offer end-users the possibility of modifying ESP32 settings (e.g. Wifi SSID), without asking them to compile/upload with the Arduino IDE?

Answers: 0


body:
I am trying to replace a no longer manufactured volts-to-frequency converter that is part of a simulator we use for training.

I understand reading the Analog pin and converting it to VDC, then I have the map() function to convert to the frequency.

How do I get one of the PWM pins to output this frequency? I've been reading about the timers and divisors and am getting myself confused.

VDC In 0.770 - 5.000
Hz Out 407 - 2643

here is my code so far;

        /*

    */
    int sensorValue;
    float voltageIn;
    long freq;

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

    }

    void loop() {
        // read the input on analog pin 0:
      sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      voltageIn = sensorValue * (5.0 / 1023.0);
      // print out the value you read:
      Serial.println(voltageIn);

      //map voltage to frequencyConversion
      freq = map(voltageIn,0.770,5.000,76.781,11.824);

    }

title: Tunable 0-5VDC input to Frequency (407-2643 Hz)

Answers: 0


body:
Good day. I would like to ask for help regarding the code for my project. I am using an I2S MEMS microphone breakout (SPH0645) to my Arduino Nano 33 IoT. Here are my pin configurations LRCL to A2 of the Arduino Nano 33 IoT, DOUT to D4, BCLK to A3. The code that I am using is:

```c
#include <I2S.h>
void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ;
  }
  if (!I2S.begin(I2S_PHILIPS_MODE, 8000, 32)) {
    Serial.println("Failed to initialize I2S!");
    while (1); // do nothing
  }
}
void loop() {
  int sample = I2S.read();
  if (sample) {
    Serial.println(sample);
  }
}
```
However, I still cannot see in the serial monitor if the microphone can detect sound. Also, every time I upload this to my Arduino, I encounter this problem:

>appdata/local/arduino15/packages/arduino/tools/arm-none-eabi-gcc/7-2017q4/bin/../lib/gcc/arm-none-eabi/7.2.1/../../../../arm-none-eabi/bin/ld.exe: warning: changing start of section .bss by 8 bytes

I followed the steps [here][1]. Thank you for your help.

  [1]: https://learn.adafruit.com/adafruit-i2s-mems-microphone-breakout/arduino-wiring-and-test

title: Using I2S MEMS microphone breakout (SPH0645) as frequency detector

Answers: 0


body:
I'm trying to write a small python program to communicate with my Arduino board but, somehow, I'm having a little trouble.
My goal is to switch on and off a LED by interacting with the desktop program in python.

In python, I've created a small class to handle my requests:
```
class ArduinoSerialLine:
    __serial  = None

    def init(self):
        self.__serial = arv.Serial(port='COM5', baudrate=9600)
        time.sleep(1)

    def read(self):
        if self.__serial.in_waiting > 0:
            data = self.__serial.readline().decode('utf-8')[:-2]
            print('READ_DATA::' + data)

    def write(self, msg: str):
        print("Writing on serial: " + msg)
        msg += "\n"
        self.__serial.write(msg.encode())
        self.__serial.flush()
        time.sleep(0.5)
```

At first, it didn't invoke `time.sleep()` but, I've added it after reading [this post](https://arduino.stackexchange.com/questions/16220/pyserial-serial-write-doesnt-work), hoping that it'd help me solve my problem. Nothing changed.
I'm sure the serial monitor is connected, since the `read()` function seems to work correctly.

As for the Arduino counterpart, I've tried to handle the commands as follows:
```
void loop()
{
  if (Serial.available())
  {
    led.switchOn();
    delay(100);
    led.switchOff();
    delay(100);

    String msg = "";
    char c;
    do {
      c = Serial.read();
      msg += c;
    } while(c != "\n");

    // if (msg == "on")
    //   led.switchOn();
    // else if (msg == "off")
    //   led.switchOff();
  }
  delay(100);
}
```

I've commented the portion of code in which it actually switches the LED because I wanted to actually check if there was anything to read at all. Turns out, it never even enters the if block.

Note that in `switchOn()` and `switchOff()` I just use the `digitalWrite` function, nothing special.

Does anyone have an idea on how I could solve this problem?

----------

Edit to answer the comments:

This is my `setup()` in the `.ino` file:
```
Led led();

void setup()
{
  Serial.begin(9600);
  led.pin = 7;
  pinMode(led.pin, OUTPUT);
  Serial.println("System ready");
}
```
Where the LED class is as follows:
```
class Led
{
  int pin;
  void switchOn()
  {
    digitalWrite(pin, HIGH);
  }
  void switchOff()
  {
    digitalWrite(pin, LOW);
  }
}
```

As for the PyScript, it might be a bit more complicated but, I'll try my best to give you more details!

I was planning on expanding the system in the future, so I've created a few classes. `ArduinoSerialLine` for now is only used in the class `LightService`.
```
class LightService:
    __serial: ArduinoSerialLine
    __isLightOn = False

    def LightService(self):
        None

    def init(self):
        self.__serial = ArduinoSerialLine()
        self.__serial.init()

    def checkStatus(self):
        self.__serial.read()

    def switchOnLight(self):
        self.__isLightOn = True
        self.__serial.write("on")

    def switchOffLight(self):
        def switchOnLight(self):
        self.__isLightOn = False
        self.__serial.write("off")
```

The `checkStatus()` function is called about every two seconds in a separate thread. I was planning to use it just for monitoring what happens on the serial even though, I'm not sure whether it should be able to read the lines written from python. It reads correctly the "System ready" printed in the Arduino setup. After that, it just skips the if block inside `read()`.

`switchOnLights()` and `switchOffLights()` are called upon the interaction with a button in the GUI. I'm not going to paste the entire code, but I can assure you that in debug it enters the functions correctly and the state of the class is the same as in the other thread. It doesn't skip instructions in debug nor give runtime errors.

title: Python program can read but not write on serial monitor

Answers: 0


body:
I am trying to use an esp32 [(NodeMCU-32s)](https://docs.ai-thinker.com/en/esp32/boards/nodemcu_32s) as a ringlight controller for my camera. All it should do is sense when an input pin goes low (the camera's output connects to ground when the shutter goes off) which is easy to detect with a simple digitalRead(). If low, then it raises 6 pins with digitalWrite() which are connected to transistors which let current flow from a 24v power supply and light up 6 banks of white LEDs. This entire setup was working great on an esp32wroom I bought from our school's shop - like I said it is very simple - but after ordering more esp32's online, I was greeted with slightly different looking ones that don't behave the same even when running the exact same code. Yes, I have verified that the pinout is the same on these two boards, although the footprint of the online boards (best datasheet I could find linked above) is one breadboard slot thinner.

#### Expected behavior:
I power it on, and nothing should happen until I connect pin 14 to ground, then the lights should turn on for a tenth of a second, then back off.

#### Actual Behavior:
I power it on, 3 banks of lights turn on rather dimmly. The other three stay off. When I connect pin 14 to ground, the three that were off turn on for a tenth of a second, then back off. While they are on, a blue light on the nodemcu-32s dev board turns on as well...

I did some digging:

On this [random nerd tutorials](https://randomnerdtutorials.com/esp32-spi-communication-arduino/) website I found code that identifies which pins are your board's default SPI pins and when I ran it, I found that 3 of the 6 pins I was currently using (pins 23, 19, and 5) are SPI-related ones. These were in fact the pins that behaved correctly (they were off until 14 was pulled low.)

I am not sure if this is related to the root cause of my issue or not, but it seems suspicious. Any tips from you wise arduino wizards would be appreciated - this was supposed to be simple!

#### Code:

Below is the code I am using. You can ignore the rgb LED stuff (LED_PIN, NUM_LEDS, BRIGHTNESS, etc.) All that matters for what I am trying to get working here are the led banks connected to pins 23, 21, 19, 5, 16, and 2. I intentionally avoided pins 6-11 because many sites were saying to avoid them.

```c
#include <Adafruit_NeoPixel.h>

#define LED_PIN 15      // Pin connected to the Data Input of WS2812B
#define NUM_LEDS 24     // Number of WS2812B LEDs in the strip
#define BRIGHTNESS 200  // Set the brightness (0-255)

#define SHUTTER_PIN 14  //Pin connected to the shutter signal of the cameras via 3.5mm jack
Adafruit_NeoPixel strip;

void setup() {
  // setup code here, to run once:
  pinMode(23, OUTPUT); // set each bank of 6 White Leds as outputs
  pinMode(21, OUTPUT);
  pinMode(19, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(2, OUTPUT);

  // set the shutterPin as a normally-high input
  pinMode(SHUTTER_PIN, INPUT_PULLUP);

  // To control rgb leds
  strip = Adafruit_NeoPixel(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
  strip.begin();
  strip.setBrightness(BRIGHTNESS);
  strip.show();

 // Initialize all pixels to off
  digitalWrite(23, LOW);
  digitalWrite(21, LOW);
  digitalWrite(19, LOW);
  digitalWrite(5, LOW);
  digitalWrite(16, LOW);
  digitalWrite(2, LOW);
}

void loop() {
  //main code here, to run repeatedly:
  // if the shutter signal drops, flash on and off
  if (digitalRead(SHUTTER_PIN) == 0) {
    digitalWrite(23, HIGH);
    digitalWrite(21, HIGH);
    digitalWrite(19, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(16, HIGH);
    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(23, LOW);
    digitalWrite(21, LOW);
    digitalWrite(19, LOW);
    digitalWrite(5, LOW);
    digitalWrite(16, LOW);
    digitalWrite(2, LOW);
    delay(500);
  }
}
```

title: Can I use SPI-related pins as a Digital Output?

Answers: 2

body:
I'm still not quite sure what's going on, but to troubleshoot this I would do the following:

- First of all, verify it's not a faulty board and try it with another one of the new ones that you've got. If that doesn't help, then do the following:
    - Move the digitalWrite-s up, above the NeoPixel initialization code. See if that helps with the start-up.
    - If that doesn't help, add pull-down resistors to the LED outputs (try 10kOhm).
    - The blue LED lights up because GPIO 2's output is connected to it, looking at the schematic on the website you've linked. You might want to switch this one to a different GPIO on the board you're using.
    - Check the transistor circuits for the LEDs that are not functioning correctly. You've not posted anything related to it, so I can't help you much there, but if you do link it we might be able to use that info.

body:
From [the schematics][1], I can see that IO2 is for the board's blue LED. So that's probably your first problem... From [this PDF][2], I see that IO21 is VSPIHD, Hold for Flash chips. No good. IO16 is HS1_DATA4, also used for the Flash chip. Also no good. You'll have to pick other pins.

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

The other issue is SIX pins supposed to deliver 3.3 volts at the same time. On a small ESP board. Not sure that's gonna happen...

  [1]: https://docs.ai-thinker.com/_media/esp32/boards/nodemcu/nodemcu_32s_sch.png
  [2]: https://docs.ai-thinker.com/_media/esp32/docs/nodemcu-32s_product_specification.pdf
  [3]: https://i.stack.imgur.com/i0mhn.jpg
  [4]: https://i.stack.imgur.com/iNxjo.jpg


body:
I am new to coding with arduino boards. I am facing a severe issue while uploading any program to ATMega128. The programs compile without any errors. But the program does not get uploaded to Board. The TX led remains ON and sketch remains to 'uploading' mode.

Note that, I have uploaded the same programs to the board previously without any issue. May be in recent times, something have changed which might be causing this behavior.

Also, It works fine with few other laptops I tried with same sketch and same hardware configuration.

Here is the error log:

```
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
```

Here is the detail compilation message log:

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware
C:\Program Files (x86)\Arduino\hardware -hardware
C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages -tools
C:\Program Files (x86)\Arduino\tools-builder -tools
C:\Program Files (x86)\Arduino\hardware\tools\avr -tools
C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages -built-in-libraries
C:\Program Files (x86)\Arduino\libraries -libraries
C:\Users\Iqbal Hossain\Documents\Arduino\libraries -fqbn=MegaCore:avr:128:BOD=2v7,LTO=Os,clock=16MHz_external -ide-version=10805 -build-path C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212 -warnings=none -build-cache
C:\Users\IQBALH~1\AppData\Local\Temp\arduino_cache_248895 -prefs=build.warn_data_percentage=75 -verbose
C:\Program Files (x86)\Arduino\examples\01.Basics\AnalogReadSerial\AnalogReadSerial.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware
C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages -tools
C:\Program Files (x86)\Arduino\tools-builder -tools
C:\Program Files (x86)\Arduino\hardware\tools\avr -tools
C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages -built-in-libraries
C:\Program Files (x86)\Arduino\libraries -libraries
C:\Users\Iqbal Hossain\Documents\Arduino\libraries -fqbn=MegaCore:avr:128:BOD=2v7,LTO=Os,clock=16MHz_external -ide-version=10805 -build-path C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212 -warnings=none -build-cache
C:\Users\IQBALH~1\AppData\Local\Temp\arduino_cache_248895 -prefs=build.warn_data_percentage=75 -verbose
C:\Program Files (x86)\Arduino\examples\01.Basics\AnalogReadSerial\AnalogReadSerial.ino
Using board '128' from platform in folder:
C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1
Using core 'MCUdude_corefiles' from platform in folder:
C:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1

Detecting libraries used...

"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega128 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_ATmega128 -DARDUINO_ARCH_AVR   "-IC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1\cores\MCUdude_corefiles" "-IC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1\variants\64-pin-avr"
"C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\sketch\AnalogReadSerial.ino.cpp" -o "nul"

Generating function prototypes...

"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega128 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_ATmega128 -DARDUINO_ARCH_AVR   "-IC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1\cores\MCUdude_corefiles" "-IC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1\variants\64-pin-avr"
"C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\sketch\AnalogReadSerial.ino.cpp" -o "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\preproc\ctags_target_for_gcc_minus_e.cpp"

Compiling sketch...

"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega128 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_ATmega128 -DARDUINO_ARCH_AVR   "-IC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1\cores\MCUdude_corefiles" "-IC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1\variants\64-pin-avr" "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\sketch\AnalogReadSerial.ino.cpp" -o "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\sketch\AnalogReadSerial.ino.cpp.o"

Compiling libraries...

Compiling core...

Using precompiled core

Linking everything together...

"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-gcc" -w -Os -Wl,--gc-sections -mmcu=atmega128  -o "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/AnalogReadSerial.ino.elf" "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212\sketch\AnalogReadSerial.ino.cpp.o" "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/..\arduino_cache_248895\core\core_MegaCore_avr_128_BOD_2v7,LTO_Os,clock_16MHz_external_e84916ce955a11deeb2803039f1fccdf.a" "-LC:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212" -lm
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/AnalogReadSerial.ino.elf" "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/AnalogReadSerial.ino.eep"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/AnalogReadSerial.ino.elf" "C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/AnalogReadSerial.ino.hex"

Sketch uses 2348 bytes (1%) of program storage space. Maximum is 130048 bytes.
Global variables use 198 bytes (4%) of dynamic memory, leaving 3898 bytes for local variables. Maximum is 4096 bytes.

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Iqbal Hossain\AppData\Local\Arduino15\packages\MegaCore\hardware\avr\2.0.1/avrdude.conf -v -patmega128 -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\IQBALH~1\AppData\Local\Temp\arduino_build_95212/AnalogReadSerial.ino.hex:i
```

title: "Overriding Baud Rate : 115200" Error while uploading program to ATMega128

Answers: 0


body:
Is there a ATmega328 drop-in replacement with more flash memory?

Needs to be 28 pin DIL to fit the socket.

Alternatively, is there a board that has the exact dimensions and pins as an Arduino UNO, but with more flash memory?

Everything in my project works fine, but I need more program memory. Can unfortunately not use a different board layout or size.

Answers: 1

body:
> Is there a ATmega328 drop-in replacement with more flash memory?

No

> Alternatively, is there a board that has the exact dimensions and pins as an Arduino UNO, but with more flash memory?

Yes, but it'll be probably something with ARM (UNO R4 minima has even 5V ARM), However libraries might be an issue

As for AVRs, there are for example AVR128DA28 but as far as I know, it's definitely not pin compatible.

However you could use some proto board for UNO and wire it up somehow on it.  (128kB, 28pin).

Also Atmega644/1284 (in pdip 40) could be used on proto board and it's much more compatible


body:
I'm using Ethernet module ENC28J60 with ESP32 on Arduino IDE.

I could establish a secure connection using `WifiClientSecure.h`
here code

    #include <Arduino.h>
    #include <WiFi.h>
    #include <WiFiClientSecure.h>
    #include <HTTPClient.h>

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

    const char* serverName = "https://myserver.com/v1";

    const char* userName = "admin";
    const char* pass = "pass";

    unsigned long previous;

    const char* rootCACertificate =
      "-----BEGIN CERTIFICATE-----\n"
      ...
      "-----END CERTIFICATE-----\n";

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

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      Serial.print("Connecting to WiFi ..");
      while (WiFi.status() != WL_CONNECTED)
      {
        Serial.print('.');
        delay(1000);
      }

      Serial.println(WiFi.localIP());

    }

    void loop() {
      if ((WiFi.status() == WL_CONNECTED))
      {
        WiFiClientSecure client;

        client.setCACert(rootCACertificate);
        HTTPClient https;

        Serial.print("[HTTPS] begin...\n");
        if (https.begin(client, serverName))
        {
          https.setAuthorization(userName, pass);
          https.addHeader("Content-Type", "application/json");
          ...
          https.end();

        }
      }
      else
      {
        Serial.printf("Unable to connect to wifi\n");
      }
      Serial.println();
      Serial.println("Waiting 60sec before the next round...");
      delay(60000);
    }

But there is no support for Ethernet.
Could anyone suggest a way to connect to server with EthernetENC or any other Library?

title: Configure CA to connect to server with Ethernet

Answers: 0


body:
When I am sending hex numbers via computer to the arduino leonardo, it sometimes won't react, but the serial monitor says that it was sent. My code;
```
    void setup()
{
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  pinMode(A0, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop()
{
  delay(100); // Wait for 100 millisecond(s)
  Serial.println(Serial.read());
  if (Serial.read() == 49) {
    Serial.println("left");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 50) {
    Serial.println("right");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 51) {
    Serial.println("backwards");
    analogWrite(9, 1023);
    digitalWrite(A0, LOW);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 52) {
    Serial.println("forwards");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, HIGH);
  }
  if (Serial.read() == 48) {
    Serial.println("stop");
    analogWrite(9, 0);
    digitalWrite(A0, LOW);
    analogWrite(10, 0);
    digitalWrite(11, LOW);
  }
}
```
When I send the numbers 1,2,3,4, and 0, it reads what the command does. Pins A0 and D11 are direction control for the motor controller, and pins D9 and D10 are speed.

[![it is kinda a mess.][1]][1]

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

title: Arduino not reacting sometimes when reading serial commands

Answers: 1

body:
>     Serial.println(Serial.read());
>     if (Serial.read() == 49) {

You are doing two reads here, not one. So you are reading and displaying, and then reading a **second** byte (not the one you displayed).

Much better would be:

    int cmd = Serial.read();
    Serial.println(cmd);
    if (cmd == 49)  {
      ... do something ...
    } else if (cmd == 50)  {
      .. do something else ...
    }

And so on.

Also, why use numbers when you can show the ASCII characters? eg.

    int cmd = Serial.read();
    Serial.println(cmd);
    if (cmd == '1')  {
      ... do something ...
    } else if (cmd == '2')  {
      .. do something else ...
    }

You may also want to consider using:

    if (!Serial.available())
        return;

That way you don't test for serial data that does not exist.

Why the delay?


body:
Context: I have an off-grid cabin with PV powered 12V DC. I want to cut power to an inverter (12V DC ->220V AC) when I leave by pressing a button as it draws too much in standby.

Most relays I have seen that can be connected to the Arduino typically handle 10A. My inverter draws up to 180A@12V at full power (2000 W), which is way more than anything I have seen. How can I control the power to this inverter?

Someone told me of hacks that utilize the fact that you get manual switches/relays that handle big current, so you can use the Arduino to control a motor pressing the physical switch, but the concept seems somewhat brittle ... Any other takes?

```

            ┌────────────┐
            │  PV array  │
            └──────┬─────┘
                   │
             ┌─────┴───┐
             │ Charger │
           ┌─┴─────────┘
           │
           │
  ┌────────┴──┐         ┌─────────┐
  │ Batteries ├─────────┤Inverter ├────────────┐
  └────────┬──┘         └─────────┘            │
           │                                   │
           │                          ┌────────┴─────┐
           │                          │220V circuit  │
       ┌───┴───────────────┐          │  w/appliances│
Has    │ Fuse box          │          └──────────────┘
on/off │ / 12v distribution│
switch!└───────────────────┘

        ┌──────────────┐
        │12V appliances│
        └──────────────┘
```

title: How can I switch the power on/off to cut BIG currents (200A)?

Answers: 1

body:
You might look for something like a "starter relay" for an engine. Those switch on 12 V and can handle currents of 150A and more. I've seen various models on the site of my favorite distributor.

**Check the data sheet to make sure the relay can handle a continuous current of 180A**, as many starter relays can only handle the current for short periods of time (you're not running the starter motor of an engine for more than a few seconds). Other possible types are 12V-industry-rated high-current relays. Also mentioned in a comment above: The hold-current of the relay shouldn't be to big, so you don't waste energy just for the switch.

You might need to use a 2-step solution, to first convert the 5V output of the Arduino to 12 V to control the relay. (use a small relay for this, or just a mosfet).


body:
I am using the following code:

    #include "USBHostGiga.h"

    //REDIRECT_STDOUT_TO(Serial)
    Keyboard keyb;
    HostSerial ser;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      while (!Serial);
      pinMode(PA_15, OUTPUT);
      keyb.begin();
      ser.begin();
    }

    void loop() {
      if (keyb.available()) {
        auto _key = keyb.read();
        Serial.println(keyb.getAscii(_key));
      }
      while (ser.available()) {
        auto _char = ser.read();
        Serial.write(_char);
      }
      //delay(1);
    }

from here: https://docs.arduino.cc/tutorials/giga-r1-wifi/giga-usb

I am using Arduino GIGA R1 on which I have connected a USB keyboard and I press buttons. I see the results on the Serial. However, I face the following problem: When I press a button, apart of the letter I get also a square next to it. For instance, let's say I press the 'A' letter. In the serial I get 'A' letter + a square symbol. When I press 'B', I get 'B' + a square symbol, etc. I am trying for 2 days to fix it, I tried to read the button as a char array with two positions and delete the [1] where the square should be, but nothing worked. The ```auto``` type is very strange in order to make a type casting, because the Arduino IDE continuously shows me error. I cannot find a way to remove the strange 'square' ASCII character which I take with each letter pressed...The only things I noticed is that the square ASCII character is displayed the time I release the keyboard button, and also it delays to appear when I increase the delay ms in the ```delay(...);``` command. Has anyone any idea how to solve this?

title: Getting a strange symbol when pressing buttons in a USB keyboard connected to the Arduino GIGA R1

Answers: 1

body:
I don't have GIGA R1, so no practical way to test this.
I also cannot explain why it's showing up as square for you. It is common behaviour for character codes that don't have a font glyph to render in that way, but the one in question (null character) does not do that for me under the 1.x 2.x IDEs.

However, the rest of what follows may help.

[According to github](https://github.com/arduino-libraries/USBHostGiga/blob//bb48eb/USBHostGiga.h#L135),
the type that is returned by `.read()` is `HID_KEYBD_Info_TypeDef`, so if you want you should be able to:

```c++
const HID_KEYBD_Info_TypeDef _key = keyb.read();
```

However, there's not much wrong with using `auto` here.  So far as I can tell, what you're [really receiving](https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.h#L283)
is the content of [Boot mode HID reports](https://wiki.osdev.org/USB_Human_Interface_Devices#Report_format).
Not *individual* key information really, but rather the state which may include up to 6 pressed keys.
If you're only pressing one key (one *non-shift state key*; as in not "shift", "control", "alt". etc,
it shows up in array index 0, which is what [getAscii](https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/USBHostGiga.cpp#L29)
is [ultimately interpreting](https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.c#L426).

So when you release the key (all of them) you are getting a report with nothing (no key code; represented with a zero value) in `keys[0]`, and so there's nothing there from which to get an ASCII code.
What it seems to be doing is translating the 0 value that's there into [another zero](https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.c#L291).

So, it would seem all you need to do is check to see if it's a zero after the call to `getAscii`, e.g.:

```c++
if (keyb.available()) {
  const auto keyboard_input_report /*not really a key*/ = keyb.read();
  const auto first_as_ascii = keyb.getAscii(keyboard_input_report);
  //  where getAscii really means getAsciiCodeOfFirstkeyIfThereIsOneInTheReport
  if (first_as_ascii != 0) {
    Serial.println(first_as_ascii);
  }
}
```

You could to check before translation with `if (keyboard_input_report.keys[0] != 0) {`. However, the former may make more sense. Because not every key on the keyboard will map unto may onto an ASCII code value anyway.  E.g. ASCII does not represent the arrow keys, function keys, or page-up/page-down.

In any case, this code may have issues if multiple keys are pressed. It looks like doing so correctly would involve [using the internals](https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.c#L422-L426) of `getAscii` to consult the translation tables for all six of the entries in the report's `keys` array.


body:
I use a laser module (HW483) to transmit a series of 0 or 1 data and Light Sensor Photosensitive(LM393) utilizes ISR to receive data and its digital pin as output. On the transmitter, I use the PyFirmata 2 to control my Arduino Mega 2560 and the transmitted data have up to 21 continuous quantities of value 1 or 0. On the receiver, I also use Arduino Mega 2560. The transmittion rate is 1Kbps ,the received data works perfect. But when the rate is 2Kbps, the received data don’t have right numbers.
Anyone have idea? Thanks a lot

Ian (first time poster)
[![enter image description here][1]][1]

python transmitter code:
```
import time
from pyfirmata2 import ArduinoMega

board = ArduinoMega("/dev/ttyUSB0")
print("Connect to ", board.name)
blink = board.get_pin('d:3:o')
duration = 500000    // 500000 ns/bit =500us/bit  //

choice = "00000111100011"  // input transmitted data //
data = ''
for item in choice:
    data += item
// 100000000000000000000001 is the start bits and end bits //
data = '100000000000000000000001'+data+'100000000000000000000001'
while (1):
    check = input("anything")
    for item in data:
        if item == '1':
            start_time = time.monotonic_ns()
            while ((time.monotonic_ns()-start_time) <= duration):
                blink.write(1)
                print('1')
        elif item == '0':
            start_time = time.monotonic_ns()
            while ((time.monotonic_ns()-start_time) <= duration):
                blink.write(0)
                print('0')
    blink.write(0)
```
python receiver code:
```
import serial
from time import sleep, time
import numpy as np

COM_PORT = "COM4"
BAUD_RATES = 115200
ser = serial.Serial(COM_PORT, BAUD_RATES, timeout=1)

try:
    data = ""
    num = 0
    recording = 0
    a = input("Write anything to start ")
    print("Start Receive")
    while True:
        if ser.in_waiting:
            receive = ser.readline().decode()
            receive1 = int(receive)
            if receive1 >= 22:
                recording = recording + 1

            if recording == 1:
                if num % 2 == 1:
                    element = "1"
                    for item in range(receive1):
                        data += element
                        print("1")
                else:
                    element = "0"
                    for item in range(receive1):
                        data += element
                        print("0")
                num = num + 1
                break
            elif recording == 2:
                data = data[23:-1]

except KeyboardInterrupt:
    ser.close()
    print("BYE！")
```
arduino receiver code:
```
const byte interrupt = 2;
volatile boolean Potential = false;
volatile boolean a = false;
float Interval = 500;     //   500us/bit  //
volatile unsigned long int Last_time = 0;
volatile int count;

void setup() {
  attachInterrupt(digitalPinToInterrupt(interrupt), InterruptChange, CHANGE);
  Serial.begin(115200);
}

void loop() {
  if (a == true) {
    Counting_Signal();
    Potential = !Potential;
    if (count < 30) {
      Serial.print(count);
      Serial.print("\n");
    }
    a = false;
  }
}

void InterruptChange() {
  a = true;
}

void Counting_Signal() {
  count = round((micros() - Last_time) / Interval);
  Last_time = micros();
}
```

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

title: Receives data from Light sensor with ISR

Answers: 0


body:
I have succesfully connected to my hm-10 device and started configuring it using AT commands. I would like to know if it is possible to modify the data sent in advertisement and read it on another hm-10 device in some way.

I am using AT commands specified here: http://denethor.wlu.ca/arduino/MLT-BT05-AT-commands-TRANSLATED.pdf

And some from here (working less consequently): https://www.rhydolabz.com/documents/37/datasheet HM-10.pdf

This is the device I am using: https://elextra.dk/en-gb/p/bluetooth-modul-til-arduino-ble-40-at-09-hm-10/H45653

I am using Arduino UNO R3.

I can configure the HM-10 module as a slave or master, and I can set name, and check characteristics. But I am having issues in setting a flag for the advertisement. How is it possible for me to set data that can be broadcasted to all nearby bluetooth devices (mainly other HM-10 modules). It does not need to be a lot. I think the flag is one byte, which is more than enough.

Anybody has the same problem? Is there anyway to broadcast and read data with this module without connecting?

This is my current code for sending AT commands:
```
/*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo and Micro support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(19200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

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

```

title: Setting flag for sending data through advertisements using hm-10 mlt bt05 and arduino uno

Answers: 0


body:
I have to simulate an ADC that behaves as an I2C slave. The simulated values that the ADC shall expose are sent over serial, saved on an attribute and are requested by a master device over I2C.

A simplified solution is the following. I have a struct `ADC` that describes the converter:
```cpp
struct ADC
{
  uint32_t register_1;
  uint32_t register_2;

  void write_register_1(uint32_t data){
    register_1 = data;
  }

  void write_register_2(uint32_t data){
    register_2 = data;
  }

  uint8_t read(){
    return register_1;
  }

  // some other methods to setup...
};
```

In `loop()`, I read the serial in order to update the `ADC::register` value and in the `onRequest` handler I eventually send the requested data by accessing `ADC::register`:
```cpp
ADC adc{};

void setup(){
  // setup adc, Wire and Serial here
  Wire.onRequest(slaveTransmitterHandler)
}

void loop(){
  if (Serial.available() > 0)
  {
     // read serial, parse received data and check them
     uint32_t data = parse_serial(); // do anything is needed to check data...

     // update adc attribute
     uint8_t oldSREG = SREG;
     noInterrupts(); // disable interrupts to update uint32
     adc.write_register_1(data);
     SREG = oldSREG;
  }
}

void slaveTransmitterHandler(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(adc.read());
  Wire.endTransmission();
}

void slaveReceiverHandler(){
  uint32_t i2c_received_data;
  while (Wire.available){
    // fill i2c_received_data with Wire.read()
  }
  adc.write_register_2(i2c_received_data);
}
```

I'm not sure if I have to declare the `adc` object as `volatile` (this would mean to declare all `ADC` methods and variables as volatile). Is it safe to use an object inside the I2C handler called by the I2C interrupt?

As far as I know, it is not (I can find no reason why it should be different from non-class variables), but I have always worked with non-class variables and never with cpp objects. Also, I can't find any information about this topic.

It could be possible that I'm wrong with the whole design, even if it seems to me to be very consistent. I'm open to change it for something better, so please if this design is nonsense, comment on that! I'm here to learn :)

Thanks.

Luca

**Edit**:
Some clarification, since my question seems not to be clear enough: I'm doing HIL simulation, that is simulating the real hardware with its real interfaces with a simulated environment (that includes sensors and actuators). See [here][1] for more info.

One of my sensors measures a voltage and stores it in a register of an ADC (that has multiple registers). I'm simulating the behaviour of ADC registers in Arduino, and they shall communicate via I2C with the real hardware.

Hope this is more clear now.

  [1]: https://en.wikipedia.org/wiki/Hardware-in-the-loop_simulation

title: Use class object inside an ISR

Answers: 1

body:
If this is a simulation, and not actually using interrupts, then you hardly need to declare anything volatile. However your use of the Wire library makes it look less like a simulation. Personally I think your problem is under-explained. Please post all of your code. If you are simulating you won't need to worry about hardware interrupts. If you are using the Wire library you will.

Your other post https://arduino.stackexchange.com/questions/94677/get-address-of-a-i2c-transaction-when-multiple-addresses-are-registered seems to be relevant here.


body:
I'm trying to replicate a short music clip with two piezos, and I want them to play at the same time. While the right piezo is playing, I want the left one to still be looping. The problem is, I'm not sure how.

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

    //Left hand
    const int leftPin = 10; /Left pin
    const int leftTones[] = {123.4, 103.83, 138.59, 92.50}; //The looping left tones
    const int leftDelays[] = {700, 1300, 900, 900}; //How long those tones last
    const int leftNotes = 4; //How many left notes there are

    //Right hand
    const int rightPin = 2; //Right pin
    const int rightTones[] = {739.99, 587.33, 587.33, 659.25, 698.46, //The looping right tones
    659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 493.88,
    554.37, 587.33, 659.25, 587.33, 554.37, 880.00, 783.99, 739.99,
    587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33,
    659.25, 739.99, 987.77, 987.77, 1108.73, 1174.66, 783.99, 739.99,
    698.46, 1174.66, 1318.51};
    const int rightDelays[] = {700, 1000, 100, 100, 300, 300, 200, //How long those tones last
    300, 300, 200, 700, 700, 250, 150, 200, 400, 300, 300, 400, 200,
    700, 1000, 100, 100, 300, 300, 200, 400, 300, 200, 700, 700, 300,
    200, 400, 300, 200, 400, 300, 200};
    const int rightNotes = 40; //How many right notes there are

    void setup(){
        pinMode(leftPin, OUTPUT);
        pinMode(rightPin, OUTPUT);
        delay(1000);
    }

    void loop(){
      for (int i = 0; i < leftNotes; i++){
        tone(leftPin, leftTones[i]);
        delay(leftDelays[i]);
        noTone(leftPin);
      }
      for (int i = 0; i < rightNotes; i++){
        tone(rightPin, rightTones[i]);
        delay(rightDelays[i]);
        noTone(rightPin);
      }
    }
With this code, the left piezo plays first, and then the right piezo plays. It should be at the same time.

Edited Code:

    long currentMillis = 0;
    long leftPreviousMillis = 0; // previous time for left hand
    long rightPreviousMillis = 0; // previous time for right hand

    const int leftNotes = 4; // The amount of left notes
    const int rightNotes = 40; // The amount of right notes
    int leftIndex = 0; // The specific index for the left piezo
    int rightIndex = 0; // The specific index for the right piezo
    const int leftPin = 10; // The left piezo
    const int rightPin = 2; // The right piezo

    // The specific left pitches (as float)
    const float leftTones[] = {123.4, 103.83, 138.59, 92.50};
    // How long the left pitches last for
    const long leftDelays[] = {700, 1300, 900, 900};

    // The specific right pitches (as float)
    const float rightTones[] = {739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 493.88, 554.37, 587.33, 659.25, 587.33, 554.37, 880.00, 783.99, 739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 987.77, 1108.73, 1174.66, 783.99, 739.99, 698.46, 1174.66, 1318.51};
    // How long the right pitches last for
    const long rightDelays[] = {700, 1000, 100, 100, 300, 300, 200, 300, 300, 200, 700, 700, 250, 150, 200, 400, 300, 300, 400, 200, 700, 1000, 100, 100, 300, 300, 200, 400, 300, 200, 700, 700, 300, 200, 400, 300, 200, 400, 300, 200};

    void setup() {
      pinMode(leftPin, OUTPUT);
      pinMode(rightPin, OUTPUT);
      Serial.begin(9600);
      delay(1000);
      tone(rightPin, rightTones[rightIndex]);
      tone(leftPin, leftTones[leftIndex]);
    }

    void loop() {
      currentMillis = millis();
      // Left hand notes
      if (currentMillis - leftPreviousMillis >= leftDelays[leftIndex]) {
        noTone(leftPin); // Turn off the left note
        leftPreviousMillis = currentMillis;
        leftIndex++;
        if (leftIndex == leftNotes) // Reset left hand index
          leftIndex = 0;
        tone(leftPin, leftTones[leftIndex]); // Turn on the new left note
      }

      // Right hand notes
      if (currentMillis - rightPreviousMillis >= rightDelays[rightIndex]) {
        noTone(rightPin); // Turn off the right note
        rightPreviousMillis = currentMillis;
        rightIndex++;
        if (rightIndex == rightNotes) // Reset right hand index
          rightIndex = 0;
        tone(rightPin, rightTones[rightIndex]); // Turn on the new right note
      }
    }
I've done some testing, and I think it's a problem with the tones function. Right now, this code only plays the right hand notes. The problem is this part:

    tone(rightPin, rightTones[rightIndex]);
    tone(leftPin, leftTones[leftIndex]);

When I do this:

    tone(leftPin, leftTones[leftIndex]);
    tone(rightPin, rightTones[rightIndex]);

Only the left hand notes are heard. But, it's not perfect. There's little beeps and buzzes every now and then. This leaves me with the conclusion that if there are two tones at the same time, it only plays the one it reads first. I've tested it with simpler code, and it stands true.

So that begs the question, is it even possible to use two piezos at the same time with one Arduino? I'm testing it with the Arduino simulator tinkercad, so maybe that's the problem? My code works for the left piezo, and the right piezo. But when you put them together, everything messes up.

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

title: How do you use two piezos at the same time?

Answers: 2

body:
> How do you use two piezos at the same time?

Consider using a [finite state machine][1] type of programming method.

As has been discovered, using calls to the [delay()][2] function (where the processor does nothing) blocks any other feature of the sketch (user's program). In a finite state machine programming pattern, there are no calls to the delay() function.  Instead the sketch's loop() function is allowed to execute as fast as possible. The trick is to control what code is executed in the loop() function based on a state machine.  And, in this case, use time to change between different states.

In an Arduino platform (the hardware and software you never or seldom see that makes up an Arduino) a counter is always tracking elapsed time.  Use the [millis() function][3] to retrieve the current value in milliseconds (1000 milliseconds = 1 second) each time through the loop() function. Consider using a 2 state state machine. In the 1st state get the current counter value, add to it the delay in milliseconds of the next note, start the note playing and finally change the variable tracking states to the 2nd state. The next time through the loop() function, while in the 2nd state, check if the response from calling millis() again is larger then the value saved while in the 1st state.  If it is, stop playing the note and change the variable tracking states to the 1st state.

Once working, create a second similar state machine to play the counter melody.

However, as [delta-g](https://arduino.stackexchange.com/users/33871/delta-g) has pointed out, the library picked out by the O.P. apparently can not play more than one note at a time.  But,[ve7jro](https://arduino.stackexchange.com/users/37523/ve7jro) has pointed out that [this Arduino tunes library](https://github.com/nathanRamaNoodles/Noodle-Synth) may be able to satisfy the requirement of playing 2 notes at the same time as stated in the O.P.'s question.

Creating a state machine in a invaluable programming lesson.  However, [this Arduino state machine library][4] is available should the programmer wish to take advantage of it.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://www.arduino.cc/reference/en/language/functions/time/delay/
  [3]: https://www.arduino.cc/reference/en/language/functions/time/millis/
  [4]: https://www.arduino.cc/reference/en/libraries/statemachine/

body:
It's always good to look at the documentation when you have a question about how a piece of code works.  In this case I looked at the page for the tone function which can be found here.  https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/

And the second sentence on that page says it all:

> Only one tone can be generated at a time. If a tone is already playing
> on a different pin, the call to tone() will have no effect. If the
> tone is playing on the same pin, the call will set its frequency.


body:
I want to create a webServer with esp32 as AP. Now the issue is that the ESP32 provides a
ESSID not the IP address.
Here's my code

    #include <ESPAsyncWebServer.h>
    #include <SPIFFSEditor.h>

    // #include <LiquidCrystal_I2C.h>

    #include <WiFi.h>
    #include <WiFiAP.h>
    // LiquidCrystal_I2C lcd(0x27, 16, 2);

    AsyncWebServer server(80);

    const char* ssid = "ESP-NAS";
    const char* password = "NAS26672";

    void setup() {
      // lcd.init();
      // lcd.backlight();
      // lcd.setCursor(0, 0);

      Serial.begin(115200);
      Serial.println();
      Serial.println("Configuring access point...");

      // You can remove the password parameter if you want the AP to be open.
      // a valid password must have more than 7 characters
      if (!WiFi.softAP(ssid, password)) {
        log_e("Soft AP creation failed.");
        while (1);
      }
      IPAddress myIP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(myIP);
      // lcd.print(ssid);
      // lcd.setCursor(0, 1);
      // lcd.print(myIP);

      delay(500);

      server.on("/",HTTP_ANY,[](AsyncWebServerRequest *req)
      {
        req->send_P(200,"plain/text","Hink");
      });
    }

    void loop() {
    }

I can connect to the WiFi but there is not any assigned IP address.

!

title: ESP32 Static IP issue in AP mode | softAP

Answers: 0


body:
Say I'm working on a library^**1** to which I want to add support for `SD.h`^**2** but knowing for a fact that many microcotrollers don't support `SD.h` *(therefore they result in compilation errors [eg. Attiny85])* I don't want to just `#include <SD.h>` *(or even `#ifndef __SD_H__` then `#include <SD.h>`)* in `Mylibrary.h` and make it totally unusable for some microcontrollers. So I was wondering, is it considered ok to just add the functionality like...
```c++
// Mylibrary.h

#ifdef __SD_H__
    // Save functionality for those including `SD.h` to their `sketch.ino`
    void Mylibrary::save(String filename){
        SD.open(filename, FILE_WRITE)
        // ...
    }
#endif
```
...without ever including the `SD.h` in `Mylibrary.h` and hence force the user whenever he\she wants to use some SD functionallity, to just include `SD.h` in his\her `sketch.ino`?  **+***(it sound exhausting to do something like [this](https://github.com/GiorgosXou/NeuralNetworks/blob/31bb95e4cefcaefb28f6b031a634ded6c7274a7d/src/NeuralNetwork.h#L52-L55) for every MCU, as an alternative way)*

[**1**] *(in my case [this library](https://github.com/GiorgosXou/NeuralNetworks))*
[**2**] *(in my case  something related to [this](https://github.com/GiorgosXou/NeuralNetworks/issues/18#issuecomment-1792298022))*

**PS.** The reason I'm asking is because I don't remember seeing it anywhere being used that way and I'm slightly confused as to if this is the right or wrong thing to do so

title: is #ifdef __SD_H__ considered a bad practice?

Answers: 2

body:
I don't think this will work, however you could try it and see. Just set the board type to something that doesn't support SD.h.

My problem would be that your library is a separate compilation unit (ie. file) that would be compiled against the things *you* put as header files.

If your library user uses SD.h in the main .ino file, then your library (which is compiled separately) would not know about that. In other words, it wouldn't know whether or not to *implement* the Mylibrary::save function.

I think a fairly simple solution would be to put a define in the include file for your library, eg.

    #define USE_FILE_SAVING false

Then check that in your code. You don't need a whole list of MCUs, just inform the user that if they want file saving implemented to change that one line.

---

For more information see [How the IDE organizes things](https://arduino.stackexchange.com/a/13182/10794)

body:
Yes, it is in general a bad practice to use include guard define to detect if the header file is included. It will work only in a header file in a compilation unit which includes the detected header file.

In Arduino all ino files of the sketch are one compilation unit. But every C or C++ file is a separate compilations unit. They would not 'see' the include guard from an include in the ino file(s).

If you want to use the include guard define, don't relay on it exclusively. Use your own define and set it if you detect the include guard. This way user can set it if theirs SD library has a different name for the include guard.

```
#ifdef __SD_H__
#define XY_USE_SD_LIB
#endif

#ifdef XY_USE_SD_LIB
    // Save functionality for those including `SD.h` to their `sketch.ino`
    void Mylibrary::save(String filename){
        SD.open(filename, FILE_WRITE)
        // ...
    }
#endif
```
I use this in my popular ArduinoOTA library [here](https://github.com/JAndrassy/ArduinoOTA/blob/5f838871e213474e7dabf70f2ddfc5ecb6cb971a/src/ArduinoOTA.h#L121).

There is other way to detect includes and it works across compilation units, but it doesn't work on all Arduino platforms. It is the `__has_include` 'directive'. I use it [here](https://github.com/JAndrassy/TelnetStream/blob/6005d8d917ee64a80417bae5b4b964cf7a6b3726/src/NetTypes.h#L42).


body:
```c++
#include <IRremote.h>

IRrecv IR (11);

Serial.begin(9600);

void setup() {
  // put your setup code here, to run once:
  IR.enableIRIn();
}

void loop() {
  // put your main code here, to run repeatedly:
  if (IR.decode()){
    Serial.println(IR.decodedIRData.decodedRawData, HEX);
    delay(1500);
    IR.resume();
  }
}
```

title: Compilation error: 'Serial' does not name a type

Answers: 1

body: In C & C++, executable statements must be within a function. Your third statement, `Serial.begin(9600);` is (or should be) executable but since it is outside any function, the compiler tried to interpret it as a declaration - thus, the error.


body:
I have an Arduino project to control a motor's speed at 3 levels, indicated by 3 LEDs, so level 1 is speed 1 and LED 1, and so on for levels 2/3.

Also, I added a low-battery voltage indicator to monitor the battery level.

I am going to use an ATtiny45, which has 8 pins(Vcc, GND, 1 analog pin, 5 digital pins). The project needs 6 digital pins and 1 analog pin, so only one more pin is needed.

I do not want to use an expander or I2C, as they will make the project more complex, and it is only one pin!

I can use a larger microcontroller but it would be the last choice.

Here is my project's diagram and code:

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

    //********************************************^************************************************
    //  https://forum.arduino.cc/t/control-motor-speed-with-npn-and-push-button-no-driver/1184925
    //
    //
    //
    //  Version    YY/MM/DD    Comments
    //  =======    ========    ====================================================================
    //  1.00       20/23/02    Running code
    //  1.10       20/23/03    Added motor and LEDs OFF if switch pressed for >= 3 sec.
    //
    //
    //

    #define PRESSED            HIGH
    #define RELEASED           LOW

    #define ENABLED            true
    #define DISABLED           false

    #define LEDon              HIGH
    #define LEDoff             LOW

    #define MOTORoff           0

    #define lipo               A0

    float lipoV = 0;

    //GPIOs
    const byte Button        = 2;
    const byte ledpin        = 3;
    const byte ledpin1       = 4;
    const byte ledpin2       = 5;
    const byte Motor         = 9;
    const byte heartbeatLED  = 13;
    const byte Red           = 6;

    //Variables
    byte lastButton          = RELEASED;
    byte currSwitch;

    int Speed_Level;

    bool bCheckingSwitch     = DISABLED;

    //timing stuff
    unsigned long heartbeatTime;
    unsigned long switchesTime;
    unsigned long threeSecondTime;

    //                                      s e t u p ( )
    //********************************************^************************************************
    void setup()
    {
      pinMode(Button, INPUT);
      pinMode(lipo, INPUT);

      pinMode(ledpin, OUTPUT);
      pinMode(ledpin1, OUTPUT);
      pinMode(ledpin2, OUTPUT);
      pinMode(Motor, OUTPUT);
      pinMode(heartbeatLED, OUTPUT);
      pinMode(Red, OUTPUT);

    } //END of   setup()

    //                                       l o o p ( )
    //********************************************^************************************************
    void loop()
    {

      //************************************************              T I M E R  heartbeatLED

      //is it time to toggle the heartbeat LED ?
      if (millis() - heartbeatTime >= 500ul)
      {

        //restart this TIMER
        heartbeatTime = millis();

        //toggle the heartbeat LED
        if (digitalRead(heartbeatLED) == HIGH) digitalWrite(heartbeatLED, LOW);
        else digitalWrite(heartbeatLED, HIGH);
      }

      //************************************************              T I M E R  check switches
      //is it time to check our switches ?
      if (millis() - switchesTime >= 50ul)
      {
        //restart this TIMER
        switchesTime = millis();

        checkSwitches();
      }

      //************************************************              T I M E R  three seconds
      //if enabled, is it time to turn things OFF ?
      if (bCheckingSwitch == ENABLED && millis() - threeSecondTime >= 2000ul)
      {
        //we are finished with this TIMER
        bCheckingSwitch = DISABLED;

        //restart the sequence
        Speed_Level = -1;

        analogWrite(Motor, MOTORoff);
        digitalWrite(ledpin, LEDoff);
        digitalWrite(ledpin1, LEDoff);
        digitalWrite(ledpin2, LEDoff);
        digitalWrite(Red, LEDoff);
      }

    } //END of   loop()

    //                               c h e c k S w i t c h e s ( )
    //********************************************^************************************************
    void checkSwitches()
    {
      byte state;

      //************************************************              Button
      state = digitalRead(Button);

      //has there been a state change in the switch ?
      if (lastButton != state)
      {
        //update to the new state
        lastButton = state;

        //*******************************
        if (state == PRESSED)
        {
          //enable the TIMER
          bCheckingSwitch = ENABLED;

          //start the TIMER
          threeSecondTime = millis();
        }

        //*******************
        //the switch was released
        else
        {
          //disable the TIMER
          bCheckingSwitch = DISABLED;

          Speed_Level++;
          lipoV = analogRead(lipo);

          //battery checker
          if(lipoV < 680){
            digitalWrite(Red,LEDon);
          }

           else
           {
            digitalWrite(Red,LEDoff);

           }

          //don't go over 3
          if (Speed_Level >= 4)
          {
            Speed_Level = 0;
          }

          //*******************
          if (Speed_Level == 1)
          {
            analogWrite(Motor, 50);
            digitalWrite(ledpin, LEDon);
            digitalWrite(ledpin1, LEDoff);
            digitalWrite(ledpin2, LEDoff);
          }

          //*******************
          else if (Speed_Level == 2)
          {
            analogWrite(Motor, 75);
            digitalWrite(ledpin, LEDoff);
            digitalWrite(ledpin1, LEDon);
            digitalWrite(ledpin2, LEDoff);
          }

          //*******************
          else if (Speed_Level == 3)
          {
            analogWrite(Motor, 100);
            digitalWrite(ledpin, LEDoff);
            digitalWrite(ledpin1, LEDoff);
            digitalWrite(ledpin2, LEDon);
          }

          //*******************
          else
          {
            analogWrite(Motor, MOTORoff);
            digitalWrite(ledpin, LEDoff);
            digitalWrite(ledpin1, LEDoff);
            digitalWrite(ledpin2, LEDoff);
            digitalWrite(Red,LEDoff);
          }

      }

    }
    }//END of   checkSwitches()

    //********************************************^************************************************

Can I use tA0 as input and output at the same time like this?

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

Or can I reduce the LED pins, meaning use 1 pins for 2 LEDs?

  [1]: https://i.stack.imgur.com/tb4KJ.png
  [2]: https://i.stack.imgur.com/KnlLG.png

title: Just one more pin!

Answers: 2

body:
You may try [charlieplexing][] your LEDs. Using only 3 digital pins
you can drive up to 6 LEDs. A web search for “charlieplexing
Arduino” should get you started.

[charlieplexing]: https://en.wikipedia.org/wiki/Charlieplexing

body:
As a (slightly hacky and binary :) ) suggestion, you could use just two LEDs and free up a pin with the following...

Level 1 - LED 1 on, LED 2 off

Level 2 - LED 1 off, LED 2 on

Level 3 - LED 1 on, LED 2 on

This is a really simple change to your current set up and code

Alternatively (as suggested by @dandavis) use a set of 3 neopixels and drive from just 1 pin


body:
I'm getting ready to add DS1307 support to my Arduino app, and was *horrified* when I looked at the sourcecode for the RTC_DS1307 class in Adafruit's RTClib library...

~~~
DateTime RTC_DS1307::now() {
  uint8_t buffer[7];
  buffer[0] = 0;
  i2c_dev->write_then_read(buffer, 1, buffer, 7);

  return DateTime(bcd2bin(buffer[6]) + 2000U, bcd2bin(buffer[5]),
                  bcd2bin(buffer[4]), bcd2bin(buffer[2]), bcd2bin(buffer[1]),
                  bcd2bin(buffer[0] & 0x7F));
}
~~~

... and realized that it appears to be instantiating a new throw-away DateTime object on the heap every time you call now()... which AFAIK, is the **ultimate** Arduino C++ taboo.

I was about to tear into the class and rewrite it to reuse a singleton DateTime object that gets created once and reused forever... but then I remembered about return value optimization.

**Is** this actually a scenario where RVO will automagically kick in to save the day and prevent a heap-allocation (by pre-allocating space for the DateTime object on the caller's stack prior to calling `now()`), or is this library indeed doing something as taboo as I think it is?

title: Using Adafruit RTClib without fragmenting the heap

Answers: 2

body:
I think you are confusing the stack and the heap. For something to appear in the heap you would expect to see the words `new` or `malloc` which I don't see.

What is happening here is that a DateTime object is being created (in the stack frame of the current function) by `RTC_DS1307::now` which is being (presumably) copied into a variable of that type in the caller's stack frame when the function returns.

No memory is being wasted here.

---

> it appears to *literally* be instantiating a new throw-away DateTime object on the heap

What gives you that idea? The heap is not involved without you using `new` or `malloc`.

---

The heap is a block of memory used for dynamic memory allocation by using `malloc` or `new`, generally speaking. Typically it will be allocated past the place in RAM where variables are allocated (ie. after all the variables) and grow upwards, whereas the stack will be allocated at the end of available memory and grow downwards. Thus they don't clash until they collide, either by using too much stack (eg. by recursive function calls) or by allocating too much of the heap (by repeatedly calling `malloc` and without calling `free`).

When you use the heap, by using `malloc` you will get a *pointer* which you can then use, and pass around. That memory which you have reserved is yours until you free it, by literally calling `free`. In C++ something very similar is done by using `new` and `delete`.

If you don't call `malloc` or use `new` then you aren't using the heap, end of story.

body:
I wrote a minimal sketch that calls `RTC_DS1307::now()`, disassembled
it, and here is what I saw:

 * The caller allocates 6 bytes on the stack for holding the return
   value.

 * It writes the address of this stack location in the register pair
   r25:r24, as per the AVR calling convention,1 then calls
   `RTC_DS1307::now()`.

 * As the callee computes the fields of the resulting `DateTime` (by
   means of inlined calls to `bcd2bin()`), it writes them directly into
   the caller's stack frame, with no intermediate copy in RAM.

This looks to me like return value optimization.

**However**, in order to witness this behavior, I had to call
`RTC_DS1307::now()` _twice_. If the method is called from a single place
within the sketch, the compiler inlines it, and there isn't even a
function call to begin with.

Then, of course, the heap is never touched.

1 You would expect the `this` pointer to be passed as the
first argument, in r25:r24. It would seem it has been optimized out,
which makes sense given that there is only one `RTC_DS1307` object in
the whole sketch.


body:
I am wrestling with the below example.
I have a RasPi on the network running Mosquito with username and password credentials setup and I know this is working.

If I load the below example, I can confirm the following:

- It does connect to my Wi-Fi
- It does connect to the mqtt broker
- It does publish the example data (confirmed in serial monitor window and MQTTBox running separately)
- But, it never receives a message on the subscribed topic.

I also have a VM with Mosquito running without credentials and if I swap to that, then messages sent on the subscribed topic do appear in the serial monitor.

I am using an ESP8266 D1 and am perplexed. Any thoughts appreciated.

<!-- language: c++ -->

    /***************************************************
      Adafruit MQTT Library ESP8266 Example

      Must use ESP8266 Arduino from:
        https://github.com/esp8266/Arduino

      Works great with Adafruit's Huzzah ESP board & Feather
      ----> https://www.adafruit.com/product/2471
      ----> https://www.adafruit.com/products/2821

      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Tony DiCola for Adafruit Industries.
      MIT license, all text above must be included in any redistribution
     ****************************************************/
    #include <ESP8266WiFi.h>
    #include "Adafruit_MQTT.h"
    #include "Adafruit_MQTT_Client.h"

    /************************* WiFi Access Point *********************************/

    #define WLAN_SSID       "my_network_ssid"
    #define WLAN_PASS       "my_network_ssid_password"

    /************************* Adafruit.io Setup *********************************/

    #define AIO_SERVER      "ipaddress for a raspberry pi only running mosquitto with username and password enabled - tested and working"
    #define AIO_SERVERPORT  1883                   // use 8883 for SSL
    #define AIO_USERNAME    "mosquitto_username"
    #define AIO_KEY         "mosquitto_password"

    /************ Global State (you don't need to change this!) ******************/

    // Create an ESP8266 WiFiClient class to connect to the MQTT server.
    WiFiClient client;
    // or... use WiFiClientSecure for SSL
    //WiFiClientSecure client;

    // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
    Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

    /****************************** Feeds ***************************************/

    // Setup a feed called 'photocell' for publishing.
    // Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
    Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell");

    // Setup a feed called 'onoff' for subscribing to changes.
    Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/mytestfeeds/onoff/"); //have changed the topic from default

    /*************************** Sketch Code ************************************/

    // Bug workaround for Arduino 1.6.6, it seems to need a function declaration
    // for some reason (only affects ESP8266, likely an arduino-builder bug).
    void MQTT_connect();

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

      Serial.println(F("Adafruit MQTT demo"));

      // Connect to WiFi access point.
      Serial.println(); Serial.println();
      Serial.print("Connecting to ");
      Serial.println(WLAN_SSID);

      WiFi.begin(WLAN_SSID, WLAN_PASS);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println();

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

      // Setup MQTT subscription for onoff feed.
      mqtt.subscribe(&onoffbutton);
    }

    uint32_t x=0;

    void loop() {
      // Ensure the connection to the MQTT server is alive (this will make the first
      // connection and automatically reconnect when disconnected).  See the MQTT_connect
      // function definition further below.
      MQTT_connect();

      // this is our 'wait for incoming subscription packets' busy subloop
      // try to spend your time here

      Adafruit_MQTT_Subscribe *subscription;
      while ((subscription = mqtt.readSubscription(5000))) {
        if (subscription == &onoffbutton) {
          Serial.print(F("Got: "));
          Serial.println((char *)onoffbutton.lastread);
        }
      }

      // Now we can publish stuff!
      Serial.print(F("\nSending photocell val "));
      Serial.print(x);
      Serial.print("...");
      if (! photocell.publish(x++)) {
        Serial.println(F("Failed"));
      } else {
        Serial.println(F("OK!"));
      }

      // ping the server to keep the mqtt connection alive
      // NOT required if you are publishing once every KEEPALIVE seconds
      /*
      if(! mqtt.ping()) {
        mqtt.disconnect();
      }
      */
    }

    // Function to connect and reconnect as necessary to the MQTT server.
    // Should be called in the loop function and it will take care if connecting.
    void MQTT_connect() {
      int8_t ret;

      // Stop if already connected.
      if (mqtt.connected()) {
        return;
      }

      Serial.print("Connecting to MQTT... ");

      uint8_t retries = 3;
      while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
           Serial.println(mqtt.connectErrorString(ret));
           Serial.println("Retrying MQTT connection in 5 seconds...");
           mqtt.disconnect();
           delay(5000);  // wait 5 seconds
           retries--;
           if (retries == 0) {
             // basically die and wait for WDT to reset me
             while (1);
           }
      }
      Serial.println("MQTT Connected!");
    }

title: Arduino secure mqtt example not subscribing to topic

Answers: 0