text:
Is there something that I need to do to make the code from this answer compile?
I tried to compile the following code (using Arduino 1.8.16 with an esp8266-12)
extern volatile unsigned long timer0_millis;
unsigned long new_value = 0;

void setup(){
  //Setup stuff
}

void loop(){
  //Do stuff
  //--------

  //Change Millis
  setMillis(new_value);
}

void setMillis(unsigned long new_millis){
  uint8_t oldSREG = SREG;
  cli();
  timer0_millis = new_millis;
  SREG = oldSREG;
}

from an answer to this question, but I get the following error
 error: 'SREG' was not declared in this scope
   uint8_t oldSREG = SREG;
                 ^
exit status 1
'SREG' was not declared in this scope

I wouldn't necessarily want to use this code for any real purpose, other than as an exercise in learning.  What am I missing?  What is SREG ?

SREG is the processor status register. One of the bits in there is the interrupt flag, which is cleared with the cli() command and reset at the end of the function. Why the original poster used the register instead of just using cli/sei is unclear. (Note: Instead of cli() and sei() the arduino documentation uses the much clearer equivalents noInterrupts() and interrupts().)
This SREG register is, in this form, hardware specific and therefore not available if you're using the esp8266 toolchain. The above code builds fine with an Arduino Uno or similar board. To build for the esp8266, change the code to:
void setMillis(unsigned long new_millis){
  noInterrupts();
  timer0_millis = new_millis;
  interrupts();
}

I don't have such a board, so I can't verify it really works on this board. You might get a linker error about a non-existing timer0_millis variable.

Re “Why the original poster used the register instead of just using cli/sei is unclear”: If setMillis() is ever called from a critical section (a context where interrupts are turned off), you don't want it to enable interrupts before returning.

Ok, that makes sense, but is a bit beyond the point he's trying to make there, I think.


text:
Control D+ and D- USB lines using an arduino disconnect/connect
I am using Arduino to remotely trigger a shutter action. All is well, until I hook up a USB cable on the 4 regular USB pins. This cable runs between a Sony camera and a printer. But I can not take an image when the D+ and D- are connected.
At this moment I have a manual switch in the usb cable. It works, but I would rather have Arduino kill the line, take the image and restore the line.
I understand I can use a relay, but is there another way?
Is a TRIAC an option? How would I need to hook up the components.

triac? that is for AC. I am not an expert., but you don't want any interference on the data lines so the control circuit mut be isolated from the data lines. so a relay I guess is the only good way.

It this USB connection you're talking about doing something like PictBridge?

I would say this is better suited for electrical stackexchange. It is more about the electrical part of the USB interface and not about Arduino. I think there you will get better answers.

I thought of the triac because of it's use in a solid state relay. USB data lines are bi-directional, that's why I thought about TRIACS. My safest bett will be a 2 channel relay I guess.

source: Stack Exchange

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

sort: votes


text:
Serial.write - sedd ascii characters with hex value in the same line
Working on making a controller for a haunted house prop. Trying to get it to interface with a device.
Was able to use a serial analyzer to see what commands and values are being sent.
the hex codes being sent over serial for manual control is " 40 4d 01" which translates to "@M[?]"
the third byte 01 is the configuration state you want to have it change to. I'm using a byte to store the value between 0-255.
I'm stumped at how to send 2 ASCII characters but in the same Serial.write() command send a raw value, or at how to send them all as hex. I'm sure this is straight forward and I'm just unaware of some simple function.

hex is just a human representation of binary ... it is easier to write 4d instead of 01001101 ... it is just a number ... decimal 77

If you see "@M[?]", which means your are reading it as ASCII. 40 hex in ASCII is '@'. You probably send the data correctly if you are using Serail.write() but when you read the data with uint8_t incomingByte = Serial.read(), the return would be in byte(i.e. uint8_t) instead of char, to see the correct HEX, use Serial.print(incomingByte, HEX);.

First of all, I will challenge your assumption that you have to send the
three bytes in the same call to Serial.write(). There is no real
advantage in doing so. Serial output is handled through a memory buffer
that is consumed by the serial port within an interrupt service routine.
Serial.write() only writes to that memory buffer. Thus, you can
simply:
Serial.write("@M");
Serial.write(1);

and the receiver will not see the difference. There will be no gap
between the 'M' and the 1. There is no notion of “messages” or
“frames” on a serial link, unless an upper layer protocol adds its own
framing, which is not the case here.
Next, if you really want to issue a single call (futile as this is), you
could
Serial.write("@M\1");

This, however, will not work if the last byte is zero. The method shown
by the busybee is more general ans is able to send a zero-valued byte.

You can use a byte array for this:
    // at the appropriate place in your code:
    byte message[] = { '@', 'M', 0x01 };
    Serial.write(message, sizeof message);

If you need, you can prepare the array and just assign the value:
byte message[] = { '@', 'M', 0 };

// ...

    byte value = 0x01; // or any other assignment

    // at the appropriate place in your code:
    message[2] = value;
    Serial.write(message, sizeof message);

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


text:
How to change the default SPI pin used in SPI and Ethernet library
Hello i have a custom board of the RP2040 and would like to use the ethernet library. But the ethernet example webClient uses the default SPI pins of whatever board it is being used, but what if im going to use a board (such as the RP20400 with multiple SPI channels or have alternate pins for the spi chanels, How do i set the SPI mosi,miso,cs of the SPI in the ethernet library?
So i have found a way to make it work, i Edited the file under
\AppData\Local\Arduino15\packages\arduino\hardware\mbed_rp2040\2.4.1\variants\RASPBERRY_PI_PICO\pins_arduino.h

change the number to the pin you like.
// SPI
#define PIN_SPI_MISO  (0u)
#define PIN_SPI_MOSI  (3u)
#define PIN_SPI_SCK   (2u)
#define PIN_SPI_SS    (1u)

But problem with this now is every RP2040 board will now make it their default SPI pins,
Is there anything i can do to keep the modification to my own sketch only?

the Arduino Ethernet library uses the SPI object from the SPI library

@Juraj I could not find any SPI macros or declerations on ethernet.h which makes it tricky to trace

https://github.com/arduino/ArduinoCore-mbed/blob/master/libraries/SPI/SPI.cpp#L117

@Juraj Oh ! so its initialized at the inside the SPI.h and not ethernet.h. So as mentioned in my edit changing pin.arduino.h changes the setting for all the boards, in my sketch can i override that decleration. So maybe redeclare it after the SPI.h include, something like #include <spi.h>;  arduino::MbedSPI SPI(0, 3, 2); #include <ethernet.h>. I will try this out right away

https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

It would be a hasle if another PC will be used as i have to port the new variant every single time. For now im looking for ways to override that decleration, with my own. I think its easier that way plus, it makes the sketch portable as everything is done on the sketch

you can't do it in the sketch. the library files are compiled without knowing about the sketch. you can put the variant files on github as I do

@Juraj yes, thats why the redifinition must happen at compile time not at runtime, via a macro or some other means (not sure if C/C++ allows it, still looking for ways)

it is not possible. custom variant files or changing the library are your only options to change what pins will the SPI library use

@Juraj you are right the definition was not in the .h but the .cpp so that mean there is no way to access it in my sketch. a bit off topic quesiton, why do i not see what frequency the spi is set at? which file was the spi frequency set at?

the frequency is set for SPI transaction in the Ethernet library. https://github.com/arduino-libraries/Ethernet/blob/7c32bbe146bbe762093e4f021c3b12d7bf8d1629/src/utility/w5100.h#L21

Nice its using the default 14MHz , im using the w5500 and can go to 30Mhz

@Juraj there is way !! but sadly i cannot post it because question has been closed, we can reassign the pin as mentioned here https://github.com/arduino/ArduinoCore-mbed/issues/339. For i2c  MbedI2C myWire(6, 7); for SPI MbedSPI mySPI(4, 3, 2); and for uart UART mySerial(0, 1);

and how do you tell the Ethernet library to use mySPI?


text:
Why does Arduino Due appear to halt after single call to ADC_Handler?
In the simple example below I just software trigger an ADC acquisition and then set the builtin LED's digital out in the interrupt handler. I don't know why the program appears to halt however.

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

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  adc_enable_channel(ADC, ADC_CHANNEL_6);
  adc_enable_interrupt(ADC, ADC_IER_EOC6);
  pmc_enable_periph_clk(ID_ADC);
  NVIC_EnableIRQ(ADC_IRQn);

  Serial.println("GO");
}

void loop()
{
  Serial.println("RUNNING");
  adc_start(ADC);
}

void ADC_Handler(void)
{
  digitalWrite(13,HIGH);
  adc_get_status(ADC);
}

I know the handler gets called because the LED lights.  The main loops appears to stop running after this as it lo longer prints out anything.  If I don't trigger an acquision in the main loop it runs forever. Likewise if I don't enable the interrupt or the NVIC.
I can't explain this behavior.

There's no reference to ADC_Handler in your setup code, so I doubt this is really called.

Possible duplicate: https://arduino.stackexchange.com/questions/19924/arduino-due-interrupt-based-adc-hangs-processing?rq=1

@PMF As with other ISRs, it overrides a weak reference in Arduino15\packages\arduino\hardware\sam\1.6.12\cores\arduino\coretex_handlers.c It is definitely called because the LED lights up only if that digitalWrite is there.

The freeze will occur unless unless ADC_ISR bits 0-15 are 0 at the end of the interrupt handler.  In this case, ISR returns bit 6 set for the enabled channel (6).  For many interrupts, the bit can be reset to 0 by simply reading ADC_ISR. However for end-of-conversion interrupts the converted data register for that channel must be read for the ISR bit to be set to 0.
Therefore this code will not halt. (I included some extra printouts to make clear the register values at each point in time.)
volatile uint32_t LAST = 0;
volatile uint32_t CHAN6 = 0;
volatile uint32_t ISR1 = 0;
volatile uint32_t ISR2 = 0;

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

  adc_enable_channel(ADC, ADC_CHANNEL_6);

  adc_enable_interrupt(ADC, ADC_IER_EOC6);

  pmc_enable_periph_clk(ID_ADC);

  NVIC_ClearPendingIRQ(ADC_IRQn);
  NVIC_EnableIRQ(ADC_IRQn);

  Serial.println("GO");
  adc_configure_trigger(ADC, ADC_TRIG_SW,0);
}

void loop()
{
  Serial.println(ISR1,BIN);
  Serial.println(ISR2,BIN);

  adc_start(ADC);
  delay(1000);
}

