text:
Making pushbutton behave as a toggle switch with ezButton - do I have to use ledstate with =! operator
I'm using ezbutton to make a pushbutton act like a toggle switch, first press doing permanent on, second press doing permanent off. I'm just trying to understand the basic coding. This project is just a testbed for what I'm planning to do later - wiring vehicle toggle switches to Arduino and feeding the output signal to mosfet that will control the load state. So I'm trying to get the code as nice and tidy as I possible can. In the code below, I would like to know if ledState will be applicable when this sketch will control a mosfet instead of a test led, and I've seen comments saying "ledState = !ledState;" is not optimal - but being a beginner I'm not sure what this means, and is there a better more sound way to address it. Thanks!
#include <ezButton.h>

// ---
// Declaration
// ---

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// ---
// Setup
// ---

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// ***
// Main Loop
// ***
void loop()
{

  button.loop();

  if (button.isPressed()) {
    ledState = !ledState;
    digitalWrite(led1, ledState);
  }

}

what comments? if a button press should change the state from true to false and from false to true then this does it right.

Thanks @Juraj I'm just trying to understand the code that I managed to merge together from various examples I found, and as for ledState I haven't found explanation for it on Arduino's official reference pages, so I didn't know what did it do exactly

if : it works + you understand how it works , then it's find ;
ledstate = !ledstate ; //  is short and efficient to "flip flap" the boolean value

please take a coding course

@Varonne, does this code really toggle the ledState on then off with each button press?  I am thinking when you press the button the ledState will be switching on and off and on and off again and again as quickly as the processor will execute the code.  Then randomly stay on or off depending on when you release the button.

@st2000 it does work exactly as intended, with pushbutton it works as "first push = permanent on, second push permanent off" and doesn't do any random behavior.

Thanks, I'll have to try the button class.  I didn't know it contained a state machine.  I just though it de-bounced switches.

I've been looking through the source code for ezButton.c
The function isPressed() is something of a misnomer and is only meaningful for a push-to-make button on the low side of a pull-up resistor. It actually detects falling edges of the signal, so it should be called isFallingEdge(), but the code itself is good.
Similarly for isReleased() which detects rising edges of the signal, so should be called isRisingEdge().
The constructor defaults to INPUT_PULLUP which may (or may not) be what you want for your buttons and toggle switches, so it's something to bear in mind especially for low-side push-to-break buttons or high-side push-to-make buttons which will generate rising edges when pressed and falling edges when released thus reversing the meanings of isPressed() and isReleased(), hence why they really should be called isFallingEdge() and isRisingEdge().
The algorithm in ezButton::loop() could be optimised a bit by getting rid of previousSteadyState and nesting the final if statement within the second if statement.
Other than that, it's quite a good algorithm that makes use of hysteresis to reset the debounce timer.
For comparison you could take a look at my algorithm in this simple debouncer for Arduino that simply detects rising edges, falling edges or both edges without regard to whether a button was pressed or released, and can be used in a polling loop or with interrupts. Here's the essence of the algorithm:
    bool input_state = digitalRead(INPUT_PIN);
    unsigned long current_ms = millis();

    edge = rise = fall = false;

    // Hysteresis:
    //   If there is no change, reset the debounce timer.
    //   Else, compare the time difference with the debounce delay.
    if (input_state == output_state)
    {
      last_ms = current_ms;
    }
    else if ((current_ms - last_ms) >= DEBOUNCE_DELAY_ms)
    {
      // Successfully debounced, so update the outputs.
      rise = input_state && !output_state;
      fall = !input_state && output_state;
      edge = rise || fall;
      output_state = input_state;
    }

And ledState = !ledState; simple toggles the value of ledState which is what you write to your LED with digitalWrite(led1, ledState); each time a falling edge is detected in the input signal.

Thanks for the insight @tim ! I'll be honest I'm struggling with this because I'm completely new to electronics and in the past month I've introduced myself to crimping, soldering, Arduino, connectors, all the things, and it's bit overwhelming, but I'll try to comprehend :D


text:
non asssign variable using by for in loop() can remeber last value. what happen here?
I modify this code from my friend and it look strange.
void setup() {
    Serial.begin(115200);
    Serial.println("reset");
}
void loop() {
    for (int d; d <= 32767; d++) {
      Serial.println(d);
      delay (1000);
    }
}

for some reason when you press reset, the variable will keep counting from last value as shown.

this not gonna happen when you put these block in setup()
I know that not good idea to use varible in for loop without assigned the value, but I belived it must have a interesting reason for this.
For my hypothesis, the variable value just allocate with same address in memory. when this code run in setup() some how the complier detect this situation and assign 0 as initial value. but when in the loop() some how the compiler don't assign new value to the memory address and it get old value from last time the program was run before resetted. I still need further explanation.

This code behaves normally for me - 'd' starts at 0 for every reset. Is this the complete and exact code that made the output example?

@JRobert, yes I use Arduino UNO with Arduino 1.1.13