void ADC_Handler(void)
{
  ISR1 = adc_get_status(ADC); // chan 6 bit =1
  LAST = adc_get_latest_value(ADC);
  ISR1 = adc_get_status(ADC); // chan 6 bit =1 (still)

  CHAN6 = adc_get_channel_value(ADC, ADC_CHANNEL_6);
  ISR2 = adc_get_status(ADC); // chan 6 bit = 0
}

However, I will note that the datasheet for the chip says on page 1322 Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.
This appears to be false. Reading ADC_LCDR does not clear the status bit and will cause a hang.  ADC_CDR6 must be read specifically to avoid a hang.


text:
How to send multiple data over serial in one byte?
I'm currently reading 3 limit switches and sending those data over Serial.write using the following code.
#include <SPI.h>
#include <Wire.h>
#include <arduino-timer.h>

//Define limit switch pins
#define LEFT_SWITCH_PIN 5
#define RIGHT_SWITCH_PIN 6
#define REAR_SWITCH_PIN 7

bool left_switch_state;
bool right_switch_state;
bool rear_switch_state;
bool switch_state_array[3] = {left_switch_state,right_switch_state,rear_switch_state};
int switch_pin_array[3] = {LEFT_SWITCH_PIN,RIGHT_SWITCH_PIN,REAR_SWITCH_PIN};

int send_status_state = 0;

void setup() {
    Wire.begin();
    Serial.begin(115200);
    status_timer.every(200, sendStatus);
}

void sendStatus() {
  if (send_status_state == 0) {
    getLimitSwitch();

    unsigned char buf[5];
    buf[0] = 'S';
    buf[1] = switch_state_array[0];
    buf[2] = switch_state_array[1];
    buf[3] = switch_state_array[2];
    buf[4] = '|';
    Serial.write(buf,5);
    send_status_state = 1;

  }
}

void loop() {
    status_timer.tick();
  }

void getLimitSwitch()
{
  for (int i=0; i<3; i++)
  {
    switch_state_array[i] = digitalRead(switch_pin_array[i]);
  }
}
/*********************************************************************************************************
    END FILE
*********************************************************************************************************/

as you can see I'm currently using 3 bytes to send the states of each limit switch separately.
    buf[1] = switch_state_array[0];
    buf[2] = switch_state_array[1];
    buf[3] = switch_state_array[2];

How can I send all limit switch data in one byte?

You should learn how to use bitwise operators. These are needed to do what you want.
We can save the state of each switch in one bit each. For this we first define our global variable that will hold the switch states:
byte switch_states = 0;

Then in getLimitSwitch() we loop through our pins. The result of digitalRead() is always one of 0 and 1. So we can take this value and bit shift it to the left. Then we do bitwise OR operations to put the value into our switch_states variable:
void getLimitSwitch()
{
  for (int i=0; i<3; i++)
  {
    switch_states |= ( digitalRead(switch_pin_array[i]) << i );
  }
}

Then you can send that byte over Serial. It can hold up to 8 states.
Serial.write(switch_states);

The most interesting line here is
switch_states |= ( digitalRead(switch_pin_array[i]) << i );

Lets follow here with an example: Lets assume we look at the pin with index 2 and it is HIGH. So we have switch_states |= ( 1 << 2 ). This equates to the following representation in binary switch_states |= ( 0b00000001 << 2 ). << shifts the bit pattern to the left; by 2 digits in this case. So we get switch_states |= 0b00000100;. That is equal to switch_states = switch_states | 0b00000100;. The bitwise OR operator | return a value where each bit is set to 1, if the corresponding bit in at least one of the two operants is 1. Here we use this to put the bits together.
If the pins have the states HIGH,LOW,HIGH the resulting value will be 0b00000101, aka. 5 in decimal.

On the other side you might want to decode this value. How it is done depends on the architecture (using a PC, a microcontroller, ...). But on an Arduino you can test for a pin to be HIGH with this:
if(received_states_variable & (1 << pin_index))

Note: Doing this
bool left_switch_state;
bool right_switch_state;
bool rear_switch_state;
bool switch_state_array[3] = {left_switch_state,right_switch_state,rear_switch_state};

doesn't make much sense. You initialize the array elements just with the implicitly to false initialized variables. You just don't need the normal bool variables. You can just simply define your bool array. If you want to initialize it explicitly, just use true or false directly:
bool switch_state_array[3] = {false, false, false};

or even
bool switch_state_array[3] = {false};

"These are needed to do what you want." Well, there are also bit field structs. I like to use them extensively in C and then in Rust I get told that transmutation is bad and I should feel bad.

I don't know Rust and I don't know why this should be so bad. But you are right. You can also ise bitfield structs. Maybe you want to add another answer with a short explanation how to use them. I personally use bitshifting but for the OP and others knowing all the options can help further


text:
Peculiar behaviour of arduino pro micro
I am working with an arduino pro micro and I am facing a peculiar problem. The project I am working with includes arduino MKR NB 1500 as well. I am transferring data from MKR NB 1500 to arduino pro micro through Serial1(Rx/Tx pins). I have added the sample code that i am using on both boards
program in arduino MKR NB 1500
void setup() {
  Serial1.begin(9600);
}
void loop() {
  Serial1.print("printing");
  delay(2000);
}

program in pro micro
#include "Keyboard.h"

void setup() {
  Serial1.begin(9600);
  Keyboard.begin();
}

void loop() {
  Keyboard.write(Serial1.read());
}

I would like to transfer some data from MKR NB 1500 to pro micro which emulates a keyboard and prints the data in a editor. I am powering the arduino MKR NB 1500 via USB using its native USB port. The pro micro works as expected when I connect both these boards to USB ports in the same laptop. (Output: printingprintingprintingprinting)
However, the pro micro prints garbage values when I connect the MKR NB 1500 to a USB port belonging to a different laptop. (Output: a10joh<qqj<zstjo)
Is there any reason for such a behavior. Please let me know if you need more information from my side or if i have not made myself clear.

Have you connected the grounds? Also you should check Serial1.available() on the pro micro.

Thank you for your response. Connecting the grounds seems to be working, i will do few more tests. Could you please let me know why this is the case. I am new to working with arduino it would be helpful in the future.

https://majenko.co.uk/blog/our-blog-1/the-importance-of-sharing-grounds-12

if (Serial1.available()) is missing. The MKR can emulate keyboard too. with the same library

I am connecting the native USB port on the MKR board to a barcode scanner. The MKR board in this case is acting as a USB Host as a result I cannot use the MKR board to emulate a keyboard.

The data I would like to transfer to pro micro comes from the barcode scanner.

Connecting the grounds seems to be working, i will do few more tests. Could you please let me know why this is the case ... it is an electric circuit issue ... would you expect a lightbulb to light if you connected only one wire between the bulb and a battery?

Ground is the reference point for the microcontrollers to measure and output voltage. The actual place of their ground (as electrical potential) may be different, so the output voltage of the other microcontroller will not make much sense. When connecting the grounds you make sure, that both microcontrollers use the same reference point and thus can talk to each other

you can use a barcode scanner with SPI interface

You have to connect ground between the modules. Without common ground the logic level of signal can't be measured. While both boards were powered over USB from the same laptop the boards had common ground.

read returns -1 if nothing is available so check if some character was received:
void loop() {
  if (Serial1.available()) {
    Keyboard.write(Serial1.read());
  }
}

btw: The MKR can emulate a keyboard too with the Keyboard library.


text:
got a compiling error while programming node mcu
i was programming my node mcu i modified the code and got a complination error but when i compiled the original code i got no error
modified code
#include "arduino_secrets.h"
#include "thingProperties.h"

// define the GPIO connected with Relays and switches
#define RelayPin1 5  //D1
#define RelayPin2 4  //D2
#define RelayPin3 14 //D5
#define RelayPin4 12 //D6

#define RelayPin5 2  //d4
#define RelayPin6 0   //D3
#define RelayPin7 13  //D7
#define RelayPin8 15   //d8

#define wifiLed   16   //D0

int toggleState_1 = 0; //Define integer to remember the toggle state for relay 1
int toggleState_2 = 0; //Define integer to remember the toggle state for relay 2
int toggleState_3 = 0; //Define integer to remember the toggle state for relay 3
int toggleState_4 = 0; //Define integer to remember the toggle state for relay 4
int toggleState_5 = 0; //Define integer to remember the toggle state for relay 5
int toggleState_6 = 0; //Define integer to remember the toggle state for relay 6
int toggleState_7 = 0; //Define integer to remember the toggle state for relay 7
int toggleState_8 = 0; //Define integer to remember the toggle state for relay 8