I think you missed a compiler warning (I did, too!) - notice that you are using 'd' uninitialized. On each re-entry to the loop() function, loop()'s stack will be in the same place in memory. The for-loop doesn't initialize 'd', but the boot loader did zero RAM for your first run. 'd' happens to occupy the same memory location on each entry to loop(), so the old value (just before reset) is still in place. Since the for-loop didn't re-initialize it... :)
The fix is:
for (int d=0; d <= 32767; d++) {

Update:
That begs the question: Why did your run fail as expected, while my run appeared to execute normally? My guess is different bootloaders, one that does, and one that doesn't, initialize SRAM on a reset that doesn't result in an upload.

Wow, never think that was firmware problem. I doesn't need the fix I want the explanation.

I can't confirm that the difference between your runs and mine is due to firmware, but there's no question that 'd' was being used without initialization.

old IDE, old AVR toolchain

source: Stack Exchange

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

sort: votes


text:
Arduino button voltage versus HIGH/LOW state
I'm measuring voltage between button's ground and input pole on the following sketch. When button is on off state, there's 5V there, when it's switched on and led turs on, there's 0. Is this a correct way, and also how do I make it easier to write code and have LOW represent led being off. In this sketch, digitalWrite(led1, LOW); means the LED is actually turned on, so how do I tweak this to be representative of actual state, high=led on.
#include <ezButton.h>

// -----
// Declaration
// -----

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// -----
// Setup
// -----

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// *****
// Main Loop
// *****

void loop()
{

  if( digitalRead(button1) == LOW ) {
    digitalWrite(led1, HIGH);
  }
  else  {
    digitalWrite(led1, LOW);
  }

}

// *****

@Juraj but doesn't the "int ledState = LOW;" mandate that when starting up the Arduino with this sketch led is off?

what is the purpose of int ledState = LOW;? ... your program does not use ledState

const int LED_Off = HIGH; const int LED_On = LOW;  then use LED_On/Off as you please...

So, if I correctly understand, you are getting confused, because turning the LED on means  writing LOW to it. And you want to change that to not be confused anymore. Is that correct?

To answer your question, Is this a correct way, yes, it is one correct way. There's nothing incorrect about an LED circuit that turns the LED on when the voltage is low, and off when the voltage is high. If you want to change that fundamental property, you have to change the circuit.

If I correctly understand, you're rather confused by the inverse logic of a PULLUP button. Alternatively to @Abel's comment you might define const int PRESSED=LOW; and write if (digitalRead(button1) == PRESSED) digitalWrite(led1, HIGH);

To answer the posted question literally: Yes, it is the correct way for your circuit, which has the button between the pin and GND, and the LED between VCC and the pin:

simulate this circuit – Schematic created using CircuitLab
I can understand the confusion. However, the meaning is right, because the level on the button's pin is LOW if pressed. And the level on the LED's pin needs to be LOW for current to flow.
You can define your own constants:
// other stuff left out

const int LED_ON = LOW;
const int LED_OFF = HIGH;

const int BUTTON_PRESSED = LOW;
const int BUTTON_RELEASED = HIGH;

void loop()
{
  if (digitalRead(button1) == BUTTON_PRESSED) {
    digitalWrite(led1, LED_OFF);
  }
  else {
    digitalWrite(led1, LED_ON);
  }
}

If you want to keep using HIGH and LOW, but interpret them as:

HIGH = button pressed / LED on
LOW = button released / LED off

Then you need to modify the circuit:

simulate this circuit
Unfortunately, there is no pin mode INPUT_PULLDOWN for the button pin, so you need to provide the pull down resistor externally. Make sure to set the pin to INPUT, not INPUT_PULLUP.
A common value for the pull down resistor is 10 kΩ.

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


text:
How to use pins for I2C that is used from other hardware?
I am using ESP32 CAM for one project and I have a sensor that is I2C connected to pins 21 and 22 (default I2C). The sensor is working fine until I turn on the camera. The camera uses this pins (21,22) as input output, not for I2C communication. When I try to read the sensor data in the loop I can't reach the sensor. I want to check the sensor data mainly and if there is some indication from the sensor to turn on the camera.
 How I can make this redefinition of the pins in the main loop?
I did try to declare the pins with  Wire.begin(21,22, 100000); in the loop but is not working.

Wire.begin(21,22, 100000); declares the pins 21 and 22 ... you already said that they interfere with the camera

Unfortunately I can't change the pins. The board have modifications and this are the only free pins. I am looking more for a solution where I can switch between the camera and the sensor without restart.

Well, if two different hardware devices are connected and want to input on both, the devices may or may not allow a software solution and you may need to add hardware logic to arbitrate them. Without knowing the details of your current HW design, it's hard to offer much specific advice. if the HE doesn't provide a way to arbitrate, it's poorly resigned.

Posting a schematic,not a frizzy thing would go a long way in solving your problem.

You didn't provide any code or schematic, so it is hard to provide a specific solution to your problem. One thing worth trying is to create a function getSensorReading() and only create the Wire instance Wire.begin() within the function so that it get out of scope at the end of the function. On your comment "I can't change the pins", well, ESP32 does provides two I2C ports, you could try Wire1.begin(14,15, 100000);.

Does this answer your problem? Especially the comments to my answer.


text:
Serial Connection - 3.3v to 5V MCU's
After asking How to connect Arduino & ESP8266, I tried to build such circuit.
First I tried the code one 2 Nano's - to verify 2 MCU sending and receiving messages. After that, I started to build the following circuit:
Take1: MCU A: Arduino Micro 5V, MCU B: WEMOS mini. R1=10K, R2=20K. FAIL
Take2: MCU A: Arduino Micro 5V, MCU B: WEMOS mini. R1=1K, R2=2K. FAIL
Take3: MCU A: Arduino NANO ,MCU B: WEMOS mini. R1=1K, R2=2K. FAIL
Take4: MCU A: Arduino NANO 5V, MCU B: WEMOS mini. Tx to Rx (no vdiv ). OK

Edit1: LCD display is connected to MCU B ( as it was tested using 2 Nano ) via I2C. Messages received are sent to LCD. PLEASE IGNORE LCD shown in not I2C
Edit2:

Diagram updated - GND was missing and POWER IN clarification.

LCD display is an I2C one. It shows properly WEMOS is booting up properly ( shows a boot msg ), and spits every incoming Serial message from other MCU. When TAKE4 and TAKE1 were taken, setup and code worked PROPERLY.

What is done wrong?

why do you say there is something wrong? ... what were you expecting to happen?

@jsotola just added "EDIT1" in my question.

@jsotola sorry. added. Library does not include I2C LCD display.

In your wiring diagram you are missing the ground connection to the Wemos. Also you have the 5V pin of the Wemos connected to Vin on the Nano, I guess to provide the Nano with power. Thats incorrect. 5V needs to go to the 5V pin. Vin is connected to the internal voltage regulator, which needs at least 6V to power the Nano.

Your frizzy thing does not help much, a schematic is better. Use a level converter, doing the resistor trick is playing with the margins of the devices and is not reliable. They give voltage ratings and threshold levels for a reason and it is good to stay away from the margins, the closer you get the more susceptible to noise you are.

How is the whole thing being powered?

You can use a mosfet to convert 5v<->3.3v: https://www.hobbytronics.co.uk/mosfet-voltage-level-converter. In this way you're not relying on the resistors and playing with the input margins

@lurker via nano’s usb

If it's all powered by the nano's USB, why is only the vin connected on the nano and not the 3.3v to the power rail?

@lurker what do you mean ? Vin is 5v

You say that nano is supplying the power to your system. Vin is a voltage input.

I'd the nano is supplying power, wouldn't you want the nano's 3.3v output available to the esp8266?

@lurker Vin also outputs 5v. So it is the same

@lurker it is not about powering the MCUs but the differnt vlogic affecting Serial communication.

@Guy.D Can you address the lack of a GND connection on the Wemos? Is that just a frizzy error or have you really missed it out?

@Majenko yes, it is an error. I'll update the diagram

Vin is NOT the same as 5V. You might measure 5V there (don't know, what the voltage regulator has on the input side, when its not used), but it is not for providing power. You are really risking to kill the voltage regulator on the Nano. Again: Do not use Vin as 5V power source. Use either the 5V pin or provide the Wemos directly with 3.3V through the 3.3V pin (though I'm not sure, if the 3.3V voltage regulator is really able to provide the necessary current for an ESP board)

RX/TX on Micro is Serial1

It's a system and the system starts with proper power and grounding. I thought it was a simple question. Your answer doesn't align well with your picture.

@lurker See edit 2 please.

@Majenko please see edit 2.

@Juraj what do you mean ? Serial.begin(115200) worked as expected, and show output on serial monitor as expected.

Yeah that's what you said: you're powering the system through thenano USB port. Bit you still didn't address the question of how you're then getting power from the nano to the esp8266, assuming you answered my original question about how the system is lowered completely. If the esp8266 is getting power from somewhere else, then please indicate. Yes, that can matter.

@lurker thank you for your replies! WEMOS us powered from Nano as you can see ( or I'm missing something here... )

As @chrisl has already said, Vin is not intended to be used for providing power. The documentation says that it's intended for supplying power TO the Arduino from an external supply.

@lurker OK, so to RAW ? still this is not the problem,since MCU is powered up ( WEMOS & LCD )

If you don't have proper power, it can be the source of various problems.

You seem to be mixing Nano and Micro boards in your setup. You do know, don't you, that the Micro has a 32U4, so Serial is the USB but not the TX/RX pins - you need Serial1 for those. Also the TX/RX pins on the nano are connected to the FT232 chip, which will most likely interfere with your voltage divider.

@Majenko I know 32U4 have Serial comm on that chip and it behaves differently in some manner than 328P. But to get serial connection via Tx and Rx pins should I use Serial1 ? is that what you've ment ?.
And what is the reason for Nano's not to work with voltage divider ?

@Juraj Nano. Typo

Guy.D, yes use Serial1 for communication with esp8266 on RX/TX of the Micro

I would not power the WEMOS from the nano. They are two different microcontroller dev boards and should be each powered off of the same power source. For development, I would use a breadboard power supply that provides 3.3v and 5v. You can put 3.3v on one of the breadboard red power rails, and 5v on the other red power rail (which are designated RED by convention, and BLACK is for ground, which I see you have mixed up in your diagram). This is my advice. I realize you believe this has nothing to do with your problem and will likely ignore it. I wish you luck in solving your problem.

@lurker, Wemos D1 mini is ok with powering over 5 V pin

@lurker Although breadboard is shown in my diagram/ circuit, but this setup will be used as standalone device powered one power source (HiLink 220AC to 5V )

@Juraj Thanks. So a single 5v source would be fine. Also, I was more concerned about current than voltage although I didn't check the mini specs for max current draw.


text:
All AT commands return Fail
I'm trying to send data from sensor to ThingSpeak, but the AT commands always return Fail. They work sometimes and send data.  But, most of the time they return fail.
My Connections:

ESP
Arduino

Gnd
Gnd

Vcc, ChPD/En
3.3v

Rx
2

Tx
3

My code:
#include <SoftwareSerial.h>

#include "DHT.h"

#define DHTPIN 10
#define DHTTYPE DHT11

#define RX 2
#define TX 3

#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal_I2C.h>

#define SensorPin 0          // the pH meter Analog output is connected with the Arduino’s Analog

#define ONE_WIRE_BUS 8

LiquidCrystal_I2C lcd(0x27, 16, 2);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DHT dht(DHTPIN, DHTTYPE);
float phValue;

String AP = "Mukadam";       // AP NAME
String PASS = "28oct1997"; // AP PASSWORD
String API = "ZIGGVWBPU0BJ9A0I";   // Write API KEY
String HOST = "api.thingspeak.com";
String PORT = "80";

String f1 = "field1";
String f2 = "field2";
String f3 = "field3";
String f4 = "field4";

int countTrueCommand;
int countTimeCommand;

boolean found = false;

int valSensor = 1;

SoftwareSerial esp8266(RX,TX);

float Celcius=0;
float Fahrenheit=0;

float b;

int buf[10],temp;

unsigned long int avgValue;

void setup()
{
  lcd.begin();
  lcd.backlight();
  Serial.begin(9600);
  dht.begin();
  pinMode(13,OUTPUT);

  sensors.begin();

  lcd.print("WT:");

  esp8266.begin(115200);

  sendCommand("AT",3,"OK\r\n\r\n");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}

void loop()
{
  sensors.requestTemperatures();
  Celcius=sensors.getTempCByIndex(0);
  Fahrenheit=sensors.toFahrenheit(Celcius);

  Serial.print("C:");
  Serial.print(Celcius);

  lcd.setCursor(3,0);

  lcd.print(Celcius);

  String getData = "GET /update?api_key="+ API +"&"+ f1 +"="+String(Celcius);

  sendCommand("AT+CIPMUX=1",5,"OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");

  esp8266.println(getData);

  delay(1500);countTrueCommand++;

  sendCommand("AT+CIPCLOSE=0",5,"OK");

  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(100);
  }

  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }

  avgValue=0;

  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];

  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value

  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);

  lcd.setCursor(9,0);
  lcd.print("pH:");
  lcd.setCursor(12,0);
  lcd.print(phValue);

  getData = "GET /update?api_key="+ API +"&"+ f2 +"="+String(phValue);
  sendCommand("AT+CIPMUX=1",5,"OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");

  esp8266.println(getData);delay(1500);countTrueCommand++;

  sendCommand("AT+CIPCLOSE=0",5,"OK");

  lcd.setCursor(12,0);
  lcd.print(phValue);

  float h = dht.readHumidity();

  lcd.setCursor(0,1);
  lcd.print("H:");
  lcd.setCursor(2,1);
  lcd.print(h);

  float t = dht.readTemperature();

  lcd.setCursor(8,1);
  lcd.print("AT:");
  lcd.setCursor(11,1);
  lcd.print(t);
  lcd.setCursor(12,0);
  lcd.print(phValue);
}

void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");

  while(countTimeCommand < (maxTime*1))
  {
    esp8266.println(command);//at+cipsend

    if(esp8266.find(readReplay))//ok
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if(found == true)
  {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if(found == false)
  {
    Serial.println("Fail");

    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

And here is serial monitor output:

work sometimes and always fail are contradictory statements ... you cannot have both .... how do the commands fail? .... what errors do you get? .... does any specific command work more often?

SoftwareSerial is unreliable at 115200 baud. use 9600 baud. you must change the baud rate in AT firmware too

@jsotola always fails as in it always give Fail & sometimes work means just 1 day or 2 it will send data

I'm fairly new to using esp8266 how to change firmware baudrate?

This answer (mine) describes how to change the ESP's power-on baud rate.

write and run a sketch which sends AT+UART_DEF=9600,8,1,0,0 at 115200 baud. you only need to run it once. the esp remembers the baud rate. or you can use this one https://github.com/jandrassy/WiFiEspAT/blob/master/examples/Tools/ChangeATBaudRate/ChangeATBaudRate.ino

@Juraj Can provide me with the change I have to make in my sketch. As I have mentioned I'm new to esp and am getting confused by the instruction and tutorials on the internet


text:
Arduino ESP8266 HTTPS Request returning empty response
I want to get some JSON data from a HTTPS secured Webserver using a ESP8266.
For some reason I'm getting an empty response, I believe there's an error parsing the GET request.
In Chrome I get the JSON response without problems.
GET Request:
httpsClient.print(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

Host and Path:
const char *host = "www.adler-mannheim.de";
const char *path = "/jsonapi/game/current";

UPDATE:
I tried fetching some JSON from another Server and it worked finde, so i can rule out my code.
Fiddling around with the host and path I observe this:

Hostname without "www" results in a 301

Hostname with "https://www" results in no HTTPS connection at all

So it seems that a "www" is required although it unfortunately leads into a empty response.
The output is as follows:
headers received
reply was:
==========
==========
closing connection

In the first case, without using "www" in ahead of host there's some 301 HTML in between the two lines of "=".
Whole function:
void connect() {
  WiFiClientSecure httpsClient;    //Declare object of class WiFiClient

  Serial.println(host);
  httpsClient.setInsecure();

  Serial.print("HTTPS Connecting");
  int r=0; //retry counter
  while((!httpsClient.connect(host, httpsPort)) && (r < 30)){
      delay(100);
      Serial.print(".");
      r++;
  }
  if(r==30) {
    Serial.println("Connection failed");
  }
  else {
    Serial.println("Connected to web");
  }

  String getData, Link;

  //GET Data

  Serial.print("requesting URL: ");
  Serial.println(host+Link);

  httpsClient.print(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

  Serial.println("request sent: ");
  Serial.println(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }

  Serial.println("reply was:");
  Serial.println("==========");
  String line;
  while(httpsClient.available()){
    line = httpsClient.readStringUntil('\n');  //Read Line by Line
    Serial.println(line); //Print response
  }
  Serial.println("==========");
  Serial.println("closing connection");

  delay(2000);  //GET Data at every 2 seconds
}

UPDATE 2:
I tried the following code from the ESP8266HTTPClient Library examples:
void connect2() {

  WiFiClientSecure client;

  //client.setFingerprint(fingerprint);
  client.setInsecure();

  HTTPClient https;

  Serial.print("[HTTPS] begin...\n");
  if (https.begin(client, "https://github.com/esp8266/Arduino/issues/3417")) {  // HTTPS

    Serial.print("[HTTPS] GET...\n");
    // start connection and send HTTP header
    int httpCode = https.GET();

    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = https.getString();
        Serial.println(payload);
      }
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
    }

    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n");
  }

  Serial.println("Wait 10s before next round...");
  delay(10000);
}

This one gives me a 200 but no payload. Other sites work
UPDATE 3:
I had a look on the headers.
https.headers()

This gives me 0 headers on every page, even when there's a payload.
I also had a closer look at the payload that returns from my desired api and its filled with NULL.
In a weird way this is only the case with my desired page and only my desired subpages.
Requesting something more at top level e.g "https://www.adler-mannheim.de/jsonapi" which is basically a SilverStripe Welcome page, I get a fully fetched beautiful HTML payload.
I got literally no Idea why. Do I have to set a specific User Agent or something so that the Server responds?

I assume it's an empty response since it says Reply (nothing in between), whereas from other sites theres a response in between. I'll edit the question to make it clear

https:// is not part of the hostname. It's the protocol indicator for a URI.

The 301 response will also have a "Location:" header which tells you the real URI you should be accessing. 301 is permanently moved, so it is safe for you to replace your URI in your code with the one provided in the Location header.

The 301 points to the exact URL which I'm trying to access (https://www.adler-mannheim.de/jsonapi/game/current). It also works fine in a Browser.

I guess you don't wait for the response long enough

How do I make it wait longer then? Insert a delay? Also since it claims that it received headers, the response should be ready, right?

I added the code to the post. It does get to "headers received" so I figure it did receive at least something, right?

The other example function gives me a 200 with also no payload.

and the headers? is there a content-type or content-length?

if the https.headers() function is correct for checking the headers, theres none.

Okay I have no Idea what I changed apart from deleting some imports which might have collided, but now it works. Regular call with "https://www" does the thing.
Thanks anyways

It would be better to have a more complete answer, assuming it can be of use to someone else.  Otherwise the question and answer both are probably better off deleted.

the version with WiFiClient or the version with HttpClient?

I had this same problem and I realized it was because I was using an WiFiClientSecure to try to an endpoint over HTTP instead of HTTPS. If anyone else is having this same problem, I would check that.


text:
Purpose of LED indicator
I am using an arduino mega clone called the Funduino.
I am developing a python based, tkinter application that will receive the serial data that arduino sends.
However, i am witnessing some behavior that i cannot explain and i am trying to debug. I won't say anything more, because this is an arduino forum, not a python forum.
But, in the arduino, there are some leds. One of them is power, which is constantly ON, when the arduino is powered.
There is another led that is named 'L'. When i open a serial connection this is lighted up and it stays ON.
However sometimes, when i send a string to the arduino, in order to trigger some data exchange, this button is switched off.
So what does this 'L' led is, and what it means when it is turned off?

"L" is the user LED that is connected to pin 13. It's controlled by your software installed in the Arduino, whatever that might be.

@Majenko -- if unconfigured, the LED pin is tristate, and could be controlled by signals external to the Arduino.

If you do not configure the pins, they are initialized as pinMode(xx,INPUT) which is a floating high impedance state.  Per the Arduino Uno R3 schematic, that pin is on PB5/SCK/13 which is run through the op-amp (top center in the schematic) to drive the LED. Per the Arduino Mega schematic, that pin is on PB7/OC0A/OC1C/13 which isn't run through the op amp.  I left mine unconfigured on a Mega clone and measured a 1.5V on 13 and had the LED on.  On an Uno clone, the light was on while unconfigured, and I measured 0.9v (but my DMM seemed to draw down the voltage).
If the pin is left floating in an unknown state, it could drive the LED into an unknown state.

You can control it's state with:
pinMode(LED_BUILTIN,OUTPUT);  // LED is forced off (0.01V)
digitalWrite(LED_BUILTIN,1);  // force LED on (4.97)

or
pinMode(LED_BUILTIN,INPUT_PULLUP); // On, but with the internal pullup resistor, not logic gates.  Pin 13 can be shorted to ground.

or set it back to the default tri-state:
pinMode(LED_BUILTIN,INPUT); // Tri-state, undefined.
// You could control the LED from an external signal on the pin.

Measure the voltage at pin 13 and see what you get.
Personally, I purpose it as a status indicator light.  E.g.  https://github.com/drf5n/foxyPulseInduction_Discrimination/blob/discrimination/StatusCodeLED/StatusCodeLED.ino
Because of the tri-state/op-amp LED driver on "L", you can use the light as as a logic probe--you could leave it unconfigured and jumper it to other inputs or outputs for troubleshooting and diagnostics.  If you have a project monitoring one important input, rather than putting it on a different input pin and explicitly echoing it to the LED like digitalWrite(LED_BUILTIN,digitalRead(sensorPin)); you could hook it to pin 13 to visually see the input status and just digitalRead(sensorPin).
====
Note that there are two revisions of the Arduino Mega schematic.

https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf -- A top search hit
https://content.arduino.cc/assets/MEGA2560_Rev3e_sch.pdf from https://store-usa.arduino.cc/products/arduino-mega-2560-rev3

After testing this behavior, I noticed that the my Mega clone did not match the Arduino Mega schematic at https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf . Tracing it out, it does use the op-amp like the Uno. (Pin 1&2 of the opamp attach to the "L" LED through the third resistor in the resistor array next to the LED.)

This buildin LED is connected to an IO pin of the microcontroller on the Mega (most commonly pin 13, but might be different depending on the board). So the meaning depends on what the code on the Mega does with it.
When the board is reset (which happens on opening of serial connection), first the bootloader will run. It gives you a short blink on the buildin LED. After the bootloader finishes, your own code is in charge. Whatever you do in your code with pin 13 will be reflected on the LED. Here the meaning depends on you.


text:
Sending data to server
I have an SD card have a very big file (1M character). i try to load it into memory in terms of 4K character array ( The maximum I could do using Arduino Mega). but this take almost 250 call to the server. And this is too much. Is there any way better to do it. I am using firebase as my server and i am touching the limit and this is inacceptable to the stability of the program

So I guess you are using an ESP8266 with AT firmware for Wifi connection? Or do you use an ethernet shield?

client.write(file); doesn't work?

@chrisl I use SIM800L

@Juraj I guess this is not available i use micro sd interface and SIM800L and there is no such function as you mentioned

I don't think, that you can get around the 4k limitation with this hardware. Is the number of calls the problem, or the time needed for doing the whole transmission?

@chrisl Both are problems

please post your code ... overwrite any sensitive information

I doubt that the GSM can send data in such large chunks. on TCP networks data are send in 1.5kB packets. so I doubt making the buffer larger will help. it is simply how things are done: read buffer, write buffer until everything is copied. I guess the optimal buffer size will be 512 bytes or less

@Juraj Ok, Is there any better solution to send data to servers in this large chunks?

better? put the SD card in a computer

I need to send data periodically and automatically


text:
Program only works with Serial.begin
My program only works when the following line is added:
Serial.begin(9600);

When this is disabled/removed the program no longer switches output state regular
I'm using an Arduino Mega 2560.
When the line is added:

The output is switched ON or OFF regular around every 1sec.

When the line is removed:

The output is switched after 1 sec (as expected) but then switched multiple times after around 3 sec.
I tried with another Arduino Mega 2560: This time, the output is switched after 1sec (as expected) but then switched multiple times right after (and not after around 3 sec).

What could be the problem?
My code:
byte inputPin2 = 2;
byte inputPin3 = 3;
byte outputPin = 13;
boolean outputPin_HIGH = false;
volatile short angle = -18;

void setup() {
  Serial.begin(9600);      //<----------------------
  pinMode(hallSensorPin, OUTPUT);

  pinMode(inputPin2, INPUT_PULLUP);
  pinMode(inputPin3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(inputPin2), ISR_addAngle, CHANGE);
  attachInterrupt(digitalPinToInterrupt(inputPin3), ISR_addAngle, CHANGE);
}

void ISR_addAngle() {
  angle = angle + 18;
}

void loop() {
  if (angle == 900) {
    if (outputPin_HIGH) {
      digitalWrite(outputPin, LOW);
      outputPin_HIGH = false;
    } else {
      digitalWrite(outputPin, HIGH);
      outputPin_HIGH = true;
    }
    angle = angle - 900;
  }
}

"When this is disabled/removed the program no longer works..." is not very informative. What, exactly, doesn't work? What were you expecting to happen? What happened instead?

When the line is disabled/removed the program no longer receives the regular interrupts and the output therefore no longer switches state.
When the line is added:
The output is set (switched ON and OFF) regular around every 1sec.
When the line is removed:
The output is set after 1sec (as expected) but then set multiple times after around 3 sec.

... or I think that the interrupt works (I can see that a signal is sent to the interrupt pin), but as I can't serial.print a flag, I don't know if it really works...

The program works fine with it, but I want to remove it (it was only for debugging)

you can store the flag values in an array ... when you reach some desired number of values stored, then call a function to do serial.begin and print out the values

I'm guessing, but it sounds like the 'proper' operation depends on UART interrupts which go away without 'Serial.begin()'. Can you confirm your sensor is indeed signaling as you expect it to?

@JRobert The interrupt comes from a driver and not a sensor (A LED lights up when it sends a signal), and I'm sure that the signal is sent as usual. I ran the code with "Serial.begin(9600);" with no problem and right after again without, with errors. I therefore also don't think there should be a problem with the signal that triggers the interrupt.

@jsotola I will try that tomorrow. But I'm sure that I get the expected flags at the right time when "Serial.begin(9600);" is used. I rather want to debug this error without serial.

It looks like you're using a ATMega328P-based Arduino (UNO,  Nano, etc).  But, you should probably say what you're using and remove all doubt.

@timemage I'm using an Arduino Mega 2560. I tried with another Arduino Mega 2560: This time, the output is switched after 1sec (as expected) but then switched multiple times right after (and not after around 3 sec).

It works without "Serial.begin(9600)" when using an Arduino Micro Pro (ATmega32u4). Here, pin 0 and pin 1 are used as the inputs to the interrupts. Nothing else is changed in the code. Sadly is this not a solution to the problem...

"output is switched after 1 sec (as expected)" why is 1 second expected?

When adding "Serial.begin(9600)" the "1 sec" is around that time I normally expect the output to switch. Without, it is very different. Why should that line matter?!?


text:
Load cell weight distribution on rectangular shape instead of square
I have built a simple scale using 4 so called 50kg load cells.

They are connected in a bridge and mounted on wooden feet of a square shaped box. All as a proof of concept which worked quite ok. The readings are all OK and deviation of +/- 2kg is totally acceptable for my project. I followed this discussion which also explains how the connection should be made properly using 4 cells.
How to get weight data from glass electronic bathroom scale sensors?
Now I want to keep the load cells on the feet but change the shape of the scale and instead of a square use a rectangle with the following sides.

In such a form a weight distribution will not be centered all the time. The object to be weighed can shift to the right or to the left.

Will this affect the measurements in a negative way or will the HX711 controller still take care of it and show the correct results?
Will the measurements still be correct using 4 cells? If not what would be the proper way of weighing a rectangular shaped load?
Would it more appropriate to measure the load with 2 cells on the right and two cells on the left and then sum it up?

why would the shape make a difference? ... the length of the cables may or may not be a problem

you say that you built the scale ... why are you asking and not testing? ... i do not see a question about any problems

For the total measured weight the load center is not relevant. If - for example - the load center is 3/4 to the right, the right load cells will measure more weight, while the left are measuring less. The overall weight has to be equal to load center in the middle

Newton's second law says that if a force acts on a mass, that mass will accelerate at a rate proportional to the force and inversely proportional to the mass.
All that means for your scale is that if you are not being accelerated up or down, the net vertical force on your body must be 0. Since your body has weight, and the net vertical force on your body is 0 (you aren't accelerating, are you? :) then the downward force must be balanced by an exactly equal upward force. That upward force is the sum of the upward forces exerted by each load cell. Their contributions may individually change depending on where you stand, but their sum must exactly equal your weight.
Note that we have said nothing about the placement of the cells! If your platform allows it, you could move one of the cells 6 (or 60 or 600) feet away from the the others, for instance. The total upward force must still be the same.
So the bottom line is:
F_lc1 + F_lc2 + F_lc3 + F_lc4 == your weight
no matter where you place the cells.

Thanks, this is exactly the answer I was expecting to hear . Clear, precise and involving physics! Of course I was almost sure it was like but needed a confirmation.

I'd just like to point out that this refers to a different Newton. It isn't me.


text:
Is defining a function improves speed rather computing average for each analog input separately
My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?
My code:
// Samples average
sample_cnt = 1000;

//// Input the pin number and compute average value
float Average_input_value(int analog_pin){
  float avg_val = 0;
  for(int i=0;i<sample_cnt;i++){
    avg_val += analogRead(analog_pin);
  }
  // Divide by Sample count to get the average value
  avg_val = avg_val/sample_cnt;
  return avg_val;
  }

Writing the code out four times, in line, is a little bit faster than calling a function because the function call and return take some time, and the loop instructions take some time, and neither of those contribute to the average calculation.
Writing a function that you use four times, however, is much more readable, is much easier to fix if you've made a mistake because you can fix it once instead of four times, and is much easier to change or replace for the same reason, if that ever becomes necessary. Besides, a good optimizing compiler can often decide when to rewrite your loop as inline several repetitions of the loop contents (called "unrolling the loop"), so hand optimizing is probably not worthwhile.
Where your function will win over 4 repetitions of the calculation code is in the code-space needed. The function is more compact, but slightly slower.

Just adding some numbers to complement JRobert's answer.
On the Uno, the cost of calling a function and returning from it is
about 0.5 µs. In contrast, calling analogRead() within a loop
costs at least 112 µs per iteration. Given that you are computing
the sum as a float (where a suitably sized integer would suffice), it
may well be more that 112 µs in your case.
I do not know how many readings you want to average, but even if it is
only a handful, the calls to analogRead() will completely dwarf the
cost of using a function.

Thank you very much for your response. I have decided to use the function approach for averaging. Right now I am using a1000 sample count for averaging. Interesting to know that calling an analogRead() actually takes 1000 times more time in the loop than in the function.


text:
How do you know what to call the digital pin your using? changing the sensor pin your using
I downloaded a water flow sketch and got it working on a bread board using an Uno, and a LCD shield.  I what to make it on perf board using a Nano, and an NOT I2C LCD.
I soldered it all up, got "Hello World" to run ok.  But because my water flow sketch originally uses D2 for the sensor, and the new sketch uses D2 for the LCD I obviously need to change the sensor pin.  I have the sensor hooked up to D8, but I can't figure out how to tell the sketch that....
I believe it is this line of code:
    byte sensorInterrupt = 0;  // 0 = digital pin 2
    byte sensorPin       = 2;

But I have tried changing the values based on the nano pin out diagram, but I just can't get it to read.  I don't think it is a hardware problem, but if i can get confirmation that i have the pin declared correctly I can go back a de-solder stuff and check....
    /*
Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

Measure the liquid/water flow rate using this code.
Connect Vcc and Gnd of sensor to arduino, and the
signal line to arduino digital pin 2.

 */
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

byte statusLed    = 13;

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 7.55;  //biger more / min

volatile byte pulseCount;

float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

unsigned long oldTime;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);

     lcd.begin(16, 2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("S.V. SAVANNAH");
   lcd.setCursor(0,1);
   lcd.print("DAY TANK");

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

/**
 * Main program loop
 */
void loop()
{

   if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print("L/min");
    Serial.print("\t");       // Print tab space

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalMilliLitres);
    Serial.println("mL");
    Serial.print("\t");       // Print tab space
  Serial.print(totalMilliLitres/1000);
  Serial.print("L");

      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print(int(flowRate));  // Print the integer part of the variable
      lcd.print("L/min ");

    // Print the cumulative total of litres flowed since starting
    lcd.print("Total ");
  lcd.print(totalMilliLitres/1000.00);
  lcd.print("L");

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

on Nano only pins 2 and 3 can be used with attachInterrupt(digitalPinToInterrupt(pin), ... https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

Can the LCD use D8 instead of D2 or D3 for "RS" or "E" on the LCD?


text:
Random servo movement with Arduino Uno
Recently, I have been working on a project involving 8 Tower Pro SG90 servos and an Arduino Uno. The issue I am running into is that the servos will randomly move when connected, without even receiving a signal from the Arduino.
Specifically, sometimes the servos will work perfectly and the input moves the servos fine, but then all of a sudden the servos will start twitching and moving erratically back and forth. Then I disconnect the power and plug it back in and I will sometimes work again or sometimes not.
I don't think power is the problem because I am powering the servos externally with a 5.5 V power supply which can provide 2.5 A. I also made sure to have a common ground between the Arduino and the power supply. Additionally, I don't think this is an issue of a broken servo because I have this problem with all eight. In my code, I have input pins to control the servos which are just buttons. These buttons also have pull-down resistors, so I don't think the input is the problem either. I am using the Arduino servo library.
The only other thing I can think of is external frequency interference because some of the circuitry and wiring are close together, but none of the wires are very long and I even tried putting a ferrite bead on the servo cables but to no avail.
If anyone has any ideas about a solution to my problem which I have not tried yet that would be amazing!
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
Servo servo7;
Servo servo8;

void setup(){
  pinMode(5, INPUT);
  pinMode(4, INPUT);
  pinMode(3, INPUT);
  pinMode(2, INPUT);
  pinMode(1, INPUT);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  servo1.attach(13);
  servo2.attach(12);
  servo3.attach(11);
  servo4.attach(10);
  servo5.attach(9);
  servo6.attach(8);
  servo7.attach(7);
  servo8.attach(6);
}

void loop(){
  if (digitalRead(5) == LOW) {
    servo1.write(120);
    delay(20);
  } else {
    servo1.write(50);
    delay(20);
  }

  if (digitalRead(4) == LOW) {
    servo2.write(110);
    delay(20);
  } else {
    servo2.write(200);
    delay(20);
  }

  if (digitalRead(3) == LOW) {
    servo3.write(120);
    delay(20);
  } else {
    servo3.write(50);
    delay(20);
  }

  if (digitalRead(2) == LOW) {
    servo4.write(110);
    delay(20);
  } else {
    servo4.write(200);
    delay(20);
  }

  if (digitalRead(1) == LOW) {
    servo5.write(120);
    delay(20);
  } else {
    servo5.write(50);
    delay(20);
  }

  if (digitalRead(A3) == LOW) {
    servo6.write(110);
    delay(20);
  } else {
    servo6.write(200);
    delay(20);
  }

  if (digitalRead(A2) == LOW) {
    servo7.write(120);
    delay(20);
  } else {
    servo7.write(50);
    delay(20);
  }

  if (digitalRead(A1) == LOW) {
    servo8.write(110);
    delay(20);
  } else {
    servo8.write(200);
    delay(20);
  }
}

Are the servos getting heated up?

No not at all. They aren't under really any load either.

Please show your code. You can edit the question, include it there and format it correctly.

As JRobert says you'll want to (accurately) debounce and maintain current state. I would also ensure that the delay is long enough for the servo to reach its end position. I would also drop the number of servos in half and see if the problem persists, but in theory eight servos should be fine on the Uno. You could also try a non-blocking delay, but I don't think that should matter. Cross-talk isn't hugely likely. I think wrapping up each button/servo combo would be a good way to get started.

You call servoX.write() repeatedly, even when no button has changed. Each call turns off interrupts briefly while the servo value is being updated. This happens, maybe 40 times/sec and may be messing up the servo timing in some non-constant way. Try only calling the servoX.write() functions once, only when its button-state has settled into a new state.
Update:

could you provide an example please

  bool prevButton5 = LOW;            // one of these for each button
    :                                // outside of the loop() func.
    :

  if(digitalRead(5) != prevButton5){  // button changed?
    prevButton5 = !prevButton5;       // save new button state
    if(preButton5 == LOW){            // (your same code from here down)
      servo1.write(120);
      delay(20);
    }
    else{
      servo1.write(50);
      delay(20);
    }
  }

Make a boolean for each button.
Wrap each of your button segments as I did for button5. Notice that your code is now executed only if the associated button has changed, so you will have many fewer servoX.write() calls.

That isn't the totally best way to do it. I made it as straightforward as I could, even though the additional code gets replicated for every button. I'd probably write a single function that manages one button and one motor, and call that function for each button / motor pair.
I also ignored the concept of switch-bounce to keep the number of changes low, but you should look it up and consider it. Switch-bounce is apparent bouncing of the switch contacts for a few milli-seconds during the change from open to closed or vice-versa, which leads to several make-break-make.....-make cycles (or the reverse) when you push or release the button. I'd probably make (or search for) a button debounce function and call it for the particular button I'm testing if I see that button has changed.
First try the "rude and crude" fix I suggested and get that working. Then if you're interested, try making one or more of the refinements.
Update:
the servos still jitter and twitch esspecailly when
I move the whole arduino and wires around.

That suggests either or both of

cross-talk;
the plug wires' connections being less than solid, especially when the wires move.

Try:

laying out the servo cables to keep them away from each other as much as possible;
wiring only a few of the servos, and in different combinations;
also try commenting out the code - or not - for those servos you disconnected in the previous step.

If it turns out to be the plug-in wires and if this project is intended to actually be used for something, I'd suggest using a screw-terminal shield on your Uno to attach the servo wires more securely.

This sounds promising but Im a little confused could you provide an example please. Thank you

Well I tried the code and it works but after a certian amount of time the servo starts jittering again. I would say that the servo jitters by less magnitude but it still jitteres and twitches. I also noticed that if I touch the 5v pin of the Arduino that the "TX" light on the Arduino turns on and the servo moves a large distance clockwise. I think the code helped but it didnt fix it yet. Any other thoughts, Thank you

I just disconnect the input pins from the buttons and the servos still jitter and twitch esspecailly when I move the whole arduino and wires around. This tells me that the problem is not in my circuitry but probably something to do with the arduino itself. Do you think it is broken or something else?

@Xander If it jitters and twitches when you "move the arduino and wires around" it sounds like an issue with the wiring.


text:
Error 1,603,0 when http post request using arduino and sim900a by Json format
I want to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data and have an error.Can someone help me to solved the error 1,603,0 since I cannot solve , I already try to use http instead of https cause I read from other QnA channel that AT+HTTPPARA="URL can only be read in http .. But nothing happen the error still there. I know the error is about the DNS but I do not know how to solve it.. Sorry it was my first time to use the sim900a
Here is my code:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

SoftwareSerial SIM900(10, 11);
StaticJsonBuffer<200> jsonBuffer;

char t[32];
char deviceID[12] = "TESTING";
char Name[12] = "Irsyad";
char Place[12] = "JB";

void setup()
{
  SIM900.begin(9600);       // the GPRS baud rate
  Serial.begin(9600);
  Serial.println("Initializing..");

  DynamicJsonBuffer jsonBuffer;

}

void loop()
{
  Serial.println("");
  Serial.println("START");

  Serial.print("Device ID: ");
  Serial.println(deviceID);

  delay(1000);

  if (SIM900.available())
  Serial.write(SIM900.read());

  SIM900.println("AT");
  delay(3000);

  SIM900.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); // untuk cek  GPRS
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=3,1,\"APN\",\"\"");//APN mobile phone (cek dekat phone)
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=1,1");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=2,1");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPINIT"); // jika keluar error means gagal
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPPARA=\"CID\",1"); //parameters untuk HTTP session
  delay(6000);
  ShowSerialData();

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& object = jsonBuffer.createObject();

  object.set("deviceID",deviceID);
  object.set("Name",Name);
  object.set("Place",Place);

  object.printTo(Serial);
  Serial.println(" ");
  String sendtoserver;
  object.prettyPrintTo(sendtoserver);
  delay(4000);

  SIM900.println("AT+HTTPPARA=\"URL\",\"http://gas-api.smartcp.app/api/ttn/uplink\""); //Server address // tukar pakai lain https://
  delay(4000);
  ShowSerialData();

  SIM900.println("AT+HTTPPARA=\"CONTENT\",\"application/json\""); //json format
  delay(4000);
  ShowSerialData();

  SIM900.println("AT+HTTPDATA=" + String(sendtoserver.length()) + ",100000"); // size bytes untuk hantar data dalam masa 10 seconds
  Serial.println(sendtoserver);
  delay(6000);
  ShowSerialData();

  SIM900.println(sendtoserver);
  delay(6000);
  ShowSerialData;

  SIM900.println("AT+HTTPACTION=1"); // Post the data (1 means post)
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPREAD");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPTERM");
  delay(10000);
  ShowSerialData;
}