void relayOnOff(int relay) {

  switch (relay) {
    case 1:
      if (toggleState_1 == 0) {
        digitalWrite(RelayPin1, HIGH); // turn on relay 1
        toggleState_1 = 1;
        Serial.println("Device1 ON");
      }
      else {
        digitalWrite(RelayPin1, LOW); // turn off relay 1
        toggleState_1 = 0;
        Serial.println("Device1 OFF");
      }
      delay(100);
      break;
    case 2:
      if (toggleState_2 == 0) {
        digitalWrite(RelayPin2, HIGH); // turn on relay 2
        toggleState_2 = 1;
        Serial.println("Device2 ON");
      }
      else {
        digitalWrite(RelayPin2, LOW); // turn off relay 2
        toggleState_2 = 0;
        Serial.println("Device2 OFF");
      }
      delay(100);
      break;
    case 3:
      if (toggleState_3 == 0) {
        digitalWrite(RelayPin3, HIGH); // turn on relay 3
        toggleState_3 = 1;
        Serial.println("Device3 ON");
      } else {
        digitalWrite(RelayPin3, LOW); // turn off relay 3
        toggleState_3 = 0;
        Serial.println("Device3 OFF");
      }
      delay(100);
      break;
     case 4:
      if (toggleState_4 == 0) {
        digitalWrite(RelayPin4, HIGH); // turn on relay 3
        toggleState_4 = 1;
        Serial.println("Device4 ON");
      } else {
        digitalWrite(RelayPin4, LOW); // turn off relay 3
        toggleState_4 = 0;
        Serial.println("Device4 OFF");
      }
      delay(100);
      break;
     case 5:
      if (toggleState_5 == 0) {
        digitalWrite(RelayPin5, HIGH); // turn on relay 3
        toggleState_5 = 1;
        Serial.println("Device5 ON");
      } else {
        digitalWrite(RelayPin5, LOW); // turn off relay 3
        toggleState_5 = 0;
        Serial.println("Device5 OFF");
      }
      delay(100);
      break;
     case 6:
      if (toggleState_6 == 0) {
        digitalWrite(RelayPin6, HIGH); // turn on relay 3
        toggleState_6 = 1;
        Serial.println("Device6 ON");
      } else {
        digitalWrite(RelayPin6, LOW); // turn off relay 3
        toggleState_6 = 0;
        Serial.println("Device6 OFF");
      }
      delay(100);
      break;
     case 7:
      if (toggleState_7 == 0) {
        digitalWrite(RelayPin7, HIGH); // turn on relay 3
        toggleState_7 = 1;
        Serial.println("Device7 ON");
      } else {
        digitalWrite(RelayPin7, LOW); // turn off relay 3
        toggleState_7 = 0;
        Serial.println("Device7 OFF");
      }
      delay(100);
      break;
    case 8:
      if (toggleState_8 == 0) {
        digitalWrite(RelayPin8, HIGH); // turn on relay 4
        toggleState_8 = 1;
        Serial.println("Device8 ON");
      }
      else {
        digitalWrite(RelayPin8, LOW); // turn off relay 4
        toggleState_8 = 0;
        Serial.println("Device8 OFF");
      }
      delay(100);
      break;
    default : break;
  }
}

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);

  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();

  pinMode(RelayPin1, OUTPUT);
  pinMode(RelayPin2, OUTPUT);
  pinMode(RelayPin3, OUTPUT);
  pinMode(RelayPin4, OUTPUT);
  pinMode(RelayPin5, OUTPUT);
  pinMode(RelayPin6, OUTPUT);
  pinMode(RelayPin7, OUTPUT);
  pinMode(RelayPin8, OUTPUT);

  pinMode(wifiLed, OUTPUT);

  digitalWrite(RelayPin1, LOW);
  digitalWrite(RelayPin2, LOW);
  digitalWrite(RelayPin3, LOW);
  digitalWrite(RelayPin4, LOW);
  digitalWrite(RelayPin5, LOW);
  digitalWrite(RelayPin6, LOW);
  digitalWrite(RelayPin7, LOW);
  digitalWrite(RelayPin8, LOW);

  digitalWrite(wifiLed, HIGH);  //Turn ON WiFi LED
}

void loop() {
  ArduinoCloud.update();

  if (WiFi.status() != WL_CONNECTED)
  {
    digitalWrite(wifiLed, HIGH); //Turn ON WiFi LED
  }
  else{
    digitalWrite(wifiLed, LOW); //Turn OFF WiFi LED
  }
}

the original code
#include "arduino_secrets.h"
#include "thingProperties.h"

// define the GPIO connected with Relays and switches
#define RelayPin1 5  //D1
#define RelayPin2 4  //D2
#define RelayPin3 14 //D5
#define RelayPin4 12 //D6

#define SwitchPin1 10  //SD3
#define SwitchPin2 0   //D3
#define SwitchPin3 13  //D7
#define SwitchPin4 3   //RX

#define wifiLed   16   //D0

int toggleState_1 = 0; //Define integer to remember the toggle state for relay 1
int toggleState_2 = 0; //Define integer to remember the toggle state for relay 2
int toggleState_3 = 0; //Define integer to remember the toggle state for relay 3
int toggleState_4 = 0; //Define integer to remember the toggle state for relay 4

void relayOnOff(int relay) {

  switch (relay) {
    case 1:
      if (toggleState_1 == 0) {
        digitalWrite(RelayPin1, HIGH); // turn on relay 1
        toggleState_1 = 1;
        Serial.println("Device1 ON");
      }
      else {
        digitalWrite(RelayPin1, LOW); // turn off relay 1
        toggleState_1 = 0;
        Serial.println("Device1 OFF");
      }
      delay(100);
      break;
    case 2:
      if (toggleState_2 == 0) {
        digitalWrite(RelayPin2, HIGH); // turn on relay 2
        toggleState_2 = 1;
        Serial.println("Device2 ON");
      }
      else {
        digitalWrite(RelayPin2, LOW); // turn off relay 2
        toggleState_2 = 0;
        Serial.println("Device2 OFF");
      }
      delay(100);
      break;
    case 3:
      if (toggleState_3 == 0) {
        digitalWrite(RelayPin3, HIGH); // turn on relay 3
        toggleState_3 = 1;
        Serial.println("Device3 ON");
      } else {
        digitalWrite(RelayPin3, LOW); // turn off relay 3
        toggleState_3 = 0;
        Serial.println("Device3 OFF");
      }
      delay(100);
      break;
    case 4:
      if (toggleState_4 == 0) {
        digitalWrite(RelayPin4, HIGH); // turn on relay 4
        toggleState_4 = 1;
        Serial.println("Device4 ON");
      }
      else {
        digitalWrite(RelayPin4, LOW); // turn off relay 4
        toggleState_4 = 0;
        Serial.println("Device4 OFF");
      }
      delay(100);
      break;
    default : break;
  }
}

void manual_control() {
  //Manual Switch Control
  if (digitalRead(SwitchPin1) == LOW) {
    delay(200);
    relayOnOff(1);
  }
  else if (digitalRead(SwitchPin2) == LOW) {
    delay(200);
    relayOnOff(2);
  }
  else if (digitalRead(SwitchPin3) == LOW) {
    delay(200);
    relayOnOff(3);
  }
  else if (digitalRead(SwitchPin4) == LOW) {
    delay(200);
    relayOnOff(4);
  }
}

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);

  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();

  pinMode(RelayPin1, OUTPUT);
  pinMode(RelayPin2, OUTPUT);
  pinMode(RelayPin3, OUTPUT);
  pinMode(RelayPin4, OUTPUT);

  pinMode(wifiLed, OUTPUT);

  pinMode(SwitchPin1, INPUT_PULLUP);
  pinMode(SwitchPin2, INPUT_PULLUP);
  pinMode(SwitchPin3, INPUT_PULLUP);
  pinMode(SwitchPin4, INPUT_PULLUP);

  //During Starting all Relays should TURN OFF
  digitalWrite(RelayPin1, HIGH);
  digitalWrite(RelayPin2, HIGH);
  digitalWrite(RelayPin3, HIGH);
  digitalWrite(RelayPin4, HIGH);

  digitalWrite(wifiLed, HIGH);  //Turn OFF WiFi LED
}

void loop() {
  ArduinoCloud.update();

  manual_control(); //Control relays manually

  if (WiFi.status() != WL_CONNECTED)
  {
    digitalWrite(wifiLed, HIGH); //Turn OFF WiFi LED
  }
  else{
    digitalWrite(wifiLed, LOW); //Turn ON WiFi LED
  }
}

void onSwitch1Change() {
  if (switch1 == 1)
  {
    digitalWrite(RelayPin1, HIGH);
    Serial.println("Device1 ON");
    toggleState_1 = 1;
  }
  else
  {
    digitalWrite(RelayPin1, LOW);
    Serial.println("Device1 OFF");
    toggleState_1 = 0;
  }
}

void onSwitch2Change() {
  if (switch2 == 1)
  {
    digitalWrite(RelayPin2, HIGH);
    Serial.println("Device2 ON");
    toggleState_2 = 1;
  }
  else
  {
    digitalWrite(RelayPin2, LOW);
    Serial.println("Device2 OFF");
    toggleState_2 = 0;
  }
}

void onSwitch3Change() {
  if (switch3 == 1)
  {
    digitalWrite(RelayPin3, HIGH);
    Serial.println("Device2 ON");
    toggleState_3 = 1;
  }
  else
  {
    digitalWrite(RelayPin3, LOW);
    Serial.println("Device3 OFF");
    toggleState_3 = 0;
  }
}

void onSwitch4Change() {
  if (switch4 == 1)
  {
    digitalWrite(RelayPin4, HIGH);
    Serial.println("Device4 ON");
    toggleState_4 = 1;
  }
  else
  {
    digitalWrite(RelayPin4, LOW);
    Serial.println("Device4 OFF");
    toggleState_4 = 0;
  }
}

i have included the arduino_secrets and thingproperties in my both pieces of code the difference is that i wanted 8 relay pins to be configured instead of 4 pins
please ask if any thing is needed from me
this was the exact error
C:\Users\akki kisu\Documents\Arduino\libraries\ArduinoIoTCloud\src\property\Property.cpp:25:19: note: '#pragma message: No RTC available on this architecture - ArduinoIoTCloud will not keep track of local change timestamps .'
   25 |   #pragma message "No RTC available on this architecture - ArduinoIoTCloud will not keep track of local change timestamps ."
      |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x1c): undefined reference to `_Z15onSwitch1Changev'
c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x34): undefined reference to `_Z15onSwitch2Changev'
c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x40): undefined reference to `_Z15onSwitch3Changev'
c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x4c): undefined reference to `_Z15onSwitch4Changev'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

And... what is the "error" you got?

you can reduce the code by almost 90% if you use arrays to hold pin numbers and pin state ... if (toggleState[relay] == 0) { digitalWrite(RelayPin[relay], HIGH);

"Hey please help me with this error. Though I won't tell you what error it is." We are not magical. Please provide the full error output including the line where the error happened

did you remove the variables in the thing definition on Arduino IoT cloud? or you get error "Undefined reference to onSwitch1Change"?

What is the difference between your modified code and the original code? Look at it, and you are at least one step nearer to the reason.

i got an error that error compiling for nodemcu board and for no particular line

you get linker error "Undefined reference to onSwitch1Change"?

In Arduino IoT cloud the variables synced between the Cloud and the sketch are defined in the definition of the (IoT) thing. The variables are reflected into the thingProperties.h file which is maintained by the Cloud editor. The on<variable_name> functions in the sketch handle the synchronization of these variables. They are declared in the thingProperties.h
You removed the onSwitchChange functions, but you didn't remove the switchChange variables in the definition of the Thing. The thingProperties.h still contains declarations of onSwitchChange functions, but the linker can't find the definition of the function because you removed it from the sketch.
The errors are like this one:
undefined reference to `_Z15onSwitch1Changev'

To solve this, remove the switchChange variables from the thing in the Cloud UI.


text:
Adding L293D motor shield to Breadboard
Anyone knows how to attach the l293D motor driver shield on a breadboard?
I need to put the shield on top of a breadboard and then use an Atmega328P as the main way of controlling it.
Than you :)

If the shield doesn't fit on the breadboard you need to use female to male jumper cables to connect it.

why do you want to do this? ... plug the shield onto the arduino instead

you can't put uno shield on breadboard

Acknowledging that it is not exactly the answer to your question, the folks at Adafruit have written an excellent tutorial on breadboarding the raw L293D chip. Which may be a more compact option for you?
Your question asks how to attach an L293D shield to a breadboard, and as @Juraj said in the comments, you can't do this easily directly. As @Jsotola mentioned, a UNO format shield is designed to connect directly to a uno, not to breadboard.
On a UNO format shield the pin alignment on the 18 pin (10+8) header sider of the shield (the digital pins) is not a comfortable fit into breadboard hole spacing (the shorter 14 pin side does align OK with breadboard). To make matters worse a UNO shield is wider than the available rows on a single standard breadboard. However, if you're willing to use more force and bend a few pins on the shield (not recommended) you can make this work using two breadboards side by side. The photo shows one possibility.

A better solution as mentioned by @ChrisL in the comments might be to use dupont connectors to connect the shield pins as needed (e.g. to a non-UNO format arduino).

There are different versions and clones of the L293D shield in circulation. I think most of these are based on the (now obsolete) Adafruit open source version 1. In any case you'll need to refer to the datasheet for the version you're using and be sure to connect every pin required from the shield to the arduino using the dupont connectors.
There are plenty of tutorials available regarding using the L293D shield, one example is at Last Minute Engineers


text:
ESP8266 How to run MQTT Client and Http Client in one loop
Scenario: Existing project: read soft serial then do http post
New project: MQTT player from other (MrDIY / MrDIY Audio Notifier · GitLab)
Objective: Combine together (Result: successful )
Issue: When read serial do http post, after http.end(). MQTT client disconnect.
It taks above 10 secs to reconnect.
The only way I found is just a workaround to add ESP.restart(); after each http post.
But that's stupid. I have spend more than 10 hours to fix this issue.
Any one can help?
Eg code:
void loop() {
  if (!mqttClient.connected()) {
    mqttReconnect();
  }
  mqttClient.loop();

  if (mySerial.available() > 0)  //Checks is there any data in buffer
  {
    receive_data = String(receive_data) + String(char(mySerial.read()));
    //Serial.println(receive_data);

    if (String(receive_data).indexOf("lighton") >= 0) {
      Serial.println("lighton");
      receive_data = "";
      http.begin(client, switchon);
      http.addHeader("Content-Type", "application/json");
      http.addHeader("Authorization", auth);
      int httpCode = http.POST("{\"entity_id\": \"switch.sonoff_guest_room\"}");
      Serial.printf("[http] GET... code: %d\n", httpCode);
      http.end();
      //ESP.restart();
    }
}

Please add URL to things you refers to!

Did you ever figure this out? I'm struggling with the same problem myself now, I also can only make one initial http request, all subsequent requests fails with status -5...


text:
Rfid checking continuously for cards
Well I am making a automatic car parking system where a any one parking their car will get a card as a token and have to return it before leaving with their cars one card for a slot
And if they don't do so the buzzer will go high
There is also a ultrasonic for each slot to check if the car is present or not.
So far I have managed to do all the part except to check or store a value when the card is removed for that I have been searching for a way to make my rfid reader to check for a tag continuously but all I get so far is my reader only respond when there is a card is present.
I am doing my project any way excluding this part but I would love to add it as it will help to increase the security level.

Can you please share your code? Also which RFID module are you using

this is a Q&A site ... not a chat forum ... please ask a specific, answerable question about Arduino

Do you mean that the RFID reader only reports a tag once when it comes near it and not continously while its near the reader?


text:
ESP8266 module ESP-12F does not connect to esptool.py
I have bought some blank ESP-12F modules like this: https://www.aliexpress.com/item/1005001520382593.html
For these modules I have made my own adapter PCB to connect them, but now I don't get any connection with the esptool.py to these modules.
The connection is:
TX --------------- RX with an PL2303 USB adapter
RX --------------- TX with an PL2303 USB adapter
EN --------------- 3.3V
GPIO-0 ----------- GND over button
GPIO-15 ---------- GND over 4K7 resistor
RESET ------------ GND over button
GND -------------- GND
VCC -------------- 3.3V from AMS1117-3.3 blocked with Elko 220µF

With a serial terminal I can cleary see with 74880 baud the response for standard boot on TXD (GPIO1):
 ets Jan  8 2013,rst cause:2, boot mode:(7,7)

waiting for host

and on TXD1 (GPIO2)
 ets Jan  8 2013,rst cause:2, boot mode:(7,6)

waiting for host

For flash mode with RESET and GPIO-0 on TXD (GPIO1):
 ets Jan  8 2013,rst cause:2, boot mode:(5,7)

waiting for host

and on TXD1 (GPIO2)
 ets Jan  8 2013,rst cause:2, boot mode:(5,6)

waiting for host

I tried to connect with:
python3 esptool.py --port /dev/ttyUSB0 flash_id
or
python3 esptool.py --chip esp8266 --port /dev/ttyUSB0 flash_id
or
python3 esptool.py --no-stub --port /dev/ttyUSB0 flash_id
but no connection can be established.
"A fatal error occurred: Failed to connect to Espressif device: No serial data received."
With the trace option I get:
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
TRACE +0.082 Read 1 bytes: 72
TRACE +0.000 Read invalid data: 72
TRACE +0.000 Remaining data in serial buffer: 6c00

I tried the connection with this two versions:
esptool.py v3.3-dev
esptool.py v2.0-beta2
I assume this is simply bad hardware.
Is there anybody who has mastered this problem?

Have you pulled up reset pin?
Check this blog https://circuits4you.com/2016/12/14/reset-programming-esp8266/

The reset pin has an pullup of 4K7

I adressed this problem now to esptool.py https://github.com/espressif/esptool/issues/694

You have io 15 HIGH. Check the pull-down.
The first number in () on first line of the boot log is the state of the boot config pins. First bit is the state of io 2, second the state of io 0 and third is the state of io 15.
You have 5 or 7 which is 101 or 111 in binary. So you have io 15 HIGH.
io 15 HIGH is a mode where the esp8266 doesn't have its own flash memory but boots from the host MCU so you get "waiting for host".
io 15 must be LOW for the esp8266 to use the flash memory.
So you should see for normal mode
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

and for flashing mode
ets Jan  8 2013,rst cause:2, boot mode:(1,6)

Note: it can be (3,7) and (1,7) too

We are talking about GPIO15 that is the next pin (10) after GND in the corner?
This pin is definitely on GND potential - i can measure always about 0,005 V.

Your analyze is correct, although i could not believe it first, because i could measure 5mV at the pin outside, that should be correct.
After a little bit thinking i did check the solder joint to the module and it was cold with a bad contact!
So i resoldered it and now it is running - thank you very much!
Where can i find an explanation of the other numbers?

there is no good documentation. so for me it is a mix of experience and information peaces from different sources which have wrong info mixed with right info. like this one: https://github.com/espressif/esptool/blob/master/docs/en/advanced-topics/boot-mode-selection.rst  it mixes info about esp8266 and esp32

Thanks - it seems not so easy to get all the 'secrets' from chinese products. :-)


text:
Arduino UNO and PCA9685 - Problem with external power supply
I am totally desperate and hope you can help me.
I've been building a project for a while where I have to control several servos. For this I bought some MG996R servos and a  PCA9685 16-Channel Servo
Driver board. Furthermore, I bought a suitable power supply (DV 5V - max 3A).
First, I connected my controller and the board as follows and attached the power supply at the intended place:

Everything worked as desired and I could control e.g. one servo with this example script.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver myServos = Adafruit_PWMServoDriver();

#define SERVOMIN  150
#define SERVOMAX  600

uint8_t servonum = 0;
uint8_t numberOfServos =  1;

void setup() {
  myServos.begin();
  myServos.setPWMFreq(60);
  delay(10);
}

void loop() {
  myServos.setPWM(0, 0, 500);
  delay(1000);
  myServos.setPWM(0, 0, 300);
  delay(1000);
}

Then I tried something and reconnected a few cables while the power supply was still on (my bad) - after that no servo moved with the original setup (see picture above). After that I tried to find the broken part but couldn't find any - so I bought a new Arduino, PCA board and power supply to try and find the error - unfortunately without success.
Then I found out by chance that the servos move again when I connect the ground of the external power supply to the Arduino and plug the positive pole of the power supply to the V+ with the PCA9685. That is,

I ordered a  pack of three new PCA9685s and again same problem - the servos no longer move when using the designated place for the power supply on the PCA9685 board - what is going on? Can anyone explain this and help me where the problem is?

measure voltage at arduino

what are your thoughts? what voltage should I measure?

power for arduino as you run motors, in each the working and failing configurations.  there are only 4 or 5 leads, at least one of which is ground so you could just measure everything one at a time and see the difference.


text:
PID control doesn't work. After computing the values, the values just become equal to 0
So, I have a working code of the stabilizer project using 2 servo motors, mpu6050, Arduino Uno. However, I want to add PID part for tuning the servo motors movement. I followed the example PID library and just changed the input as data received from the mpu6050 sensor, and output as the data that we send to servo motor. The problem is after adding the PID part project stopped working properly. Servo motors did not react to the accelerometer movement anymore. I tried printing out the values computed by the PID and all of them turned out to be 0 and they don't change even if I rotate the sensor. Can anyone spot the mistake in the code with PID part? I am pretty sure that the rest works perfectly.
/*
                        DIY Gimbal - MPU6050 Arduino Tutorial
                        by Dejan, www.HowToMechatronics.com
                        Code based on the MPU6050_DMP6 example from the i2cdevlib library by Jeff Rowberg:
                        https://github.com/jrowberg/i2cdevlib
*/
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file
#include "PID_v1.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
#include <Servo.h>
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

double Setpointx, Setpointy, Inputx, Inputy, Outputx, Outputy, pidX, pidY;
double Kp = 2, Ki = 5, Kd = 1;
PID myPID0 (&Inputx, &Outputx, &Setpointx, Kp, Ki, Kd, DIRECT) ;
PID myPID1 (&Inputy, &Outputy, &Setpointy, Kp, Ki, Kd, DIRECT) ;
// Define the 3 servo motors
Servo servo0;
Servo servo1;
Servo servo2;
float correct;
int j = 0;

#define OUTPUT_READABLE_YAWPITCHROLL

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
  mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Setpointx = 10;
  Setpointy = 10;

  myPID0. SetMode (AUTOMATIC);
  myPID1. SetMode (AUTOMATIC);

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize serial communication
  // (115200 chosen because it is required for Teapot Demo output, but it's
  // really up to you depending on your project)
  Serial.begin(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // initialize device
  //Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(17);
  mpu.setYGyroOffset(-69);
  mpu.setZGyroOffset(27);
  mpu.setZAccelOffset(1551); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    // Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    //Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    // Serial.print(F("DMP Initialization failed (code "));
    //Serial.print(devStatus);
    //Serial.println(F(")"));
  }

  // Define the pins to which the 3 servo motors are connected
  servo0.attach(10); //Z Axis
  servo1.attach(9); //Y Axis
  servo2.attach(8); //X Axis
  servo1.write(90);
  servo2.write(90);
}
// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
    if (mpuInterrupt && fifoCount < packetSize) {
      // try to get out of the infinite loop
      fifoCount = mpu.getFIFOCount();
    }
  }

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    fifoCount = mpu.getFIFOCount();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

    // Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    // Yaw, Pitch, Roll values - Radians to degrees
    Inputx = ypr[2];
    myPID0.Compute();
    Outputx = pidX;
    Inputy = ypr[1];
    myPID1.Compute();
    Outputy = pidY;
    Serial.print("\nX: ");
    Serial.print(pidX);
    Serial.print("\nY: ");
    Serial.print(pidY);
    ypr[0] = ypr[0] * 180 / M_PI;
    pidX = pidX * 180 / M_PI;
    pidY = pidY * 180 / M_PI;
    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(pidY, -90, 90, 0, 180);
      int servo2Value = map(pidX, -90, 90, 180, 0);
      // Control the servos according to the MPU6050 orientation
      servo0.write(90);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif
  }
}

Why are you doing Outputx = pidX;? Outputx is the output variable of the PID object. You are not supposed to write to it. You need to read it and then use it as a servo angle. And you should only compute the PID when you are actually using the value. You don't need it for the callibration cycle

@chrisl How should I use the outputx then after it is being computed by myPID.compute()? I mean I have to make the values that I send to the servo in degrees and map them from 0 to 180. I doubt that if I put outputx directly to servo2.write(outputx) it would be in degrees instead of radians and with no mapping. And the last question where the pid output should be computed then? Isn't it supposed to be computed inside the void loop()?

Your code is not using Outputx after it is being computed by myPID0.Compute();, you are immediately overwriting what is computed with the following Outputx = pidX; line.  Per https://playground.arduino.cc/Code/PIDLibrarySetOutputLimits/ use myPID0.SetOutputLimits(0,180); & servo1.write(Outputx), etc.  and drop the rest of the conversion and mapping stuff.   The Kp, Ki, and Kd constants all convert units of setpoint-input error into units of controlled output.  (Or at least change Outputx = pidX;intopidX = Outputx;)

pidX and pidY are initialized to zeros in the declaration, and then are only updated by the pidX = pidX * 180 / M_PI;     pidY = pidY * 180 / M_PI; which resets them to zero.  You need to change the Outputx = pidX; into pidX = Outputx;, and also for Y.

You seem to have some misconceptions about PID. For explaining I will use a different use case of a PID control, which is easier to understand (and also mentioned in the documentation of the PID library):
A PID control can be used in any feedback loop system with consistent feedback. When you drive your car you want it to reach a specific speed. For that you press the gas pedal, changing its angle until you reach the target speed. In this scenario you are doing the PID control. The setpoint is the target speed, the input is the actual current speed and the output is the angle of the gas pedal.
You see: Output and input/setpoint don't have the same unit. They are completely different measurements of different things. They are only connected via the feedback loop in the system, meaning that increasing the gas pedal angle will increase the speed of the car. The PID control is then just a formula which involves the actual speed, the desired speed and some scaling variables (Kp, Ki, Kd)(to tune the behavior of the control). And the output of the formula is then the needed gas pedal angle at that time.
So what does this mean for you?

You don't need to convert the output value into an angle. The unit of the output is not important, since the PID will control itself to get to the setpoint. It is more important to tune the PID through Kp, Ki and Kd to get the PID to behave correctly in your system.

The workflow looks like this:

Set the setpoint variable Setpointx to the wanted input value.
Read the input from the MPU and save it to Inputx
Call myPID0.Compute(); to compute the output from setpoint and input.
Read the value from Outputx and write it to your servo. The servo movement will then cause a change in the read input in the next loop.
repeat from step 2

As I currently don't really understand your feedback loop system: Make sure, that the feedback loop is working correctly. An increase in the output should lead to an increase in the input. Make sure it is consistent. Your input value should not have too much noise (or the PID will react to that noise). For testing you might want to tune Kp, Ki and Kd down so that the PID works slower. Then you can see the behavior better. Make sure, that both PID controls aren't influencing each other. They need to be independent.

Use myPID0.Compute(); every time you write a new value to your servo and only then. Calling it in between will be just a waste. So it makes sense to use that line somewhere directly before writing to the servo.

If it still not works, then you should have a detailed look at the read values and how they relate to the servo angle. Are the requirements above met? Are they stable enough. Is the feedback loop as expected? What does changing Kp, Kd and Ki change in the outcome?

The PID input and output don't have to be in matching units, but they could be. The Servo.write() input range is 0 to 180 for minimum to maximum, and is intended to map to degrees https://www.arduino.cc/reference/en/libraries/servo/write/  -- Internally Servo.write() maps the 0-180 back to microseconds: https://github.com/arduino-libraries/Servo/blob/master/src/avr/Servo.cpp#L264  In this case, input and setpoint need to be in the same units, but output could be in degrees constrained to 0-180 or 1000-2000 microseconds. kP converts input units of error to output units.

This chunk of code is feeding radians into the PID algorithm, and then discarding/overwriting the output with the initialized-to-zero pidX and pidY values.
...
Inputx = ypr[2];
myPID0.Compute();
Outputx = pidX;
Inputy = ypr[1];
myPID1.Compute();
Outputy = pidY;
...

I'd set the output limits to match the device under control:
void setup() {
   // join I2C bus (I2Cdev library doesn't do this automatically)
   Setpointx = 10;  // MPU degrees
   Setpointy = 10;  // MPU degrees

   myPID0. SetMode (AUTOMATIC);
   myPID1. SetMode (AUTOMATIC);
   myPID0.SetOutputLimits(0,180); // servo degrees
   myPID1.SetOutputLimits(0,180); // servo degrees
   ...

...and then convert the inputs to match the setpoints, and feed the constrained PID outputs directly to the controls:
Inputx = ypr[2]*180.0/M_PI;
myPID0.Compute();
pid_X = Outputx;
Inputy = ypr[1]*180/M_PI;
myPID1.Compute();
pidY = Outputy;
...
servo1.write(Outputx);
servo2.write(Outputy);
...

It is important to use the PID.SetOutputLimits(min,max) so that the PID routine can internally ensure that the outputs don't wander deep into infeasible control regimes.  If you don't call SetOutputLimits(), the default output constraints are 0-255, which would not make sense for a 0-180 servo.
One way to think of your PID constants Kp = 2, Ki = 5, Kd = 1; is how big an output unit change (degrees of servo setting) you want to make for a unit of input (MPU radians or degrees?) error, integrated error (error*seconds/5 per https://playground.arduino.cc/Code/PIDLibrarySetSampleTime/), or delta error.  They might need adjusting if the system isn't responding as you like.


text:
CapacitiveSensor Library example works with great with UNO but not with Nano Every?
The CapacitiveSense library is the key to my project. A custom art touch lamp.
Arduino CapacitiveSensor Library
It works great with the Arduino UNO but the Nano Every has vastly different performance and issues with exactly the same code and HW. The Arduino is just too large for my project so I had high hopes that the Nano E would be a compatible fit.
My HW setup is per the example. Using a high value Resistor between pins 7 and 8 for Send and Receive(sensor). Works for the Uno but the Nano E just outputs a -2. Even though I tried resistor values 56K to 2M!. Realize the error -2 can mean a missing resistor. So I then tried the Threshold 3 way switch example code which suggests that just using pin 8 as an antenna is possible. I have a small steel plate (3"x4") connected directly to pin 8. Again Arduino Works great. By that I mean that I can adjust the parameters labeled in the code as a, b and c to get a repeatable trigger output to the serial monitor. The Nano Every with the same code though gets vastly different readings for cs and they don't stabilize. By vast , I mean Arduino returns cs numbers in range 100 to 200;s while the Nano E returns in the 33000's. Now I can make the code recognize those numbers for a trigger but subsequent touches range all over the place (1000's to 50000's) making touching the plate highly random with triggers.
I have made large tables (many hours) trying to dial the parameters in on the Nano with no success while it took me about 10 mins to dial in on the Arduino for reliable operation.
Why would the Nano Every be so different from the Uno?
The Threshold example code (bottom of page) in the library reference is perfect my setup as it is described as a used for a 3 way switch. The example code is below.
#include <CapacitiveSensor.h>
CapacitiveSensor cs_7_8 = CapacitiveSensor(7,8); //10M Resistor between pins 7 and 8, you may also connect an antenna on pin 8
unsigned long csSum;

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

void loop() {
    CSread();
}

void CSread() {
    long cs = cs_7_8.capacitiveSensor(80); //a: Sensor resolution is set to 80
    if (cs > 100) { //b: Arbitrary number
        csSum += cs;
        Serial.println(cs);
        if (csSum >= 3800) //c: This value is the threshold, a High value means it takes longer to trigger
        {
            Serial.print("Trigger: ");
            Serial.println(csSum);
            if (csSum > 0) { csSum = 0; } //Reset
            cs_7_8.reset_CS_AutoCal(); //Stops readings
        }
    } else {
        csSum = 0; //Timeout caused by bad readings
    }
}

Serial Output with Uno board with nice triggers.
parameters cs>700, csSum>=1500, samples are 10,
799
812
Trigger: 1161
I realize this is a lot of detail in this question. But I've searched this and other boards for anything on getting Capacitive Sensor to work reliably on any other board beside Uno and haven't found anything.
I'm also aware of the grounding issues talked about in relation to touch sensing. I had a previous post here about that using the Trinket M0 but abandoned that due to grounding issues with it.
I still have issues whether the Nano is connected via USB or an independent AC-DC power supply with 12vdc going to Nano.  I don't see any grounding issues with both the Arduino Uno and nano every with either USB power or independant AC-DC 12v power
Any insights appreciated.

You may have more luck with the plain Nano (not the Every), as it is built around the same MCU (ATmega328P) as the Uno.


text:
I want my LED's to turn on for 5 sec when the Ultrasonic Sensor Activated
const int Trigger = 6;
const int Echo = 7;
const int LEDpin1 = 4;
const int LEDpin2 = 5;
const int Parameter = 400;
float Time;

void setup()
{
Serial.begin(9600);
pinMode(Trigger, OUTPUT);
pinMode(Echo, INPUT);
pinMode(LEDpin1,OUTPUT);
pinMode(LEDpin2,OUTPUT);
}
void loop()
{

digitalWrite(Trigger, HIGH);
delayMicroseconds(10);
digitalWrite(Trigger, LOW);
Time = pulseIn(Echo, HIGH);
Serial.print("Distance: ");
Serial.println(Time);
delay(10);
if (Time < Parameter)
digitalWrite(LEDpin1, HIGH);
else
digitalWrite(LEDpin1, LOW);

if (Time < Parameter)
digitalWrite(LEDpin2, HIGH);
else
digitalWrite(LEDpin2, LOW);

//**When I include -delay(5000)- right here, it also delays the Ultrasonic sensor to only detect every 5 seconds**
}

The answer is using non-blocking code involving the millis() function in a pattern like the BlinkWithoutDelay example shows. There are many tutorials about that on the web. When you learn that coding principle you will be able to solve your problem

Please format code as code (you can edit your post) so it's easier to read.


text:
Arduino library or code for ESP32 to scan for Bluetooth devices?
Is there some code or library that would allow me to scan for nearby Bluetooth devices using a common ESP32 board ?
I only found similar code for actual Arduino boards.

a web search reveals some

Well.. now this question is answer #4 in a web search and 2 of the answers above are for BLE only and the other one leads to another unanswered question. It is not that easy to find good example because the Arduino-ESP32 framework added advanced Bluetooth support just recently - and its not that easy to use the receent versions.

@IanH Almost two years later, there is an actual solution to this. See gbafamily's answer below.

The ESP32 Arduino boards support package includes libraries for ESP32 Bluetooth and BLE. Both libraries have examples which you can find in Arduino IDE Examples menu.

I looked trough the examples but I didn't see one that lists nearby devices, just various example on how to pair with specific device.

https://github.com/esp32beans/ESP32-BT-exp is a Bluetooth Dual
Mode (classic and BLE) scanner. ESP32-BT-exp works on the original ESP32. No other ESP32 supports BT classic mode.

Worked as promised! How unfortunate that it is *only * ESP32, and not ESP32S2/S3 or ESP32C2/C3. (Cue rant on Espressif's naming conventions...)


text:
Should I use C or C++ for a pure code implementation of Arduino?
I have an arduino board (SAMD21 microcontroller) which supports either Arduino or CircuitPython programming. I'd like to program in pure C/C++ instead of Arduino, which seems to be possible without too much trouble. But I'm not sure whether to use C or C++. I thought Arduino was based in C++ but I went to look at some of the library files and they were written in C. Since I'm pretty sure they're not interchangeable, can someone help me learn which language I should use to program my board?

Whichever you are most comfortable in. C is a subset of C++ (or the other way around - C++ is a superset of C).

You can effectively use either c or c++ in Arduino. There's a few caveats to be aware of, but they both work. You can even inline assembly if you want.

I thought Arduino was based in C++

There is no language "Arduino" - the Arduino IDE runs a the GNU C++ compiler so "its language" is the language supported by the compiler. It is primarily C++ with a little bit of preprocessing done to your code to help learners get past some of the places they can trip over easily (adding #include statements when it thinks you need them, for instance).
Here is an answer I wrote to a similar question a few years ago. I think it's relevant to your question.


text:
servos act strangely instead of stopping/starting
I am trying to make it so that my robot rolls straight when pin 8 is high and stop when pin 8 is low, the 2 servos is constant rotation servos. instead the servos spin when the wire touches it pin even without power to the wire, and they don't stop when the wire is pulled, but sometimes they don't start and sometimes they stop.
I'm new to coding and I really need this help.

#include <Servo.h>

Servo h1;
Servo h2;

#define servoPin 13
#define servoPin 3

int angle = 0;
const int buttonPin = 8;
int buttonState = 0;
void setup() {

  h2.attach(13); //left servo
  h1.attach(3); //right servo
  pinMode(8, INPUT);
}

void loop() {

  if (digitalRead(8) == LOW)  {
  h1.write(90); //no movement
  h2.write(90);//no movement

  } else  {
    h1.write(180); //go straight
    h2.write(0); //go straight
  }
}

What happens if you change INPUT to INPUT_PULLUP?

reduce your code to repeatedly print the state of pin 8 ... what do you observe?

As VE7JRO suggested, this really sounds like a floating pin. I guess you have a button on that pin, which connects the pin to ground when pressed, but you don't have an external pullup resistor. Using pinMode(pin, INPUT_PULLUP) will activate the internal pullup resistor for that pin.

Are you aware that there are at least two very different types of servos? Are you sure that the library you use matches the type of servo you attached?


text:
Possible way to interface a TFT touch panel with Arduino
I have a salvaged 40-pin TFT touch panel, and I am trying to see if I can control it with an Arduino. What are my chances of getting a driver for it ? I bought a RA8875 Driver Board from Adafruit, but the pin layout did not match.
Any suggestions are appreciated. Thank you

You could see under the cover of the PCB and try to identify the part number of the controller. If its a standard one you might be able to find information about it. Though if this was from consumer hardware this is  not very likely. These parts often have custom chips or the labels on the chips is removed. And with an Uno you won't have much luck driving this. I guess the connections on the ribbon cable are all needed to drive it. The Uno most likely doesn't have enough pins for that.

I don't think the panel has a driver, that is the reason why I am looking for one.

Then I would ask what is on that PCB? But the result is the same. You need to find out what function each pin has. For that you can only look at the PCB. Reverse engineering is a very complex task. We cannot really help with that.


text:
how to put whitespace in long Serial println() input
I have this long, Serial.println() that is in quotes, on multiple lines.
Arduino IDE warns: "Missing terminating character".
I am certain there is a way to break the lines up, while having the entire text enclosed in quotes, but I don't remember how.
Serial.println("
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
<svg
   xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
    xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"
   id=\"svg8\" version=\"1.1\" viewBox=\"0 0 227.35277 156.29323\"
   height=\"6.1532764in\"
   width=\"8.9508963in\"
   sodipodi:docname=\"etchasketchborder.svg\">
    <defs
     id=\"defs2\" />
  <path
     style=\"fill:#ff0000;stroke:#ff0000;stroke-width:1.32300019;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
     d=\"m 12.000819,0.66145838 c -6.2819637,0 -11.33936062,5.05739692 -11.33936062,11.33936062 V 144.29249 c 0,6.28197 5.05739692,11.33936 11.33936062,11.33936 H 215.35224 c 6.28197,0 11.33885,-5.05739 11.33885,-11.33936 V 12.000819 c 0,-6.2819637 -5.05688,-11.33936062 -11.33885,-11.33936062 z M 18.932696,12.696383 H 205.5854 c 5.02557,0 9.07128,4.04571 9.07128,9.071282 v 77.03923 c 0,5.025575 -4.04571,9.071285 -9.07128,9.071285 H 18.932696 c -5.025572,0 -9.0712819,-4.04571 -9.0712819,-9.071285 v -77.03923 c 0,-5.025572 4.0457099,-9.071282 9.0712819,-9.071282 z\"
    />
  <ellipse
     style=\"fill:#ffffff;fill-opacity:1;stroke:#ff0000;stroke-width:1.32300007;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
     cx=\"21.16666\"
     cy=\"130.59085\"
     rx=\"10.583334\"
     ry=\"9.0714283\" />
  <ellipse
     style=\"fill:#ffffff;fill-opacity:1;stroke:#ff0000;stroke-width:1.32300007;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
     cx=\"200.62982\"
     cy=\"131.57361\"
     rx=\"10.583334\"
     ry=\"9.0714283\" />
      </svg>
");

https://stackoverflow.com/questions/1135841/c-multiline-string-literal

Ah, I figured it out.
you cant do this:
Serial.println("foo
                                bar");

but you can do this:
Serial.println("Foo"
                "Bar");

So then in bash I write a little command, to take my svg files, and escape the quotes that exist in the file, then another line to add quotes at the start and end of every newline. then I can just copy paste my svg images into the println() function.
$ sed -i 's/"/\\"/g' input.svg

and
$ xargs -I{lin} echo \"{lin}\" <input.svg

respectively.

Note that "foo" "bar" (on separate lines) results in "foobar" not "foo\nbar" as the layout would suggest.

sure, I was just looking to break it up visually. I think the svg doesnt care about newlines, and if it does, ill just add a \n into my bash script.

SVG doesn't care (It's just XML after all) - but just something to keep at the back of your mind in case you use the same trick for something that does care (or for other users that read this answer and don't realise that little caveat).


text:
How to use an Arduino to play audio from an Adafruit Soundboard using audio file name
I'm trying to control an adafruit soundboard with my elegoo uno R3. I'm a beginner programer and I'm trying to get the soundboard to play a sound file by name when I press a button. I have confirmed the soundboard works because it works when I run the menu program that I got from the tutorial I followed, but when I try to simplify that and transfer it to my own code something goes wrong. Here is my code:
#include <Adafruit_Soundboard.h>
#include <SoftwareSerial.h>

#define SFX_TX 10
#define SFX_RX 11
#define SFX_RST 12

int pin_a = 8;
int pin_b = 7;
int pin_c = 4;
long randNumber;
long randNumberCheck;
const int buttonPin = 2;

int buttonState = 0;
int lightLoopCount = 0;

#define NUM_SOUNDS 2
char *soundName[NUM_SOUNDS] = {
  "T00     OGG",
  "T00     OGG",
};

SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);
Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);

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

  if (!sfx.reset()) {
    Serial.println("Not found");
    while (1);
  }

  pinMode(pin_a, OUTPUT);
  pinMode(pin_b, OUTPUT);
  pinMode(pin_c, OUTPUT);

  pinMode(buttonPin, INPUT);

  randomSeed(analogRead(0));
}

void loop() {
  analogWrite(pin_a, 0);
  analogWrite(pin_b, 0);
  analogWrite(pin_c, 0);

  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH) {

    sfx.playTrack(soundName[1]);

    if (!sfx.playTrack(soundName[1])) {
      Serial.print("Failed to play");
    }

    lightLoopCount = 0;
    while (lightLoopCount < 10) {
      analogWrite(pin_a, 0);
      analogWrite(pin_b, 0);
      analogWrite(pin_c, 0);

      // print a random number from 0 to 299
      randNumber = random(3);
      while (randNumber == randNumberCheck) {
        randNumber = random(3);
      }

      if (randNumber == 0) {
        analogWrite(pin_a, 255);
      }
      else if (randNumber == 1) {
        analogWrite(pin_b, 255);
      }
      else {
        analogWrite(pin_c, 255);
      }

      randNumberCheck = randNumber;

      delay(300);
      lightLoopCount++;
    }
  }
}

Here is the datasheet for the soundboard: https://www.digikey.com/htmldatasheets/production/1800160/0/0/1/audio-fx-sound-board.html
I've tried several different ways to get the board to just play a sound by filename when I press the button. Everything else works when I press the button, I think I'm just having trouble converting the string into a char array that the board can understand. It's saying "Failed to play" when I press the button. Can someone help me convert the string properly?

please add a link for the soundboard datasheet to your post ... do not add to a comment

add debugging code to your sketch ... print out the song filename ... also print the length of the filename  just to make sure of any hidden characters


text:
Arduino Uno stops accepting command from PS3 Wireless controller?? although it remains connected!
so I was trying to control a bot wirelessly with the help of ps3 controller and USB host shield, i am using Arduino UNO as micro-controller. I was able to connect PS3 controller with Arduino and checked all button presses. It works very smoothly for button presses and shows on serial monitor which button was pressed without any lag. But the issue I am facing is that when I try to call any function on button press, the entire function is getting executed and execution comes back to void loop but Arduino stops accepting commands from ps3. But it shows that PS3 is still connected and the connection isn't lost. I went through different blogs and I found out that some say that issue is with new HOST SHIELD library 2.0 and some say that UNO computation takes time.
this is what I have tried.
#define motopinl1 8
#define motopinr1 9
# define motopine1 10

#define motopinl2 11
#define motopinr2 12
#define motopine2 13

#define val 200

void setup() {
Serial.begin(115200);
#if !defined(__MIPSEL__)
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nPS3 Bluetooth Library Started"));
}

void moveforward()
{

// digitalWrite(motopinl1,LOW);
digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
// digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinl1,HIGH);
//digitalWrite(motopinr2,HIGH);

Serial.println("MoveForward called");
Usb.Task();

}

void moveBackward()
{

digitalWrite(motopinl1,LOW);
//  digitalWrite(motopinr1,LOW);
// digitalWrite(motopinl2,LOW);
digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinr1,HIGH);
//digitalWrite(motopinl2,HIGH);

Serial.println("Movebackward called");
Usb.Task();
}

void moveleft()
{

digitalWrite(motopinl1,LOW);
// digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
// digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinr2,HIGH);
//digitalWrite(motopinr1,HIGH);

Usb.Task();
Serial.println("Moveleft called");
}

void moveright()
{

// digitalWrite(motopinl1,LOW);
//digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinl1,HIGH);
//digitalWrite(motopinl2,HIGH);

Serial.println("Moveright called");
Usb.Task();
}

void stopit()
{
digitalWrite(motopinl1,LOW);
digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
digitalWrite(motopinr2,LOW);
analogWrite(motopine1,0);
analogWrite(motopine2,0);
Usb.Task();
}

void loop() {
Usb.Task();

if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
  if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
   // Serial.print(F("\r\nLeftHatX: "));
    //Serial.print(PS3.getAnalogHat(LeftHatX));
    //Serial.print(F("\tLeftHatY: "));
    //Serial.print(PS3.getAnalogHat(LeftHatY));
    if (PS3.PS3Connected) { // The Navigation controller only have one joystick
      //Serial.print(F("\tRightHatX: "));
      //Serial.print(PS3.getAnalogHat(RightHatX));
      //Serial.print(F("\tRightHatY: "));
      //Serial.print(PS3.getAnalogHat(RightHatY));
    }
  }

  // Analog button values can be read from almost all buttons
  if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
    Serial.print(F("\r\nL2: "));
    Serial.print(PS3.getAnalogButton(L2));
    if (PS3.PS3Connected) {
      Serial.print(F("\tR2: "));
      Serial.print(PS3.getAnalogButton(R2));
    }
  }

  if (PS3.getButtonClick(PS)) {
    Serial.print(F("\r\nPS"));
    PS3.disconnect();
  }
  else {
    if (PS3.getButtonClick(TRIANGLE)) {
      Serial.print(F("\r\nTriangle"));
      moveforward();
      PS3.setRumbleOn(RumbleLow);
    }
    if (PS3.getButtonClick(CIRCLE)) {
      Serial.print(F("\r\nCircle"));
      PS3.setRumbleOn(RumbleHigh);
      moveright();
    }
    if (PS3.getButtonClick(CROSS))
    {
        Serial.print(F("\r\nCross"));
        moveBackward();
    }
    if (PS3.getButtonClick(SQUARE))
    {
      Serial.print(F("\r\nSquare"));
      moveleft();
    }

    if (PS3.getButtonClick(UP)) {
      Serial.print(F("\r\nUp"));
      stopit();
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED4);
      }
    }
    if (PS3.getButtonClick(RIGHT)) {
      Serial.print(F("\r\nRight"));
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED1);
      }
    }
    if (PS3.getButtonClick(DOWN)) {
      Serial.print(F("\r\nDown"));
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED2);
      }
    }
    if (PS3.getButtonClick(LEFT)) {
      Serial.print(F("\r\nLeft"));
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED3);
      }
    }

    if (PS3.getButtonClick(L1))
      Serial.print(F("\r\nL1"));
    if (PS3.getButtonClick(L3))
      Serial.print(F("\r\nL3"));
    if (PS3.getButtonClick(R1))
      Serial.print(F("\r\nR1"));
    if (PS3.getButtonClick(R3))
      Serial.print(F("\r\nR3"));

    if (PS3.getButtonClick(SELECT)) {
      Serial.print(F("\r\nSelect - "));
      PS3.printStatusString();
    }
    if (PS3.getButtonClick(START)) {
      Serial.print(F("\r\nStart"));
      printAngle = !printAngle;
    }
  }
#if 0 // Set this to 1 in order to see the angle of the controller
  if (printAngle) {
    Serial.print(F("\r\nPitch: "));
    Serial.print(PS3.getAngle(Pitch));
    Serial.print(F("\tRoll: "));
    Serial.print(PS3.getAngle(Roll));
  }
#endif
}
#if 0 // Set this to 1 in order to enable support for the Playstation Move controller
else if (PS3.PS3MoveConnected) {
  if (PS3.getAnalogButton(T)) {
    Serial.print(F("\r\nT: "));
    Serial.print(PS3.getAnalogButton(T));
  }
  if (PS3.getButtonClick(PS)) {
    Serial.print(F("\r\nPS"));
    PS3.disconnect();
  }
  else {
    if (PS3.getButtonClick(SELECT)) {
      Serial.print(F("\r\nSelect"));
      printTemperature = !printTemperature;
    }
    if (PS3.getButtonClick(START)) {
      Serial.print(F("\r\nStart"));
      printAngle = !printAngle;
    }
    if (PS3.getButtonClick(TRIANGLE)) {
      Serial.print(F("\r\nTriangle"));
      PS3.moveSetBulb(Red);
    }
    if (PS3.getButtonClick(CIRCLE)) {
      Serial.print(F("\r\nCircle"));
      PS3.moveSetBulb(Green);
    }
    if (PS3.getButtonClick(SQUARE)) {
      Serial.print(F("\r\nSquare"));
      PS3.moveSetBulb(Blue);
    }
    if (PS3.getButtonClick(CROSS)) {
      Serial.print(F("\r\nCross"));
      PS3.moveSetBulb(Yellow);
    }
    if (PS3.getButtonClick(MOVE)) {
      PS3.moveSetBulb(Off);
      Serial.print(F("\r\nMove"));
      Serial.print(F(" - "));
      PS3.printStatusString();
    }
  }
  if (printAngle) {
    Serial.print(F("\r\nPitch: "));
    Serial.print(PS3.getAngle(Pitch));
    Serial.print(F("\tRoll: "));
    Serial.print(PS3.getAngle(Roll));
  }
  else if (printTemperature) {
    Serial.print(F("\r\nTemperature: "));
    Serial.print(PS3.getTemperature());
  }
}
#endif
}```

I haven't connected to bot. I was checking whether function are being executed on button press or not or serial monitor. so there cannot be issue of power supply. problem is PS3 still remains connected, also line of execution returns to void loop, then why it stops further commands. please please do suggest any ideas and methods by which I can solve this problem. thank you.

I found that when you use delay inbuilt function, it completely blocks Arduino from accepting any command, that causes some communication barrier. Although ps3 remains connected, it doesn't accept commands. so all you have to do is to remove all delays from your function and build logic based Millis.


text:
Problem when using Servo.h and WIre.h libraries
I have a project that consists of an Arduino, a NodeMCU and 2 servos. The NodeMCU is configured as master and the Arduino as slave. I have bidirectional flow of data between them.
In order to receive data from Arduino I use the requestFrom() function from the Wire.h library and I call this function in the NodeMCU loop every 100ms.
The problem is that the servos (which are connected to the Arduino to pins 10 and 11) twitch every approximatively 10s. If I change the interval at which the NodeMCU asks for data from Arduino to 200ms, the twitch interval for the servos changes to 20s.
Is there a buffer that gets full or what is happening? I think that the Wire.onRequest() handler from Arduino interferes with the PWM of the servos. Is there a workaround? Do you have any idea how to stop the servos from twitching? Perhaps make the libraries use different timers? Thanks in advance!
Code:
#include "Arduino.h"
#include <Wire.h>
#include <Keypad.h>
#include <Servo.h>

Servo servo_1;//up-down servo
Servo servo_2;//left-right servo

byte deg_1=0;
byte deg_2=0;

byte manual_move_mode = 0;

byte data_count = 0, master_count = 0;

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup() {
 Wire.begin(8);                /* join i2c bus with address 8 */
 Wire.onReceive(receiveEvent); /* register receive event */
 Wire.onRequest(requestEvent);
 Serial.begin(115200);           /* start serial for debug */
 Serial.println("Program Started");
 pinMode(13, OUTPUT);

 servo_1.attach(10);
 servo_1.write(0);
 servo_2.attach(11);
 servo_2.write(0);
}

void loop() {

 manual_move_servo();
 //send_keys();

}

// function that executes when data is received from master
void receiveEvent(int howMany) {
  String data="";
 while (0 <Wire.available()) {
    char c = Wire.read();      /* receive byte as a character */
    data += c;

  }
    Serial.println(data);   /* print the request data */

    if (data=="PIN_13_HIGH"){
    digitalWrite(13,HIGH);
   } else if (data == "PIN_13_LOW"){
    digitalWrite(13,LOW);
   }

    if (data=="MANUAL_TRUE"){
    manual_move_mode = 1;
   } else if (data == "MANUAL_FALSE"){
    manual_move_mode = 0;
   }
}

void requestEvent()
{
  char customKey = customKeypad.getKey();
  if (customKey){
    Serial.print("Transmission to NodeMCU begins...");
    Serial.println(customKey);
    Wire.write(customKey);  // sends hello string
  }
}

void manual_move_servo(){
  if (manual_move_mode == 1){
      char customKey = customKeypad.getKey();
  if (customKey=='2'){//move up
    //digitalWrite(13,HIGH);
    deg_1+=5;
    servo_1.write(deg_1);
  } else if(customKey=='8'){//move down
    //digitalWrite(13,LOW);
    deg_1-=5;
    servo_1.write(deg_1);
  } else if(customKey=='4'){//move left
    //digitalWrite(13,HIGH);
    deg_2+=5;
    servo_2.write(deg_2);
  } else if(customKey=='6'){//move right
    //digitalWrite(13,LOW);
    deg_2-=5;
    servo_2.write(deg_2);
  } else if(customKey=='*'){
    manual_move_mode = 0;//este nevoie sa trimitem inf asta spre nodemcu????? nu cred pentru ca nu comandam altceva in fctie de var asta cu nodemcu poate doar daca adaugam un led indicator pe interfata web
  }
  }
//ne asiguram ca nu trecem de intervalele impuse
  if (deg_1<=5){
    deg_1=5;//daca pun 0 se duce automat la 180(probabil se intercaleaza intervale)
  }

  if (deg_1>=180){
    deg_1=180;
  }

    if (deg_2<=5){
    deg_2=5;//daca pun 0 se duce automat la 180(probabil se intercaleaza intervale)
  }

  if (deg_2>=180){
    deg_2=180;
  }
}

/*void send_keys(){

    char customKey = customKeypad.getKey();

  if (customKey){
    Serial.println(customKey);
    Serial.print("Transmission to NodeMCU begins...");
    Wire.beginTransmission(47); // begin with device address 8
    Wire.write(customKey);  // sends hello string
    Wire.endTransmission();// stop transmitting
  }
}*/

Please show us your code. The servo library and the Wire library both make use of Interrupt Service Routines. The onRequest() callback function is called from an ISR. If it takes too long to execute the ISR of the servo motors might have to wait, thus the motors are twitching. At least that would be my theory.

You could drive the servos directly from two PWM pins, instead of using the Servo library which uses an ISR. I'd suggest using the pins 9 and 10, as those use timer1. See https://forum.arduino.cc/t/servo-motor-controlled-by-timer-1-to-prevent-jitter/483767

@chrisl I added the code for the Arduino

Please try to do the very minimum of work inside the onRequest() and onReceive() callback functions. These are called from an ISR. For the onRequest() read the keypad in the main code and just prepare a variable (declared as volatile), which you then just do Wire.write() with in the onRequest() callback function. Reading the keypad takes some time. Also be cautious with printing too much to Serial inside an ISR. If it fills the buffer it can block your entire code and the data will only be send after the ISR is left.

So if I remove code from the onRequest() and onReceive() the servos should stop twitching?

I'll try to use hardware PWM instead of timer interrupts for the servos but I do not really know how (i'm gonna read about this). I have used the ServoTimer2 library but that does not work so is the hardware PWM going to work( I believe it is a different concept?; does it also use timers?)