void ShowSerialData()
{
  while (SIM900.available() != 0)
    Serial.write(SIM900.read());
  delay(1000);

}

please do not post a picture of text ... remove the picture and add the actual text

Just looking at the code, my guess is that all those 6 second delays cause a timeout error somewhere.
PS +SAPBR: 1,1,"10.143.42.168" I'm unfamiliar with AT-codes, but that 10.143.42.168 looks like an IP address, and that IP address is in the private range. Maybe it's just Carrier-grade NAT, and not related to your problem.

I hope you had found solution, otherwise, I tried this with SIM800l and it is working fine. Maybe you could try that module. I took help from your code in removing a syntax error in my code, so thank you for that.

it doesn't work for me. Getting the same error.


text:
Hexadecimal array does not add up as expected
I have an array of hexadecimal values as given below.
byte Hexa_Val[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I want to increase this array from the end. As in, go from {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} all the way to {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, and then increase the value next to it to {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, and continue. The increment should go as shown below.
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}
.
.
.
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}
.
.
.
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}
.
.
.
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}

The code I am came up with is
byte Hexa_Val[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

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

void loop() {

  Hexa_Val[7] = Hexa_Val[7] + 1;

  if(Hexa_Val[7] = 0xFF){
    Hexa_Val[6] = Hexa_Val[6] + 1;
    Hexa_Val[7] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF)){
    Hexa_Val[5] = Hexa_Val[5] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF)){
    Hexa_Val[4] = Hexa_Val[4] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF)){
    Hexa_Val[3] = Hexa_Val[3] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF)){
    Hexa_Val[2] = Hexa_Val[2] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF) && (Hexa_Val[2] = 0xFF)){
    Hexa_Val[1] = Hexa_Val[1] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
    Hexa_Val[2] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF) && (Hexa_Val[2] = 0xFF)  && (Hexa_Val[1] = 0xFF)){
    Hexa_Val[0] = Hexa_Val[0] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
    Hexa_Val[2] = 0x00;
    Hexa_Val[1] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF) && (Hexa_Val[2] = 0xFF) && (Hexa_Val[1] = 0xFF)  && (Hexa_Val[0] = 0xFF)){
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
    Hexa_Val[2] = 0x00;
    Hexa_Val[1] = 0x00;
    Hexa_Val[0] = 0x00;
  }

  //to find out what I am sending
  for( byte a=0; a<8; a++ ) {
    Serial.print(Hexa_Val[a], HEX);
  }
  Serial.println();

  delay(500);

}

But it just gives me zeros in the serial monitor. If I just leave the first two IF statements
byte Hexa_Val[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

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

void loop() {

  Hexa_Val[7] = Hexa_Val[7] + 1;

  if(Hexa_Val[7] = 0xFF){
    Hexa_Val[6] = Hexa_Val[6] + 1;
    Hexa_Val[7] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF)){
    Hexa_Val[5] = Hexa_Val[5] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
  }

  //to find out what I am sending
  for( byte a=0; a<8; a++ ) {
    Serial.print(Hexa_Val[a], HEX);
  }
  Serial.println();

  delay(500);

}

The increment will start from the third value on the right. Something like
00000200
00000300
00000400
00000500
00000600
00000700

How do I get it to increase as I mentioned at the beginning? Why does the code recognize 0xFF as a zero?

Your second (and following) if compares Hexa_val[7] with 0xFF, but the first has already reset it to 0.

Boy, I feel an itch to write assembly code that does that without branching.

There are multiple problems here:

if(Hexa_Val[7] = 0xFF)

First of all, = is the assignment operator. You are setting
Hexa_Val[7] to 0xFF. If you want to compare for equality, you should
use ==.
Second problem, The value 0xff will never be displayed, because you
are replacing it by zero. This byte will then count 0xfd, 0xfe, 0x00,
skipping 0xff. If you want to count 0xff, the condition should be
Hexa_Val[7] == 0, i.e. increment Hexa_Val[6] only after
Hexa_Val[7] has overflowed.
Third problem, your second if test comes too late. At this point
Hexa_Val[7] has already been reset. You should test for Hexa_Val[6]
overflowing only within the previous test.
With all that fixed:
Hexa_Val[7] = Hexa_Val[7] + 1;
if (Hexa_Val[7] == 0) {
  Hexa_Val[6] = Hexa_Val[6] + 1;
  if (Hexa_Val[6] == 0) {
    Hexa_Val[5] = Hexa_Val[5] + 1;
  }
}