I managed to stop the servos from twitching by removing the keypad reading from the onRequest() function. Thanks a lot!


text:
How to fix this problem of invalid conversion from 'const char*' to 'char' [-fpermissive]
Im working with node mcu ESP 8266 and trying to make it a webserver but keep encountering this problem.
   #include<ESP8266WiFi.h>
    WiFiClient client;
    WiFiServer server(80);
    void setup()
    {
    Serial.begin(9600);
    WiFi.begin("network","password");
    while(WiFi.status()!= WL_CONNECTED)
    {
      delay(200);
      Serial.print("...");
    }
    Serial.println("NodeMCu is connected");
    server.begin();
    }
    void loop()
    {
    client = server.available();
    if(client==1)
    {
       String request= client.readStringUntil("\n");
      Serial.println(request);
    }
    }
    ```

I'm getting this error :error: invalid conversion from 'const char*' to 'char' [-fpermissive]
   24 |    String request= client.readStringUntil("\n");
      |                                           ^~~~
      |                                           |
      |                                           const char*

Please copy the exact error message, including the line where the compiler finds the error. Also put your code in a code block (" {}  " when editing).

BTW, the problem is in the client.readStringUntil("\n"). The double quotes make the \n into a c-string (const char *), but it expects a single character (char). You can correct this by changing "\n" into (single quoted) '\n', which makes it into a single character.

I assume this is "off-topic" because the bug is not specifically about the Arduino. Given OP's level of experience, they had no way to know that.  I expect many other Arduino novices will encounter this same error and come here looking for an explanation.  Is this really so off-topic?


text:
I can get arduino code/board to show voltage using analog input but not python/board
I am trying to simply read a voltage from a battery. I am able to work out how to do this using arduino code on an arduino board. (UNO)
When I try to do the same thing on a board using python the output seems erroneous.
Using arduino I will say for example get a voltage output to serial monitor or 1.39v which stays pretty much constant.
When doing so with the python board (Trinket M0) the output varies from 1.23342 -1.78484 and varies between these values.
My arduino code is as follows:
int offset =0;// set the correction offset value
void setup() {
  // Robojax.com voltage sensor
  Serial.begin(9600);
}

void loop() {
  // Robojax.com voltage sensor
  int volt = analogRead(A0);// read the input
  double voltage = map(volt,0,1023, 0, 2500) + offset;// map 0-1023 to 0-2500 and add correction offset

  voltage /=100;// divide by 100 to get the decimal values
  Serial.print("Voltage: -");
  Serial.print(voltage);//print the voltge
  Serial.println("V");

delay(500);

}

My Python code is as follows
import time
import board
from analogio import AnalogIn

analog_in = AnalogIn(board.A1)

def get_voltage(pin):
    return (pin.value * 3.3) / 65536

while True:
   print((get_voltage(analog_in),))
    time.sleep(0.1)

Have you checked the voltage with a multi-meter while the Trinket M0 is running, to compare against a reference? Perhaps the M0 reading is correct?

Ok, i had made a really stupid mistake and had wired the analogue pin incorrectly. However, now my reading in the serial console read 0.33456 -0.34564 the voltmeter reads voltage as 1.42v


text:
Bluetooth Upload is Hanging
I am trying to program my Arduino via bluetooth and have been following this tutorial very closely in order to do so: https://www.instructables.com/Program-an-Arduino-Wireless-Over-Bluetooth/
I have been able to put my HC-05 into AT command mode, entered the commands, and received the "OK" responses. When I go to try to upload the code, however, the sketch usually hangs and nothing happens. The TX on my HC-05 goes to the Arduino RX, RX to TX, VCC to 5V, GND to GND, and EN to RESET.
I am able to see the device no problem on my windows computer and seem to be using the correct port. Any ideas on how to fix the issue?
Any help is greatly appreciated!

what is EN pin?

I think it is the same as the Pin 32 or something. My HC-05 only has STATE, VCC, GND, TXD, RXD, and EN.

as you can see in the tutorial the wire for reset is solder directly to the Bluetooth module. it is not a random pin.

How should I connect the HC-05 to the Bluetooth module then?

do you have the reset wire soldered to the BT module?

I was just reading this tutorial: https://www.fpaynter.com/2019/06/arduino-remote-programming-using-a-hc-05-bluetooth-module/ which indicated that I instead should connect the STATE pin to the Arduino's RESET pin. It still is not working though.

I was just reading more of that tutorial again - my HC-05 shows no lights or anything when plugged in. Is that a problem?


text:
Exception 29 when trying to display NTP time on an LED
I'm currently working with a "WEMOS D1 R2 & mini" and am trying to call the time from an NTP server and display it onto an OLED display. I've been stuck on an error code that I can't seem to work around and was hoping for some pointers in the right direction. I've used an exception decoder to try an understand it but it's not really helping.
The error in the exception decoder:
Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
PC: 0x4020d032
EXCVADDR: 0x00000000

Decoding stack results
0x40202d64: ESP8266WiFiSTAClass::status() at C:\Users\XXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src\ESP8266WiFiSTA.cpp line 563
0x4020292e: digitalClockDisplayOled() at C:\Users\XXX\Documents\Arduino\possible_fixed_clock/possible_fixed_clock.ino line 40
0x40202970: loop() at C:\Users\XXX\Documents\Arduino\possible_fixed_clock/possible_fixed_clock.ino line 35
0x4020512c: loop_wrapper() at C:\Users\XXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266\core_esp8266_main.cpp line 125

The code I'm using:
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET -1
#define OLED_SCREEN_I2C_ADDRESS 0x3C
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Defining constants
const char *ssid     = "XXX";
const char *password = "XXX";
const long offset = 3600;
// Background stuff
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", offset);
void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);

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

  timeClient.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalClockDisplayOled();
}

void digitalClockDisplayOled() {
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(timeClient.getHours());
  printDigitsOled(timeClient.getMinutes());
  printDigitsOled(timeClient.getSeconds());
  display.display();
}

void printDigitsOled(int digits){
  display.print(":");
  if(digits < 10)
    display.print('0');
  display.print(digits);
}

What is this error code actually telling me, and what kind of implementation could I use to fix it?

That error is an access violation. The fact that it happens inside a system function indicates that you probably have some memory corruption. Try removing code (e.g. remove the display output) until it works.


text:
WiFi HaLow library
Does anyone know if some Arduino based library is on the way to support new low power WiFi HaLow modules. If there is, I would like to know for which module?
For reference I'm sharing link here

What's a WiFi HaLow module?

I shared link in the question

If anyone will make one Adafruit will, and they haven't yet. The tech is too new for Arduino...