If you don't want to write 8 nested conditions (which is kind of
cumbersome), you can instead loop over the array backwards, incrementing
each element in turn, and break out of the loop as soon as an increment
does not overflow:
for (int i = 7; i >= 0; i--) {
    if (++Hexa_Val[i] != 0) break;
}

If you don't mind the array being backwards, you can also handle the
whole array as a single 64-bit number, and just increment it like you
would increment any integer. But then you have to print the array
backwards, starting from the mast element:
union {
    uint64_t number;
    byte bytes[8];
} Hexa_Val = { .number = 0 };

void loop() {
    // Increment the array.
    Hexa_Val.number++;

    // Print out.
    for (int i = 7; i >= 0; i--) {
        if (Hexa_Val.bytes[i] < 0x10) Serial.write('0');
        Serial.print(Hexa_Val.bytes[i], HEX);
        Serial.write(' ');
    }
    Serial.println();

    delay(500);
}


text:
Blew my arduino pro mini s4 named component
While working on my project I supplied 12v to my pro mini through raw input and then a s4 named component smoked and my pro mini  stopped working . It didn't turn on either through vcc or raw. The voltage regulator seems completely fine. Can I repair my pro mini. Please help.

S4 is most likely a Schottky diode. You could try replacing it (in the correct orientation) and hope nothing else is damaged. Don’t run it at 12V in the future I guess. The fact that it doesn’t start up with just Vcc is not a good sign but you might have to remove S4 from the board first. Do you have a data sheet or schematic  of your particular Pro Mini clone? Is it a 3.3V or 5V version?

Sorry but i can only tell you that it's a 5 v version.

How do you konw if the voltage regulator is completely fine? Is that purely based on visual inspection or have you tested it? Since the failure, is it regulating the voltage to 5V (measured with a multi-meter)?

Many Arduinos have a Schottky diode between the power connector and the voltage regulator as a protection against accidental reverse polarity connection. The official Pro Mini, or the Sparkfun variant, does not.
So you can either de-solder the diode or break it off the board using diagonal cutters and then replace it with either a similar diode -- or with a solder-bridge if you are confident about never connecting power the wrong way around.
It's possible (likely even) that other components that look OK visually are actually damaged. Especially if you can't power the board by connecting a regulated 5V supply to the VCC pin.

Once you have removed the diode as described in @RedGrittyBrick's answer, you will need to replace it with another. Note you don't have to replace it with a SMD version if you can't get your hands on one. Most electronics shops sell a 1N4004 or 1N4007 diode which would be a suitable replacement.
If worst comes to worst, you could solder a blob of solder across the diode's pads - which would mean you lose the reverse polarit protection - but it would provide a path for your voltage input to go into the regulator.

The defective component is a Schottky diode. 4001 or 4007 are not Schottky diodes and have much higher Vf. A better replacement would be 1N5817 or an SMD equivalent.

It doesn't matter in this instance as it is just for reverse polarity. A normal diode is fine, a Schottky diode would be better if you can get one.


text:
Motors not working with a motor Shield
Got a Duratech motor shield today, and I'm wondering why my motors do not run. Appreciate any help. The code I am using is the Adafruit sample code, Motorparty. The servos work however the motors do not.
Here is a photo of my setup, code is below:

/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438

This sketch creates a fun motor party on your desk *whiirrr*
Connect a unipolar/bipolar stepper to M3/M4
Connect a DC motor to M1
Connect a hobby servo to SERVO1
*/

#include <Wire.h>
#include <Servo.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Connect a stepper motor with 200 steps per revolution (1.8 degree)
// to motor port #2 (M3 and M4)
Adafruit_StepperMotor *myStepper = AFMS.getStepper(200, 2);
// And connect a DC motor to port M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

// We'll also test out the built in Arduino Servo library
Servo servo1;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("MMMMotor party!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Attach a servo to pin #10
  servo1.attach(10);

  // turn on motor M1
  myMotor->setSpeed(200);
  myMotor->run(RELEASE);

  // setup the stepper
  myStepper->setSpeed(10);  // 10 rpm
}

int i;
void loop() {
  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, FORWARD, INTERLEAVE);
    delay(3);
 }

 for (i=255; i!=0; i--) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, BACKWARD, INTERLEAVE);
    delay(3);
 }

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, FORWARD, DOUBLE);
    delay(3);
 }

  for (i=255; i!=0; i--) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, BACKWARD, DOUBLE);
    delay(3);
 }
}

You can try to replace the motor with an LED and a resistor. This way you can check, if there is at least something coming out (the LED will only light up in one drive direction). Also you can try measuring the voltage with a multimeter. From the picture I cannot really see, how everything is connected. Please provide a schematic or wiring diagram


text:
How detect I2C errors with requestFrom()
I am going to use MCP23017 chips, and some of them will be cabled with a 1 meter max unshielded cable. I am expecting that certain transmissions may toss errors. So I want to tackle this problems by using the built in error detection of I2C, polling the inputs frequently (every 20ms or so) and by debouncing the received data in code by comparing the previous state to the current state of every input pin.
If you write bytes to an I2C slave with the Wire library. You can use the return value of Wire.endTransmission(); to test if the slave has acknowledged the message.
How does this work when you are requesting bytes using Wire.requestFrom( address, 3 ); for example. This function does return the amount of received bytes. Can we check this value with the value of the amount of bytes we requested?
I have read the TI document over how I2C works

The master will continue sending out the clockpulses, but will release the SDA line, so that the slave can transmit data. At the end of every byte of data, the master will send an ACK to the slave, letting the slave know that it is ready for more data. Once the master has received the number of bytes it is expecting, it will send a NACK, signaling to the slave to halt communications and release the bus. The master will follow this up with a STOP condition

So the master either ACKs or NACKs a read-in byte. Does the Wire library automatically make several attempts with reading? Oris there something in the Wire library which we can use to detect a failed read operation?
Is it perhaps so that the requestFrom() function may return a different amount of bytes than you requested with which would indicate that atleast 1 read operation failed?
So could I attempt something like
doItAllAgain:

for(int i = 0 ; i < 5 ; i ++ )
{
    Wire.beginTransmission( address ) ;
    Wire.write( register ) ;
    if( !Wire.endTransmission() ) break ; // if no error, break out of for loop
    Serial.println(F("write operation failed");
}

Serial.println(F("write operation succes");

byte requestedBytes = 3 ;
byte returnedBytes = Wire.requestFrom( address, requestedBytes ) ;

if( requestedBytes != returnedBytes )
{
    Serial.println(F("read operation failed");
    goto doItAllAgain ;
}
else
{
    Serial.println(F("read operation also succes");
    byte byte1 = Wire.read() ;
    byte byte2 = Wire.read() ;
    byte byte3 = Wire.read() ;
}

You can only get little information about unsuccessful transmission as long as e.g. a slave which is actually there does not acknowledge. I2C has no way of figuring out if transmitted data is corrupted or not. This is the mayor problem because instead of not reacting, slaves can behave erratically. To deals with that you have to implement error checks yourself, for example by validating a checksum.

From what I understand. If the dataline has a flank change while the clockline is high, there will be a NACK and this should work in 2 directions. Regardless how could I possibly add a checksum while reading out an Mcp23017 device? To have a checksum system, the slave device should be able to accept and transmitt checksum bytes correct?
I have a bare arduino at my desk with no I2C devices, I will check what the requestFrom() function returns when there is no device

Ok, so Wire.requestFrom() returns 0 when no device is connected. This means that this function does incorporate a check on NACK bits.

The Wire library does not give you any possibility to get error states, when requesting bytes from a slave. Basically you are stuck with the number of bytes being read.
Though you can read some information from that. If the number of bytes is zero, the slave didn't answer (either because its not there, or because it cannot send any byte currently). This equals a NACK by the slave after the address byte.
Other than that the I2C protocol doesn't give any more information. On requesting the slave is sending data and the master is acknowledging it. That means, that the slave cannot generate a NACK in this process. In fact that also means, that the returned number of bytes can only be zero (on NACK on address) or equal to the number of requested bytes, since after the address ACK from the slave the master will continue to generate clock pulses, until it has read all bytes, that it wanted. If the slave doesn't have any more data to send before that, it cannot stop the transmission. It would just stop driving the data line, resulting in all high data bytes (0xFF).
Also I doubt, that it would be really useful in your case. I2C is made for small distances, mostly on the same PCB. It can be used for longer distances, but your mileage may vary. If your setup really can corrupt the communication on the I2C lines, your biggest problem will be a stuck bus. The I2C protocol is generally not prepared for noisy environments and it incorporates states, where the devices on the bus can wait infinitely. This is also reflected in the Wire library. That means, that big noise on the lines will often lead to the bus being stuck in the middle of a transaction, needing you to reset the devices (not only the slaves, but also the master) to get the bus free again. I would go so far to say, that is it more likely to get the bus stuck, than to get corrupted data. So any information about errors is not really helping you here, since you won't get out of requestFrom() in the first place. Your code can very well get stuck there.
I suggest, that you test your setup thoroughly with the wanted run times. If the bus gets stuck too often for you, then you should make your setup more robust (shielded cables, or using an extra MCU with the I2C slave and using a more robust communication interface between main MCU and extra MCU).


text:
Best way to obtain angular velocity from a 9 DoF sensor
I have been using a BNO055 sensor (9° dof IMU) for a project which will use angular velocity to the mouse cursor on screen.
So far, I have gotten quaternion output from the sensor and been able to convert it to angular velocity in a couple of ways. The first, multiplying 1 quaternion sample by its conjugate in the next sample, and then converting the quaternion Delta in Euler angles. The second, converting from quaternions to Euler angles and then finding the change in those between samples.
Both methods result in angular velocity measurement, but each with their advantages and disadvantages. E.g. Quaternion Delta between samples does not suffer from gimbal lock, but it's difficult to isolate y-axis from z-axis movement.
I know that you can ask the sensor for angular velocity data directly, but apparently that's less precise due to the Gyro drift and it's relative orientation only, which is why I opted to work with quaternions.
Is there a better way to go about this?
My code included below for reference with the 2 approaches in case it's helpful/interesting. It uses the Adafruit repository, doing the standard stuff in setup function and then calling the function below in loop.
void quaternion_Delta () {
  // Quaternion data 1
  imu::Quaternion quat = bno.getQuat();
  // Euler 1
  imu::Vector<3> euler_one = quat.toEuler();
  //delay between samples
  delay(BNO055_SAMPLERATE_DELAY_MS);
  // Quaternion data 2
  imu::Quaternion quat_two = bno.getQuat();
  // Euler 2
  imu::Vector<3> euler_two = quat_two.toEuler();
  // quaternion comparison
  imu::Quaternion quatDelta = quat_two * quat.conjugate ();
  imu::Vector<3> euler = quatDelta.toEuler();
  Serial.print(" X: ");
  Serial.print(euler.x()*radius_to_degrees, 2);
  Serial.print(" Y: ");
  Serial.print(euler.y()*radius_to_degrees, 2);
  Serial.print(" Z: ");
  Serial.print(euler.z()*radius_to_degrees, 2);
  Serial.print("\t\t");
  // Euler comparison
  imu::Vector<3> euler_comparison = euler_two - euler_one;
  Serial.print(" x: ");
  Serial.print(euler_comparison.x()*radius_to_degrees, 2);
  Serial.print(" y: ");
  Serial.print(euler_comparison.y()*radius_to_degrees, 2);
  Serial.print(" z: ");
  Serial.print(euler_comparison.z()*radius_to_degrees, 2);
  Serial.print("\n");
  }

Sorry if this overlaps with any of my previous questions, I felt it was different enough that it would be more confusing to edit a already closed one. Thank you for your time.

Consider building on Sebastian Madgwick's PhD IMU research.  A GitHub Arduino project based on Madgwick's work can be found here.

Thanks for your response. The BNO sensor uses a proprietary fusion algorithm, but I've seen this implementation on a different sensor. I think my question boils down to if it's going to be more accurate to polled the sensor for quaternions from which to calculate angular velocity, or to poll the gyroscope only. Is the only difference that one is out of orientation, and the other is absolute?

I am not sure.  I have not worked with IMU chips that create quaternions.  Only with IMU chips which provide X,Y & Z values from accelerometers and gyroscopes.

There is also an Adafruit library for this and other fusion algos.


text:
What is the best way I can detect if a ping pong ball has hit the ping pong table?
The goal is to track points, which, in the case of ping pong, is how many times the ball has touched the table.
My concerns are with how light the ball and therefore the impact on the table will be.  Is this too light for something like a vibration sensor to register?
Would you imagine the sensor working better on the paddles or the table?
I'm open to other suggestions on more reliable ways to track points other than vibration.

For tracking points in ping pong I think you have to check for the ball hitting the table. Hitting the paddles does not say much (If the ball hits my paddle but then not yours, it could be my fault or yours, so the point depends more on the table). I don't think, that vibration sensing is feasable here. vibration would mean, that the whole table moves when the ball hits it. A table is normally way too heavy for that. Maybe you can cover the table with a very sensitive touch foil, though I'm absolutely not sure about that and it might be very error prone.

The best that I can think of, would be to use a camera system and let a computer track the ball in the image. Though with this you are out of the Arduino realm. That's for computers, like the Raspberry Pi.

@chrisl - Understood, I appreciate the ideas. I was trying to think out of the box and avoid the camera system route, afraid cost might start to really add up, but that might be the best solution.

one idea more: you could use a laser pointer a little strip of mirror at the sides of the table. When you carefully align it, you might be able to create a light barrier at the surface of the table (laser light bouncing back and forth between the mirrors going from the laser pointer at the one side to a fitting photodiode at the other side). The laser would have to be reflected quite (or you need to use multiple lasers diodes). That might be a bit (but not much) cheaper, than the camera thing, but might be difficult to align and the mirrors standing up at the edge might be bad for the game.

@chrisl - Funny enough I had a similar idea. Again, I'm a newbie at this so I wasn't sure of what limitations I would run into. But I thought about having some sort of motion detection or lasers running across the table along the net pointing towards the ceiling. Another funky idea was trying to detect points using sound as ping pong makes a pretty distinct noise.

The sound idea is interesting. Though I think Arduino is not really fit for that. But with a little raspberry pi (like the Zero W for 10$) and a decent microphone that might be a good way

Attach a piezo to the underside of (both) tables (similar to a contact microphone). Sound travels very well through the plywood, so just one should do. Have a look at this Arduino knock detection project

@Gerben - Finally got the sensors and started to test. I downloaded this library you recommended. But I'm getting an error when compiling. I am not great with C++ syntax. I am currently trying to run his example .ino. Any hints?
/sketch_apr24f.ino:25:44: warning: invalid conversion from 'void ()(float, long int)' to 'void ()(float, int)' [-fpermissive]
KnockDetector knockDetector(20, 5, callback);

That's a warning, not an error. You should be able to just ignore it.

By any chance, did you have the opportunity to finish your project 2/3 years ago ? I'm trying to detect the sound of a ping pong ball when it hits the table compared to when it hits anything else. How did it work on your side ?
Hope you'll see this even if it's been a long time,
Philippe

Having played ping-pong (badly) I think a microphone would be able to count ball/table impacts quite well. The 'click' sound is much higher than that of hitting the paddle, so you might be able to differentiate on that basis. You might consider a two microphone/transducer arrangement- one coupled to the table and one not touching the table. If you get a simultaneous signal on both, the ball has hit the table. If you get only one signal (from the not-touching microphone) then the ball has hit a paddle. This also gives you the option of getting some timing information.

Seconding the coupled microphone idea. It may well be possible to filter out paddle-clicks in software. The only gotcha I see is a player whose "patter" includes knocking their paddle on the table.

@JRobert I think the frequency of the 'patter knocking' would be lower/different than the 'click' of the ball impact. Much larger signal on the table coupled transducer as well.


text:
Pushbutton to initiate a 5 time flash
The following code operates in a way that LED starts to flash only if the pushbutton is pushed for one second. I want to change this and make the LED flash for 5 times, immediately on push, regardless if the button is held "long" or released immediately. Can anyone help me out with this? I'm using the LC_baseTools library btw. I managed to do this with another library with doFlash(5) but I have to work with LC basetools in this scenario and I can't figure out how to do it.
#include <mechButton.h>
#include <blinker.h>

#define BUTTON_PIN   11
#define LED_PIN      13
#define BLINK_MS     500.0
#define HOLD_MS      1000

mechButton  theButton(BUTTON_PIN);                    // A debounced button object. (Hook button between pin & ground)
blinker     theBlinker(LED_PIN,BLINK_MS/2,BLINK_MS);  // A fire and forget blinker object.
timeObj     pushTimer(HOLD_MS);                       // A timer object

void setup(void) {
   theBlinker.setOnOff(false);            // Make sure the blinker is acutally off.
   theButton.setCallback(btnClicked);     // Set the callback for the button.
}

// This gets called when the button is clicked.
void btnClicked(void) {
   if (!theButton.trueFalse()) {    // If it has been grounded..
      pushTimer.start();            // Start the timer.
      theBlinker.setPercent(100);   // Set the blinker to full on.
      theBlinker.setOnOff(true);    // Fire it up.
   } else {                         // Else, button released..
      theBlinker.setOnOff(false);   // SHut off the blinker.
   }
}

void loop(void) {
   idle();                             // idle runs the stuff in the background (button & binker)
   if (!theButton.trueFalse()) {       // If the button is currently pressed..
      if (pushTimer.ding()) {          // If the timer has expired..
         theBlinker.setPercent(50);    // Start blinking!
      }
   }
}

I don't know the library, but it seems you are using pushTimer to get this long press behavior. Why just not using it by removing the inner if statement in loop()? have you tried that?

@chrisl im not that well versed to be honest, but i'll try to mix it up with removing that part, see what comes of it

it's afternoon hobby work, I am soldering and crimping and arduino'ing out of lockdown boredome, I just took up these hobbies and quite frankly the arduino stuff is fully out of my jurisdiction, i would pay someone to at least guide me on how to do it, and i have some more ideas but no coding knowledge so I think it will inevitably come to me paying someone to get ti done :D I don't have time, with my regular responsibilites and job, to tackle arduino programming, it's not as "piece of cake" as many people suggest.

again, take a coding course

@Varonne think of a pedestrian crosswalk ... the pedestrian does not directly ask the drivers to stop ...  the pedestrian raises a flag in form of a red traffic light ... drivers watch for red light....... put a layer of separation between the button press and the LED blink ... pressing a button sets a flag, nothing else .... the LED blink code watches the flag and blinks when flag is raised .... the flag could have a value 5 ... when the blink code sees the flag being non-zero, then it blinks the LED once and decrements flag value .... on next iteration of loop() it does it again ... etc.

First of all, considering your comment: "I don't have time [...] to tackle arduino programming" - If you don't learn how to code, then you can't work with code (and that includes putting together libraries you find on the internet). And learning takes time, it's that simple.
I recommend you forget about those libraries and implement that easy task from scratch, so you actually learn something. The below code has the logic you ask for, try to understand what it does.
#define BUTTON_PIN   11
#define LED_PIN      13

bool button_was_pressed=false;

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

void loop() {
  if (digitalRead(BUTTON_PIN)) {
    if(!button_was_pressed) {
      for (int i=0;i<5;i++) {
        digitalWrite(LED_PIN,HIGH);
        delay(50);
        digitalWrite(LED_PIN,LOW);
        delay(50);
      }
    }
    button_was_pressed=true;
  }
  else {
    button_was_pressed=false;
  }
}

...pretty simple and it's only a few lines. You may want to debounce the button and use a non-blocking coding style, but that's a different chapter.
My advice is that you learn programming in a structured manner, e.g. by watching tutorials. A Q&A site is not the right place to do so, as we only answer questions.

Thanks @Sim Son for some reason your code gets an error when compiling, "if (digitalRead(BUTTON_PIN) { - error: expected primary-expression before '}' token"

@Varonne missing a closing parenthesis

@Varonne the answer provided by VE7JRO has a much better code. Mine was just intended to show you how such a thing can be implemented.

I managed to do this with another library with "doFlash(5)" but I have to work with LC basetools in this scenario and I can't figure out how to do it.

It looks like you are still allowed to write Arduino code in your sketch, so why not use the BlinkWithoutDelay "concept" and just write your own code.
I would favour an OOP solution for the LED flashing part of your requirement.
// Arduino IDE 1.8.9.
// Sketch uses 1126 bytes (3%) of program storage space.
// Global variables use 25 bytes (1%) of dynamic memory.
class Flasher{

  private:

    byte ledPin;
    byte ledState;
    unsigned int flashCounter;
    unsigned long highTime;
    unsigned long lowTime;
    unsigned long previousMillis;

  public:

    Flasher(byte ledPinNumber, unsigned long ledOnTime, unsigned long ledOffTime){
      ledPin = ledPinNumber;
      ledState = LOW;
      highTime = ledOnTime;
      lowTime = ledOffTime;
      previousMillis = 0;
      pinMode(ledPinNumber, OUTPUT);
      digitalWrite(ledPinNumber, LOW);
    }

    void Update(){

      // Check to see if it's time to change the state of the LED.
      unsigned long currentMillis = millis();

      if((ledState == HIGH) && (currentMillis - previousMillis >= highTime) && ((flashCounter > 0))){
        ledState = LOW;
        previousMillis += highTime;
        digitalWrite(ledPin, ledState);
        if(flashCounter > 0){flashCounter--;}
      }
      else if((ledState == LOW) && (currentMillis - previousMillis >= lowTime) && ((flashCounter > 0))){
        ledState = HIGH;
        previousMillis += lowTime;
        digitalWrite(ledPin, ledState);
        if(flashCounter > 0){flashCounter--;}
      }
    }

    void Start(unsigned int flashNumberOfTimes){
      flashCounter = flashNumberOfTimes * 2;
      ledState = LOW;
      digitalWrite(ledPin, ledState);
    }

    void Stop(){
      Start(0);
    }

    void SetPinHighTime(unsigned long pinHighTime){
      highTime = pinHighTime;
    }

    void SetPinLowTime(unsigned long pinLowTime){
      lowTime = pinLowTime;
    }

};

// Flasher object_name(Pin Number, ON Time MS, OFF Time MS);
Flasher led1(LED_BUILTIN, 500, 500);

void setup(){

  // Flash the LED 5 times.
  led1.Start(5);

}

void loop(){

  // Call the Update function as fast as possible.
  led1.Update();

}

See my comment on https://arduino.stackexchange.com/a/60861/40646.


text:
Serial and I2C not working together
I have very peculier problem. When I run this code SSD1306 fails to initialize. Output at serial console is:
20:26:33.194 -> MPU6050 OLED demo
20:26:33.532 -> SSD1306 allocation failed
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int count =0;

void setup() {

  Serial.begin(9600);
  while (!Serial);
  Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  Serial.println("Found a MPU-6050 sensor");

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setRotation(0);
}

void loop() {
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  display.clearDisplay();
  display.setCursor(0, 0);

  display.println("Accelerometer - m/s^2");
  display.print(a.acceleration.x, 1);
  display.print(", ");
  display.print(a.acceleration.y, 1);
  display.print(", ");
  display.print(a.acceleration.z, 1);
  display.println("");

  display.println("Gyroscope - rps");
  display.print(g.gyro.x, 1);
  display.print(", ");
  display.print(g.gyro.y, 1);
  display.print(", ");
  display.print(g.gyro.z, 1);
  display.println("");
  display.display();
  delay(100);
}

But when I run this code, without displaying gyro everything runs fine. Adafruit logo is displayed and then followed by regular accelerometer data.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int count =0;

void setup() {

  //Serial.begin(9600);
  //while (!Serial);
  //Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    //Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  //Serial.println("Found a MPU-6050 sensor");

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setRotation(0);
}

void loop() {
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  display.clearDisplay();
  display.setCursor(0, 0);

  display.println("Accelerometer - m/s^2");
  display.print(a.acceleration.x, 1);
  display.print(", ");
  display.print(a.acceleration.y, 1);
  display.print(", ");
  display.print(a.acceleration.z, 1);
  display.println("");

  display.println("Gyroscope - rps");
  display.print(g.gyro.x, 1);
  display.print(", ");
  display.print(g.gyro.y, 1);
  display.print(", ");
  display.print(g.gyro.z, 1);
  display.println("");
  display.display();
  delay(100);
}

Now, while debugging when I disable Serial logs and comment all Serial.print then the above code runs properly, logo is displayed, accelerometer and gyro both the data are displayed on OLED properly.
Compiler Log for non-working code is:
Sketch uses 21980 bytes (71%) of program storage space. Maximum is 30720 bytes.
Global variables use 761 bytes (37%) of dynamic memory, leaving 1287 bytes for local variables. Maximum is 2048 bytes.
The setup I am using as Arduino Nano, MPU6050 connected over I2C (address 0x68), SSD1306 based 0.96" 128x64 display over I2C (address 0x3D). I am using A4 and A5 pin of Arduino Nano as I2C. Both device are connected over same bus. I am using breadboard for testing.
PS: Both the code compiles without error or warning

Where is the difference between those sketches?

Made the corrections, I made mistake while copying pasting the comments

The SSD1306 uses a lot of RAM. Pretty much all your RAM.  Serial also uses quite  a bit of RAM.  The two struggle to work together.
There is a special "text only" SSD1306 library that uses considerably less RAM: https://github.com/greiman/SSD1306Ascii

Thank you Majenko...
It was low RAM problem.
SSD1306 takes 1K, with MPU6050 the and serial print which I have included the remaining RAM is 5 bytes only, hence the initialization issue.
I followed simple guideline to reduce RAM footprint
Read this thread https://stackoverflow.com/questions/8649174/checking-memory-footprint-in-arduino
Code to print available SRAM.
Serial.print(availableMemory());

// free RAM check for debugging. SRAM for ATmega328p = 2048Kb.
int availableMemory() {
    // Use 1024 with ATmega168
    int size = 2048;
    byte *buf;
    while ((buf = (byte *) malloc(--size)) == NULL);
        free(buf);
    return size;
}