text:
None of the pins work as inputs
I’m using an Arduino-uno
I'm trying to read an PWM signal being output by pin 6.
I'm attempting to read it with pin A0.
5 volts are being supplied from pin 6 to a 300 ohm resister in series with one led.
This circuit returns to the analog input pin A0.
It'll admit it's a strange set up and I was told to use a pass through filter to read the signal.
At this point I'm not concerned with whether the program reads the right values,
so despite the code involving the serial monitor I'm just trying to figure out why the led won't turn on anymore.
As I stated in the sketch, this exact set up was working fine yesterday. The led was on and (accurate or not) there were consistent values being printed to the serial monitor.
I'm trying to figure out now what changed after I unplugged it last to create a now open circuit.

```

void setup() {

  Serial.begin(9600);
  pinMode(6, OUTPUT);
  // I  also tried setting the A0 pin as an input even though I thought you didn't have to and it didn't change anything.

}

void loop() {

  analogWrite(6, 255); // This pin is working as an output, I tested it to ground and led lights.

  int value = analogRead(A0); // I realize inputs are typically used for things like potentiometers
                              // But just as an example the LED should still turn on when connected here, correct?
                              //And it did the first few times I did it... maybe that was the problem?

  Serial.println(value);  // This was  all working previously. It just randomly stopped.
                          // Now this just prints random numbers and the circuit remains incomplete.
                          // Even if the input pins are not supposed to be used with 5 volts, Why was it working before then...
                          // ALSO it does not matter which pins you use for what...
                          // No current is running through the digital inputs with digital output set to HIGH.
                          // And No current runs through the analogInput pins when analogWrite is set to 255.
                          // Once again, I apologize if my terminology is off.

}
```

This is what I did to trouble shoot:
With the same sketch running on the board...
I connected a jumper from pin A0 to ground and the serial monitor switched from a bunch of random values to a solid 0. So it recognizes input still... in a sense.
Then I modified the sketch...
void setup() {

Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(8, INPUT);

}

void loop() {

// now I'm attempting to read a digital signal with the same circuit...
// Pin 6 is connected to a 300 ohm resistor in series with an led which returns to pin 8.

digitalWrite(6, HIGH);

int value = digitalRead(8);

Serial.println(value);

}

This gave the same result. The led wont turn on anymore unless the circuit ends are connected from a voltage source to ground.
Previously, any pins configured as INPUT would not only read consistent values but also complete the circuit, turning the led on.
Now the pins only recognize zero volts and do not complete any circuits. You can't even use a simple potentiometer if you wanted.
Each pin that can be configured as an INPUT acts the same way.
The only thing I did between the times when it was working and wasn't was unplug and plug in the board...

Please edit your post and show your sketch. Your terminology of "don’t even complete a circuit as inputs" is confusing. For example, a microphone is an input. How would expect that to complete a circuit?

However, when connecting the circuit to any pins configured as input, the light won’t even turn on... but it works fine connected to ground. - why do you expect an input to light an LED? That's like saying that when you connect your microphone to a computer it doesn't play sound.

Sorry for the confusion. I did not expect an input to light an LED, you're right that would be absurd. I figured some assumption could be made. My bad, The post is updated.

Re “I did not expect an input to light an LED”: You are contradicting yourself here. You previously wrote “when connecting the circuit to any pins configured as input, the light won’t even turn on... but it works fine connected to ground”. So you did expect the light to turn on.

Yes, connecting the end of the circuit. The other end is hooked up to a pwm source. Besides, right after that I state, "it doesn't work when connected to ground either". So your assumption would also imply that I thought a circuit with absolutely no power source should be able to turn on an led.

Sorry, "it does work when connected to ground". See, the original post IS confusing. That is why I updated it. Either way my point stands. It should not be hard for a person like your self to make the right educated assumption to that statement. Instead you assume people's ignorance's, pick out the all the discrepancies, and remain unhelpful. This is why forums are not as popular anymore. If you are genuinely confused and need anymore clarification I can do that, otherwise don't bother posting. It's a waste of time.

Re “It should not be hard for a person like your self to make the right educated assumption to that statement”: Sorry, I am not intelligent enough to read your mind: I am genuinely confused. Pointing out the discrepancies is a way to help you clarify your question. And that would be no luxury: my reading of your question is exactly the same as towe's and Nick Gammon's. Thus, if you think towe did not provide an appropriate answer, that means that you have at least three people confused as to what you really mean. Now, given the unfriendliness of your reaction, I will not try to help.

I'm still confused by your post. Maybe you can make a list of each scenario with a wiring diagram, a description and for each state, what you expected and what actually happened. Currently it is unclear to me, what is connected to what, when you expect the LED to light up

I don't mean to argue, but I too can not read your mind. What you said already was mentioned by yes, three people and cleared up. And the way you said it would give anyone a reason to assume "unfriendliness" on your end as well. You say you can not read my mind yet you literally state what you believe I am thinking. I was not assuming intelligence, I was assuming tone. Which I still think to be in your words "unfriendly". I respect that you do not want to help. However, respectfully, I do hope you realize the hypocrisy in your respons and just remember that there really was no point in this.

Chris, I can do that. I'll update it again in a little bit thanks.

Ok, now its a bit clearer. Tomorrow I will write an answer and discuss the situations, that you describe there. Now its time to sleep, where I live

So, finally, here's the problem. Your present circuit as described by you is connected as PIN6--> LED--> RESISTOR--> PIN8. Instead of connecting the resistor to PIN8 you need to connect it to ground. With the same code, to test input, connect a jumper wire from 5V to PIN8, you should see all 1's in the serial monitor. By connecting PIN8 to GND and you should see all 0s.

Please try to include some schematics and clearly state what you try to achieve and what actually happens. I’m confused by your description of the “problem” as it seems the circuit you describe behaves exactly like expected. Inputs behave like very high resistances. You can’t light an LED by connecting one of its legs just to an input, unless you connect a current/voltage source to that same leg/input as well.

Sounds like there's a basic misunderstanding here.
Setting a pin as "output" mean it'll either supply +5V ("HIGH") or 0V ("LOW"). Both those states are considered "outputs", and the pin can source or sink current in those states. When driven "LOW", the circuit does "input" current to the chip, but that's not what "input" usually means.
"Input" means you can use the pin to read the voltage applied to the pin. When connected to a PWM source, this might manifest as the pin quickly switching between "1" / "HIGH" / "+5V" and "0" / "LOW" / "0V".
Normally, you would use the "input" mode to read things like switches, or potentiometers on the analog input pins.
Your desired use of "current input" pins will require you to configure the pin as "output", and then set it to "LOW", which will make it able to sink current.

This seems very much to me to be the correct answer. An input pin does not "suck in current". It measures if it is there or not. As an analogy, a thermometer does not make things hot or cold, it measures if they are hot or cold.

Sorry for the confusion, I updated the post. I was attempting to use the analog input pins (either A0 - A5) to read the voltage from the circuit which I powered with a pwm source. So where I'd normally connect the end of the circuit to ground, I connected it to an analog input pin configured to "read" the voltage. It was working previously, can this not be done?

@User-2746 Does that mean you are trying read a PWM sicnal with analogRead()? That will not work as long as you don't use something like a low pass filter.

Yes, thank you. I will try this. I'm still slightly confused because previously using the same exact set up the led was on. Whether or not the PWM signal was being read properly due to no filter, I'm not sure, but the led it's self was working. It's like something changed from when I unplugged everything to when I tried it again the next day. Because now, with the same set up, the circuit is incomplete when connected from a PWM on pin 6 to the analogRead on pin A0... Which once again is the opposite to what it did originally.

I also updated it one more time for much needed clarification. It's a strange problem and I didn't explain it well enough.

The LED would glow only when the pin is configured as an OUTPUT or it would be very dim in INPUT mode. This is because INPUT mode sets the pin to a high impedance state, suitable for reading voltages and not for driving circuits requiring current.
Setting a digital pin to INPUT mode, allows you to only read voltages as 0 or 1  which correspond to 0V and 5V respectively. For example, upload the code below to your Arduino and open the serial monitor. Now, by connecting Pin 11 to GND the serial monitor should display 0, and by connecting it to 5V, it should display 1. If this doesn't work something may be wrong with the Arduino.
const int TESTPIN=11; //connect pin 11 to 5V and GND for testing

void setup() {

  pinMode(TESTPIN, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(digitalRead(TESTPIN));
  delay(500);
}

However, I would recommend that you share your code and diagram before concluding a fault in the Arduino.

Thanks for the input. I tried what you said and it helped explain the problem a little better. The monitor displayed "0" when connected to ground but the values are all random when supplied with voltage. I think your right, somethings wrong with the board. I updated my post adding this in. It's very strange that it just failed so randomly. It was working at first, then I unplugged it, plugged it back in the next day and now it doesn't.

Just to confirm, I hope you connected PIN11 directly to 5V using a jumper with nothing in between?

In your second update you described the following circuit:

simulate this circuit – Schematic created using CircuitLab
Then in code you are doing digitalWrite(6, HIGH);, which sets pin 6 to HIGH/1/true/5V. Pin 6 is configured as output, pin 8 as input. In this situation the LED will not light up. A pin, that is configured as input, will not draw or source current (except a very very small amount). The input pin behaves somewhat like a little capacitor to ground (so in principle nearly no current can flow). Thus no current is flowing through the circuit. No current also means, that the LED does not light up (it needs current for lighting up) and no voltage drop will happen on the circuit. The circuit will not be "completed", as you phrased it. Thus your input pin will also get HIGH/1/true/5V, which is what you then read on in the code.
When you instead change pin 8 to output (pinMode(8, OUTPUT);) and set it to LOW (digitalWrite(8, LOW);), the LED will light up, as now the voltage difference is the full 5V (from HIGH at pin 6 to LOW/ground at pin 8). If you now read the pin with digitalRead(8) you will just read, what you have written to it, meaning LOW/0/false/ground.
You might also have tried to use digitalWrite() with a pin, which is configured as INPUT. That does not really output anything. Instead it activates or deactivates the internal pullup resistor of the pin. As I remember, this pullup resistor is between 20 and 50 kΩ, so again you cannot get enough current to light an LED through that pin. The internal pullup resistor is then like an additional 20 to 50 kΩ resistor from the corresponding input pin to Vcc (5V in your case). If nothing else pulls on the pins value, the pullup resistor will pull the value of the input pin to HIGH/1/true/5V, so that you don't have a floating pin (see below for an explanation of that term).

The next scenario: Using analogRead()
Here you first tried to read an analog pin (A0), which was not connected to anything. That is called a floating pin. There is nothing, that gives this pin a definite value, thus it catches whatever electrical noise comes around, from the microcontroller, from other pins, from the circuit or from outside. A floating pin can change it's value rapidly and randomly, depending on the noise, which comes around. Thus you will get very different and varying values here.
Then you connected A0 to ground. That gives the pin a definite value (LOW/0/false/ground). Thus you now only read zero as value.
If you are doing the analogRead() with a circuit similar to the first case (with the LED between two pins) you will get a similar result as with digitalRead(). An analog input will also not source or draw any current (besides a very very small current). Thus you cannot "complete" a circuit to light an LED on the path.

I'm trying to read an PWM signal being output by pin 6. I'm attempting to read it with pin A0.

A PWM signal is nothing else than changing rapidly between Vcc (5V in your case) and ground. The value, that you give the PWM signal via analogWrite(), defines the duty cycle of the signal, meaning the ratio between the HIGH and LOW portions in the signal. The function name analogWrite() is unfortunately very misleading, as you don't really output an analog voltage. Most Arduinos don't have the hardware to do that, so analogWrite() uses PWM to output a pseudo analog voltage. Devices like motors are not fast enough to react to the fast voltage change, so you can change the speed with PWM. LEDs are fast enough, but the human eye cannot see the individual on-off cycles, so you see the LED being dimmed with lower values.
But the analogRead() function (which uses the ADC hardware internally) is fast enough, thus you would only read a series of changes between 5V and ground, when reading a PWM signal. You could build a low pass filter, which will filter out the PWM frequency and give you a real analog voltage, which you can then read via analogRead(). Though keep in mind, that this makes it slower, so you cannot read fast changes with that. A low pass filter looks like this:

simulate this circuit
The values come from the come from the comment of Edgar Bonet (thanks):

The PWM frequencies of the Uno are 977 and 490 Hz, below the cut-off of the filter you drew. Per the ADC's specification, you can safely increase R1 up to 10 kΩ, which should put the cutoff low enough to attenuate the PWM frequencies by at least 30 dB.

Though you might also want to read up the formula for the cut-off frequency. You can google terms like "RC low pass filter".
If you don't want to use extra hardware, but still want to read the PWM signal, you need to read the pulse length. For this there are multiple ways, depending on the requirements. You can use pulseIn(), you can use interrupts and take timestamps, you can use the capture mode of a hardware Timer.

As I stated in the sketch, this exact set up was working fine yesterday. The led was on and (accurate or not) there were consistent values being printed to the serial monitor.

Unfortunately this is not possible. The pins must behave like I described above. As electronics not break and then just magically unbreak, you must have done something different. An input pin (digital or analog) will not source or draw enough current to light an LED.

Now the pins only recognize zero volts and do not complete any circuits. You can't even use a simple potentiometer if you wanted.

You may have damaged something, though I cannot really say, if that is really the case or if you are just doing something wrong there. A potentiometer has to be connected like the following: The outer pins to ground and 5V respectively, the middle pin directly to the analog input. Nothing else. You might check, if that is, what you did.

Besides all that, you didn't really state, what you are trying to achieve. As you already acknowledged in your question, the described circuit is not typical and a strange setup. To light an LED, you would just connect it to the output pin (via the resistor) and on the other side to ground.

Nice answer! Just two comments: 1. The pullup is specified to be between 20 and 50 kΩ (not MΩ), with 30 kΩ being typical. 2. The PWM frequencies of the Uno are 977 and 490 Hz, below the cut-off of the filter you drew. Per the ADC's specification, you can safely increase R1 up to 10 kΩ, which should put the cutoff low enough to attenuate the PWM frequencies by at least 30 dB.

@EdgarBonet Ups, thanks for correcting. Thinking back, 50MOhm should have made me suspicious of my claim XD. I have included the 10kOhm value into the schematics and mentioned/cited you in the answer.

I got here with a similar problem to the OP, I see they didn't answer your question about what they wanted to achieve, I can't figure it out but I can explain what I was trying to do.  I have a toggle swtich on-none-on, and I want to have 2 leds, to indicate which one is on (yes I know I could just look at the switch :) ).
What I wanted to do was have the LEDs in-line with the input to the Arduino so that instead of using 2 pins for inputs from the switch and 2 pins as outputs for the LED's I could get away with just using the 2 input pins.


text:
Alternative to a delay so it can be interrupted
I have task which includes a 30s delay in the void loop. During this delay I want to be able to press a key on a keypad and have a message displayed on the serial monitor as an emergency stop. Since delays block code until they are done I thought I would be able to break them down into smaller sections so I could still press the emergency stop key in between them but of course that doesn't work. I've read through how to use the milis() function but from what I can gather it seems like it wouldn't work for my system as I need user input for it so the time from the start of the Arduino to me pressing the emergency stop button is different every time. Is there a way that isn't too complicated and would allow me to press the button during that 30s?
The delay is in if (key == '2') and the last part of the sketch is the emergency stop.
const int greenLED = 13;  //Declares greenLED as being connected to D13
const int redLED = 12;    //Declares redLED as being connected to D12
//
const int ButtonT1 = 11;    //Declare pin number for ButtonT1 as D11
int ButtonT1State = 0;      //Variable for reading ButtonT1 state
const int ButtonT2 = 10;    //Declare pin number for ButtonT2 as D10
int ButtonT2State = 0;      //Variable for reading ButtonT2 state
//
int count_value1 = 0;       //Variable for storing counter value for turnstile 1
int count_value2 = 0;       //Variable for storing counter value for turnstile 2
//
const byte ROWS = 4;        //Four row matrix
const byte COLS = 4;        //Four columns matrix
char keys [ROWS] [COLS] = { //Defines symbols on buttons of keypad
  {'1','2','3','A'},        //Defines ROW 1
  {'4','5','6','B'},        //Defines ROW 2
  {'7','8','9','C'},        //Defines ROW 3
  {'*','0','#','D'}};       //Defines ROW 4
  byte rowPins[ROWS] = {9, 8, 7, 6};  //Pin numbres of row pinouts of the keypad
  byte colPins[COLS] = {5, 4, 3, 2};  //Pin numbers of column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
//
void setup() { //Begin void setup, code runs once
 Serial.begin(9600);      //Begin serial transmission
 Wire.begin();            //Begin I2C wire communication protocol
 lcd.begin(16,2);         //Begin LCD with 16 columns and 2 rows
//
 pinMode(greenLED, OUTPUT);  //Set greenLED as an OUTPUT
 pinMode(redLED, OUTPUT);    //Set redLED as an OUTPUT
 pinMode(ButtonT1, INPUT);   //Set ButtonT1 as an INPUT
 pinMode(ButtonT2, INPUT);   //Set ButtonT2 as an INPUT
}
//
void loop() {                               //Begin void loop
   char key = keypad.getKey();              //Get a character key from the keypad
//
   //counter 1
    ButtonT1State = digitalRead(ButtonT1);  //Read the state of ButtonT1 -
    if (ButtonT1State == HIGH){             //Begin IF ButtonT1State is HIGH
      count_value1++;                       //IF buttonT1 pressed, increase count value
      Serial.println(count_value1);         //Print count_value1 on serial monitor
      delay(200);                           //Delay for 200ms, 0.2s
      digitalWrite(greenLED,HIGH);          //Set greenLED to HIGH,ON
      digitalWrite(redLED,LOW);             //Set redLED to LOW, OFF
 //
     if (key == '1'){                         //Wait until key '1' is pressed
    }                                         //End IF key == '1'
    ButtonT2State = digitalRead(ButtonT2);   //Read ButtonT2 state
    if (ButtonT2State == HIGH){              //Check if ButtonT2State is == HIGH
      count_value2++;                        //IF buttonT1 pressed, increase count value
      Serial.println(count_value2);          //Print count_value2 on serial monitor
      delay(500);                            //Delay for 500ms, 0.5s
//
    if(key == '2'){                            //Wait untill key '2' is pressed - confirm ride is ready
      Serial.println("Ride starting - 30s");   //Print message in brackets on serial monitor
//30s delay, broken into smaller delays
      delay(10000);
     Serial.println("20s left");
      delay(10000);
      Serial.println("10s left");
      delay(10000);
      Serial.println("Ride finished");        //Print message in brackets on serial monitor
      delay(100);                             //Delay for 1000ms, 1s
    }                                         //End if key == '2'
//
    if (key == '4'){                        //Wait until key '4' is pressed - emergency stop
      Serial.println("Emergency stop");     //Print message in brackets on serial monitor
      digitalWrite(redLED,HIGH);            //Set redLED to HIGH,ON
      digitalWrite(greenLED,LOW);           //Set greenLED to LOW,OFF
      lcd.clear();                          //Clear i2c LCD
      lcd.setCursor(0,0);                   //Set cursor to column 0, row 0
      lcd.print("Emergency stop");          //Print message in brackets on i2c LCD
      count_value2 = 0;                     //Set count_value2 to 0
      delay(1000);                          //Delay for 1000ms, 1s
    }                                       //End IF key == '4'
}

Three words: "Finite State Machine". Don't have any delays. Instead use millis() to decide when to do different actions.

@Majenko How do I use millis() to create a 30s delay without making it in intevals? I want the delay to start once a key on the keypad is pressed. Can I set the value to 0 when i press the key and then do the 30s interval?

Record the time when the button is pressed. Then look at the difference between the current time and that time to find how much time has passed. Like you would when boiling an egg. You don't sit staring at the clock, you look at it once and then glance at it regularly while doing other things until the 5 minutes has passed.

Make a statemachine.
Take a piece of paper and draw out the order of operation and each time you are waiting you specify what each button will do.
So for example each time button 1 is pushed you increment the counter and change the display.
When waiting for a timeout you check if(startTimestamp - millis() > timeout) for the next step.
Then give each waiting state a number and put a big switch on a global at the start of the loop() and update the global each time the state needs to change.

source: Stack Exchange

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

sort: votes


text:
SIM800C status LED not blinking
I am using an Allwin HW-537 SIM800C module. I am also using a 3.7V 2200mAH ICR18650-22F battery which discharges about 4-5 amps according to the datasheet.
However, I am unable to get the status LED on the module blinking.
I have tried using a multimeter to measure the voltage and it was 3.7V.
I did some digging and found a thread on a similar issue with the SIM800L Module where it was fixed by shortening the connection to reduce resistance.
I tried that and still, no luck. I also checked the LED and it works fine.
Am i doing something wrong? Or is the current too high?

5.18A? I'll bet you just put the probes straight across the battery to measure that, didn't you?

yes I did , that is a mistake i presume

Yes. You measure current through things, not across them. To measure current you should disconnect one of the power connections from the battery then connect the ammeter in between that power connection and the battery. Putting a DMM in amps mode (or any ammeter) directly across a battery is basically making a short circuit and will potentially damage both the battery and the DMM. You're lucky you didn't blow the fuse in the DMM at the very least.

Thank you very much. That is a great piece of advice. I am fairly new to electronics and this will help a great deal

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


text:
Adafruit_LEDBackpack library interfering with analog input reading
I'm trying to do something I think would be simple. I'd like to read the input of a electret microphone board and update the Adafruit 24-segment LED Bar Graph. I got each individual item working perfectly: I can read the input of the microphone on the analog pin and I can update the LED bar graph using I2C.
The issue occurs when I tried to combine the two concepts. When the bard graph gets updated, the analog input reads HIGH (1023) and never changes. I used my standard debug method and commented out code until the problem went away, so I've narrowed down the issue to a single line of code (right at the end). When the bar.writeDisplay is called the analog input perpetually reads 1023.
If I comment out that one line of code and re-upload my sketch the readings (in the Serial Monitor) are as expected (lower when its quiet and higher when its loud).
Under the hood Adafruit is using the Wire library.
I'm no good at wiring diagrams, but here's what I have:
RoboDyn Mega 2560 Pro (Embed)
5V, Gnd, SDA (20), SCL (21) to the LED Backpack
5V, Gnd, Out (A15/69)
That said, I'm relatively confident this is not a wiring problem as everything works until the software gets ahold of it.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"

Adafruit_24bargraph bar = Adafruit_24bargraph();

int pin = 69;
unsigned int sampleWindow = 50; // millis
unsigned int maxScale = 24;

void setup() {
  Serial.begin(9600);
  bar.begin(0x70);  // pass in the address
}

void loop() {
  unsigned long startMillis = millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level
  unsigned int sample;
  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;
  while (millis() - startMillis < sampleWindow) {
    sample = analogRead(pin);
    if (sample < 1024) {  // toss out spurious readings
      if (sample > signalMax) {
        signalMax = sample;  // save just the max levels
      }
      else if (sample < signalMin) {
        signalMin = sample;  // save just the min levels
      }
    }
  }
  peakToPeak = signalMax - signalMin;
  int displayPeak = map(peakToPeak, 0, 1023, 0, maxScale); // map 1v p-p level to the max scale of the display
  Serial.print("mic: "); Serial.print(peakToPeak); Serial.print(" "); Serial.println(displayPeak);
  for (uint8_t b = 0; b < 24; b++) {
    if (b <= displayPeak) {
      int c = LED_GREEN;
      if (b >= 20) {
        c = LED_RED;
      }
      else if (b >= 16) {
        c = LED_YELLOW;
      }
      bar.setBar(23 - b, c);
    }
    else {
      bar.setBar(23 - b, LED_OFF);
    }
    //bar.writeDisplay(); // <------- THIS LINE
  }
}

UPDATE: It appears to be something with the way Adafruit uses the Wire library. I have a similar problem when I use the Adafruit 7-segment library, when I use their MCP23017 library.
But it is wiring related too. If I uncomment the commented out line above but disconnect the I2C device the analog input starts working again.
One more thing I've discovered: it depends on how many lights are lit on the I2C board. Once all the lights are lit, the analog pin reads full. When only a couple of lights are lit, the values are lower. It is like the voltage going into the mic is higher when the lights are brighter.
For curiosity sake, I tried the same thing on a different Arduino (Adafruit Feather 32u4) with the same result (so it isn't my Arduino).

step one: comment out everything to do with the LED backback and see if it still gives 1023.

As I said, that's what I've already done. If I comment out just that one line, I get normal readings. If I leave that one line in, I get 1023.

I may have been too quick to say it wasn't a wiring problem. I also don't get the issue if I leave that line in the code and remove the led backpack from the breadboard. Perhaps the LED backpack is the issue. Maybe I messed up the soldering or maybe I got a bad board.

Ah, I missed that bit. My bad.

Can you post a photo of your breadboard setup?

Do I maybe need a resistor somewhere?

No, that all looks fine to me.

Does the supply voltage to the microphone and/or the microcontroller drop when the LEDs are on?

I found something similar https://esp32.com/viewtopic.php?t=2794

Does bending the micophone signal wire well away from the I2C wires make any difference?

You get 1023, what? The value of analogRead? The value of Peak-to-peak? I'd try using a different analog pin for the microphone. Also add a small delay after bar.writeDisplay();. Lastly; I'd try providing the microphone board with it's own power wires, instead of getting it from the bar-graph module.

Add up all the current needed to run your project. Double the number. That's the amperage you should use as a minimum for your power supply.  Guessing, say there are 24 LEDs at 3mA each. That's about 100mA?  Add another 50mA for the Arduino Uno and another 50mA for the microphone?  Totaled that's about 200mA?  So you're power supply should be rated for at least 1/2 Amp.  And you should double that if going through the analog Arduino regulator. BTW, USB power sources are only supposed to hand out 500mA. Beyond that they are allowed to drop voltage. That's a lot of guess work. Just try a big PS.

Since you cannot post a schematic I will take a SWAG and say you have two different hardware devices using the same pin for different reasons. I2C is a bus only and its associated pins cannot be used for anything else. Be sure the I2C bus is only connected to I2C terminals. Also be sure it is terminated properly.


text:
SPI register read returns 0x00 or 0xff
I am trying to interface a Arduino Uno with an ASM330LHH using SPI. Whenever I try to read any register, I either get 0xff or 0x00 on the serial monitor
The code I am using:
#include <SPI.h>

#define LOOP_DELAY 1000 //ms
uint8_t data;

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

  /* Refer datasheet for ASM330LHH
   * SPI freq max 10MHz
   * MSB first
   * SPI mode 3
   */
  SPI.begin();
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));

  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  Serial.println("Setup complete!");

}

void loop() {
  digitalWrite(10, LOW);
  byte masked_addr = 0x0F | 0x80;
  Serial.println(masked_addr, BIN);

  SPI.transfer(masked_addr);
  data = SPI.transfer(0x00);
  Serial.println(data, BIN);
  digitalWrite(10, HIGH);
  delay(LOOP_DELAY);
}

The output I get:
10001111
11111111
10001111
11111111
10001111
0
10001111
0

The expected output for the above code is 0x6B. What might have gone wrong?
Thanks in advance

add SPI.begin();

I'm not entirely sure it will matter in what you have currently, but SPI.begin() should happen before .beginTransaction()

begin must be called before beginTransfer and 10 MHz is to fast for an 16 MHz arduino. 1 MHz should be OK. It might be, that the library correct the 10 Mhz property to a suitable value.

Just as an aside, your data rate was probably fine.  The Arduino UNO's ATMega328P running 16 MHz, can't run the SPI clock faster than 8 MHz or slower than 125 kHz.  The rate will be clamped to this range, which most SPI devices will handle.  The slower rate is probably better while you're troubleshooting though.

Your ASM330LHH is a 3.3V device.  You should probably update the question to have a picture/diagram/schematic of however you're interfacing your 5.0V Arduino UNO to it.

I just connected the Arduino Uno to ADXL345 (Equivalent to ASM330LLH) to test the code. The code works fine. Maybe the ASM330LLH has gone bad. I need to check.

There is so much I can't see to have any confidence in that idea.  Just to drive the point home: You can't, in the general case, connect a 5V and a 3.3V device together and expect them to work or work reliably without /some/, however minor, consideration for the differences.  I'm just guessing you have breakout boards, and those boards may or may not being doing something helpful in interfacing the chip to the Arduino.  Beyond rearranging the pins I mean.


text:
TFMini Sensors with Arduino
I have three TFMini sensors I need all of them to detect. I only got one to work , pins 4,5 . My info in coding is basic . I really appreciate your help . Thanks in advance.
I think the problem is with Library I can't add TFMini_1.
Here is my code,
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfmini;
TFMini tfmini1;

//Declaring variables and constants
TFMini TFFront;
TFMini TFRight;
TFMini TFLeft;
SoftwareSerial SerialTFMini (4,5);    //(RX, TX)
SoftwareSerial SerialTFMini_1 (6,7);    //(RX, TX)
SoftwareSerial SerialTFMini_2(8,9);     //(RX, TX)

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if(SerialTFMini.available())

  {
    // Serial.println( "tfmini serial available" );
    rx[i] = SerialTFMini.read();

    if(rx[0] != 0x59) {
      i = 0;
    } else if(i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if(i == 8) {
      for(j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if(rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else
    {
      i++;
    }
  }
}

       //Threshold distance in "cm"; speak only when any object is nearer than this distance

void setup()
{

  //Initializing Baud Rates
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  SerialTFMini.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
tfmini.begin(&SerialTFMini);
}

void loop()
{
   int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while(!distance) {
    getTFminiData(&distance, &strength);
    if(distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
   }

delay(100);

}

First: Why are you including, declaring and initializing the library's tfmini object, if you then don't use it for reading the sensor?
Your problem will be, that you can only listen to exactly 1 SoftwareSerial interface at a time. If you listen to the first interface and the sensor on the second interface is sending something, you will miss that data.
I suggest, you switch the Uno for a board with more hardware Serial interfaces (which work via hardware, thus can work in parallel). The Arduino Mega for example has a total of 4 hardware Serial interfaces.
Though you might get away with the Uno when working with the external trigger mode. The TFMini library has an example named SingleReading. It sets the SingleScanMode in setup(). Then it issues an external trigger and then reads the sensor. I suggest trying the following: In your code you initiate all 3 TFMini objects with their respective SoftwareSerial object. Then in loop() you go through these 3 items, first calling listen() on the corresponding SoftwareSerial object. Then you issue the external trigger on the corresponding TFMini object and read the data from it. Then you go to the next SoftwareSerial interface and call listen() on it, and so on. The idea is, that with an external trigger you can control, when you will get a valid data frame. I'm not sure, if the sensor will also send some data between the triggers, but that data should just be discarded without any problem.
Note: I cannot test this idea, because I don't have the corresponding hardware. You will have to test that yourself.

I did try to use the Mega but I didn't even get one sensor to work .

@Soul Then you must have done something else wrong. You didn't show your code for the Mega, so I cannot say, what is the problem there. But of course you can try the external trigger mode with the Uno, as described above

I basically used the some code .

@Soul Then that is your problem. You cannot listen to multiple SoftwareSerial at a time, as described above. You need to change the code for the Mega, so that you use the Hardware Serial interfaces Serial1 to Serial4 and connect the TFMinis to the respective pins


text:
Finding Relatively Accurate Velocity Using an IMU
I am currently working on a project where I am trying to accurately find velocity in a handheld device using an IMU for about 30 seconds.
I have been having major issues doing this because of large amounts of drift from poor calculations due to inaccurate sensor readings.
I have tried tuning offsets for my sensor and using other sensor fusion libraries to find my linear acceleration.
At this point I don't know if I am doing something wrong, going about the process wrong, or if my sensors are just to inaccurate to accomplish this.
I am hoping if anyone may have recommendations on how to accomplish this from the ground up. I currently have two 9DOF IMUS listed below. The first one I tried to use the predefined linear acceleration function to find velocity in ndof mode, using bosch calibration steps. The second i spent hours tuning the offsets on to get linear acceleration and it came out much worse than the first sensor. For the second I can include code but I used the madgwick from the Adafruit_AHRS library for the sensor fusion for sake of time.
Any help is appreciated.

https://www.adafruit.com/product/4646 (BNo055 first board)
https://www.adafruit.com/product/3463 (FXOS8700 + FXAS21002 second board)

Integration of acceleration to derive velocity is a difficult task.  This is the first step in dead reckoning.  Consider some of the following options to improve accuracy:

Some IMUs can be adjusted to increase sample speed. If the
acceleration is sudden, more samples my improve the accuracy of the
calculated velocity.
Try aligning just 1 of the axes of the IMU chip in the direction of
acceleration. Do this to simplify the problem.  Depending on the
Arduino you are using, the processor may not have the power to
perform the trig functions necessary for anything except
acceleration only along 1 of the IMU's axes.
Take care of loosing significant digits.  If using integers, try
multiplying everything up.  For example instead of 1 equaling 1
meter multiply the value up such that 1000 equals 1.000 meters.  Now
integer math can be used to calculate down to the mm.

I do have it at the highest rate I can sample. Also unfortunately for my current project the imu is in a handheld device and therefore cannot be aligned in a easier fashion.

Hand held?  Then you need get data from all 3 accelerometers.  And do the math to add up the contribution of each to find the overall acceleration vector.  Then integrate that vector over time in to a velocity vector.  Maybe you can do this if you are clever on an Arduino Uno.  But it my be worth looking at the specific processor used on different Arduinos and picking the fastest most powerful one.  I think you should really start simple and then try to add complexity.  Hand held is really really hard.  A car would be easier as one can assume the car is always up right.

I actually have been doing the vector math. I believe the main issue is because of bad readings from the accelerometer or bad orientation algorithm, I am not able to subtract the gravity vector out without large error

This is 1 of several reasons I think it best to start simple and add complexity 1 step at a time.  Thinking, maybe it's time for a trick.  Warning, this will likely not work well over longer periods of time.  But for 30 seconds, why not try subtracting the long term average from the reading.  So at rest the device eventually zeros out.  The long term average will not be able to respond to sudden acceleration so such acceleration will be seen by the velocity calculation code.

Okay thank you I'll give this a shot and let you know how it goes

Checkout my post above as well i added more detail

For more context I did ask BOSCH directly about this issue and explained my setup in more detail.
https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BNO055-Outputting-Bad-Linear-Accel-Data/m-p/18976#M5212

Please edit this into your question and then remove it. "This space is for answers only".


text:
Why am I only getting -1 values in the Serial Monitor, when interfacing with the MPU 6050?
I am trying to smoke test my Seeeduino XIAO (Arduino-compatible) board with an IMU sensor, the MPU 6050. I mainly care about the accelerometer and gyroscope values.
But when I run my Arduino code on the XIAO, I am only getting -1 values in the Serial Monitor. When I first smoke tested the MPU 6050, I actually saw regular X,Y,Z values (e.g. 123, -456, etc), but it disappeared after a few readings. Both the microcontroller and IMU chips are able to power on, since they both display the LED light. The XIAO seems to display a blue LED light when it is transmitting/receiving data, but I am not entirely sure that is what is going on.
The MPU 6050 communicates via I2C, so I have connected Vcc to 3.3V on the XIAO since I read somewhere that the MPU 6050 runs on 3.3V, Gnd to Gnd, SCL to Pin 5 on the XIAO, SDA to Pin 4, and the INT pin to Pin 2 (not sure if I need the INT pin or not, but I read that it helped clear the buffer I think). Then I have the XIAO connected to my laptop's 5V USB port. Also not sure if I need to connect to 3.3V or 5V from the MPU to the XIAO.
Any idea why I am getting -1 values? I also occasionally get 0 values, but mostly -1s.
Here is a snippet of the output I am getting on the Serial Monitor:
12:06:32.476 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:32.578 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:32.681 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.057 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.159 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.465 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.566 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.738 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.841 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.014 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.390 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.492 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.596 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.699 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.903 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.378 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.480 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.584 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:37.064 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:37.710 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.122 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.257 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.393 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.529 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.664 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1

Here is the code I found on some tutorial website:
https://www.electronicshub.org/getting-started-arduino-mpu6050/
#include<Wire.h>
const int MPU6050_addr=0x68;
int16_t AccX,AccY,AccZ,Temp,GyroX,GyroY,GyroZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU6050_addr,14,true);
  AccX=Wire.read()<<8|Wire.read();
  AccY=Wire.read()<<8|Wire.read();
  AccZ=Wire.read()<<8|Wire.read();
  Temp=Wire.read()<<8|Wire.read();
  GyroX=Wire.read()<<8|Wire.read();
  GyroY=Wire.read()<<8|Wire.read();
  GyroZ=Wire.read()<<8|Wire.read();
  Serial.print("AccX = "); Serial.print(AccX);
  Serial.print(" || AccY = "); Serial.print(AccY);
  Serial.print(" || AccZ = "); Serial.print(AccZ);
  Serial.print(" || Temp = "); Serial.print(Temp/340.00+36.53);
  Serial.print(" || GyroX = "); Serial.print(GyroX);
  Serial.print(" || GyroY = "); Serial.print(GyroY);
  Serial.print(" || GyroZ = "); Serial.println(GyroZ);
  delay(100);
}

Attached is my current electronics setup. Yes, I know I should have used a breadboard, but I did not have one on me at the time. The connection was not stable, so maybe that messed with the readings.

-1 is usually all 1's and 0 is all zeros.  So it looks like you are not getting any data.  The code appears to be set up for an I2C device at address 0x68.  The 6050 can be set to appear at that address or at address 0x69.  What is pin 9 of the 6050 chip connected to?

Oh ok. I ran i2c device scanning code that I found online and it said the address at 0x68 was available, along with the rest of that address space. The 6050 only has 8 pins.

I am not sure what "running i2c device scanning code" means.  It sounds like the scan did not find anything at 0x68 and as such indicated that address was available. BTW, the 6050 chip has 24 pins.  The board the 6050 chip is soldered onto has 8 pins. For more help, you need to let us know where you got that board from.  As we need the board's schematic to do a good job at figuring this out.

Yes, the scan indicated that the address at 0x68 was available. Oh ok. Diymore 6DOF MPU-6050 GY-521. That's the name of the board.

A quick look around and I can not find the schematic.  If you know where to find one please let us know.  I did find this project which is what you are doing only they are using a real Arduino Uno board.  I am now wondering if the XIAO is as compatible as needed for this project.

The schematic and board look like this:
https://www.theengineeringprojects.com/wp-content/uploads/2019/02/mpu6050.jpg

Thanks @rmutalik but a schematic looks more like the image in the answer "There may be a couple of issues to consider:".  As the instructables.com project I linked to in that answer is connected just like your project is (and assuming that project is working) I would suggest you try to follow that project's instructions while using an Arduino Uno.  Again, this wouldn't be the 1st time a new Arduino board does not behave just like the original Arduino Uno.

Ok thanks, I will try that and then reply back to this post with my findings.

There may be a couple of issues to consider:

In the 6050 specification we see that the 6050 can be configured to show up at address 0x68 or 0x69.  In the photo there appears to be no connection to a pin (AD0?) which may control the 6050 address.  The code appears to expect the 6050 at address 0x68. (Note: The board the 6050 comes on may already deal with this issue by including a pull up or pull down resistor.)

An I2C bus normally needs pull up resistors on the data and clock lines as all drivers are normally of type open collector.  Here is part of a figure from the 6850's specification document:

(Note: The board the 6050 comes on may already deal with this issue by including 2 pull up resistor.)

Look for a working project which is the same or nearly the same as yours.  Here is a project that uses the same 6050 board connected to an Arduino Uno.

Consider if the libraries and other supporting software are truly abstracting your XIAO hardware (in this case an SAMD21CortexM0+ processor) (the real Arduino Uno uses a ATmega328P processor).  It would not be the first time trying to emulate an Arduino using different and more powerful processors has affected otherwise working sketches with unexpected behaviors.

Finally, there appears to be many schematics many with and a few without a 5 volt to 3.3 volt LDO regulators. It may be even with a Low Drop Out regulator that supplying the board with 3.3 volts will not result in 3.3 volts at the 6050 chip.  This may lead to problems.  But supplying a board with no regulator with 5 volts may damage the 6050 chip. Here is one of the schematics found:

(Note: In this schematic, the data and clock lines are pulled high on the board.  And pin 9 (AD0) of the 6050 chip is pulled low.)


text:
Arduino serial issue
My arduino mega should be communicating with another card (ANET8) and also with a DC resistance meter (with python code) using 2 serial ports, one using the USB(resistance meter) and the other one with RX and TX.
The Anet8 is sending a signal to trigger the MeasGo part in the code, and therefore with the Serial.print(A8flag) it triggers a measurment part in python, that measurement part in python sends in the Serial port a command that the arduino should read through Serial.readString and thus execute a function called "MuxRelayChoicee".
My problem is that, the part with " if Serial.available()>0 ... " is not working. I know it because my debug_pin1 is not made to HIGH.
Did i miss something ?
#include "pins.h"

#include <SoftwareSerial.h>

String flag, A8flag, sys;
int i;
int POW_RELAY_PIN=12;
int debug_pin = 38;
int debug_pin1 = 39;
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // set the digital pin as output:
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);

  pinMode(debug_pin, OUTPUT);
  pinMode(debug_pin1, OUTPUT);

  Set_Pins(); //to activate mux pins

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

  mySerial.begin(9600);
//  mySerial.setTimeout(500);
  while (!mySerial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

void loop() {

  if (mySerial.available()>0)
  {
     delay(50);
     String A8flag ="";
     A8flag=mySerial.readString();
     delay(50);

 if(A8flag.equals("MeasGO\n")){
     Serial.print(A8flag);
     delay(100);
     Serial.flush();
     digitalWrite(debug_pin, HIGH);

     if (Serial.available()>0)
     {

        String sys ="";
        sys=Serial.readString();
        delay(50);
        digitalWrite(debug_pin1, HIGH);
        MuxRelayChoice(sys);
 }
 }

Here is a part of the code i send with python :
if flag=="MeasGO":
      for n in range(4):
        ser.write(("sys"+str(n)+"\n").encode()) #Writing to the Serial port of Arduino
        time.sleep(1)
        data=mybk.query('FETCh?')
        time.sleep(1)
        t.append(time.time()-t0)
        print("sys"+str(n)+ '\n')
        res[n]=float(data[:13])*1000
        print(str(res[n])+'\t mOhm')
      with open(path+'csvfile.csv','a') as f:
          f.write(str(time.time()-t0)[:7]+'\t'+str(res[0])+'\t'+str(res[1])+'\t'+str(res[2])+'\t'+str(res[3])+'\n') #Give your csv text here.
      time.sleep(0.5)
      ser.write("MeasOK\n".encode())

Why are you using software serial, the Mega has 4 serial ports that work very nicely. Also to my knowledge the Softwareserial can only service 1 operating software serial channel at a time.

It seems likely that this code can be edited down to show the same problem using the Serial Monitor rather than python for send data and making no reference to AVET8 or MeaGo, whatever those are.  If the problem is principally about everything leading up to enter a conditional statement the first time, the body of the conditional statement is unimportant to the problem. If you don't find the problem yourself in this process, you'll have code that most anyone here can test themselves.

If you're unable to completely remove the python code from the troubleshooting process (you likely can), you may be able to at least shorten it and remove all of the unnecessary dependencies yielding complete and short python source that can be run by anyone wanting to help you with your arduino code.

This has nothing to do with anything, but SoftwareSerial::begin() sets the correct pin modes for the RX and TX pin numbers given in the constructor.  You needn't call pinMode for them yourself.  Ignoring the constructor bit, the same is true for your available HardwareSerial objects.  That can be removed from the code.


text:
Reading Multiple MPU 9250 Sensors using TCA9548A Multiplexer
I am trying to read multiple MPU 9250 sensors using TCA9548A multiplexer in ESP 32 and Arduino IDE. Has anyone done that successfully?
I am new to the  area of Arduino coding. I am trying to edit the code in this tutorial for MPU 9250 (https://www.bluedot.space/tutorials/connect-multiple-sensors-using-i2c-multiplexer/). I am facing issues with libraries and commands while shifting from BME 280 to MPU 9250.  Once  I am changing to MPU 9250 and trying to call instance MPU9250 IMU_0, I am getting error "no matching function for call to 'MPU9250", which I understand is because the library I've used doesn't support the call. I am unable to find alternate library or command. How can this be sorted out?
#include <Wire.h>
#include <MPU9250.h>
MPU9250 mpu_0;
MPU9250 mpu_1;
MPU9250 mpu_2;
MPU9250 mpu_3;

#define TCAADDR 0x70
void tcaselect(uint8_t i) {
  if (i > 7) return;

  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}
void setup() {
  Serial.begin(9600);
  Wire.begin();
  Serial.println(F("##############################"));
  Serial.println(F("Starting Initialization"));
  Serial.println(F("##############################"));

  //*************INITIALIZING FIRST SENSOR*******************************
  tcaselect(0);

  if (mpu_0.begin() != 0x68)
  { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("No"));}
  else
  { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("Yes"));}
  //**********************************************************************
  //*************INITIALIZING SECOND SENSOR*******************************
  tcaselect(1);

  if (mpu_1.begin() != 0x68)
  { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("No"));}
  else
  { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("Yes"));}
  //*********************************************************************
  //**********************************************************************
  Serial.println();
  Serial.println(F("##############################"));
  Serial.println(F("Initialization Finished"));
  Serial.println(F("##############################"));
  Serial.println();
  Serial.println();
}

"I am facing issues".  What issues?

Your code is nearly impossible to read.  You might consider editing your question and using the code formatting facilities on the page.

Which MPU9250 library are you using? Did you look at its examples to fix your code?

I see no question being asked

I am using MPU 9250 library from bolder-flights system. In the tutorial about multiplexer, they have used BME280 and BlueDot_BME280library. Once  I am changing to MPU 9250 and trying to call instance MPU9250 IMU_0, I am getting error "no matching function for call to 'MPU9250", which I understand is because the library I've used doesn't support the call. I am unable to find alternate library or command. What alternatives can I use or how can I achieve taking readings from Multiple MPU9250 simultaneously using a multiplexer?
Thanks

You need to adapt the example you're following to follow how the MPU library does its construction and setup.
Looking at the documentation for the MPU library you are using, you should change the definitions to:
MPU9250 mpu_0(Wire, 0x68);  // 0x69 if you pulled AD0 high

Then if you read further to the "Common Setup Functions" section, you'll see that this library's setup function has this behavior:

This function returns a positive value on a successful initialization and returns a negative value on an unsuccesful initialization

So you need to adapt that too:
Serial.print(F("MPU.1 detected?\t"));
if (mpu_0.begin() < 0) { // the examples assume zero is ok too
  Serial.println(F("No"));
} else {
  Serial.println(F("Yes"));
}

You'll save yourself some trouble if you use an array for your sensors too.
MPU9250 mpus[] = { MPU9250(Wire, 0x68), MPU9250(Wire, 0x68) };
const int num_mpus = sizeof(mpus)/sizeof(mpus[0]);

Then your initialization can be done with a loop:
for (int i = 0; i < num_mpus; ++i) {
   tcaselect(i);
   if (mpus[i].begin() < 0) {
     // ...
   }
 }

And you can do similar things for interacting with the sensor. e.g.:
for (int i = 0; i < num_mpus; ++i) {
   tcaselect(i);
   mpus[i].readSensor();
   Serial.println(mpus[i].getAccelX_mss());
   // ...
 }

Thankyou very much... I would try implementing these..


text:
Can I safely connect my A6 GPRS module to this 5V 2A phone adapter
I have an A6 GPRS module, and my Samsung phone power adapter has output of 5V and 2A. But it also says 9V and 1.6A

My Phone's Adapter
So would it damage my A6 GPRS Module if I plug this to it via the micro usb power port? (especially because it also says 9V)?

My A6 GPRS module

Although you have marked your question "Arduino-Uno" and "Arduino-Mega", it's not about Arduino.

@StarCat corrected.

That is an adapter that support USB Power Delivery (specifically USB PD rev. 2.0/3.0). So it will put out 5V, unless it's specifically asked to deliver 9V by the device that's plugged in. You device will never request this, so it will always get 5V.

The standard output for USB is 5V but there are some such chargers that will output more for enhanced charging output on devices that support it.
In this case the adapter will default to 5V and will only upgrade to 9V if the device requests it.  The GPRS module will not request 9V and so the adapter will continue to provide only 5V which is what you want.


text:
Fried 2 MKR Wifi 1010 after plugging them to a solar panel
I fried 2 MKR Wifi 1010 after powering them using a solar panel.
Here is the diagram:

Both were working fine as long as I used the LiPo battery and/or my macbook (using USB) as power sources. They were correctly detected and I could upload sketches.
Once I plugged the Solar panel + Voltage regulator to the MicroUSB port of the arduino and waited for the solar panel to be selected as the power source by the board, then it would not be recognized by the IDE anymore.
First board is not recognized by MacOS and Arduino IDE. Double tap Reset button has no effect on the "L" LED that remains turned off.
Second board is recognized by MacOS (By looking at System Information > USB) but not by Arduino IDE. When it is powered up, CHRG blinks a few seconds, then "L" LED pulses indefinitely. Double tap Reset button just turns off the LED while the button is pressed, but goes back to pulsing on release.
The sensor connected to the I2C pins is able to deal with both 3.3V and 5V, so it should work when getting 5V from USB and 3.3V from battery.
What could have damaged these 2 boards ?
Edit:
The voltage regulator operates at DC 9V - 36V (not sure why it is also labelled as 24V/12V) and outputs 5.2V / 6A.
I measured the output voltage once when the sun was hitting the panel and it was 5.2V.
The full product description is available at https://www.jzk-jzk.com/products/24v-12v-to-5v-5a-power-buck-module-dc-dc-step-down-power-supply-converter-with-led

Comments are not for extended discussion; this conversation has been moved to chat.


text:
how to control 2 sensor and 3 relay with fuzzy
i'm using fuzzy to decide how long the relay on pump on and i got some trouble for it he just looping on relay how should i do thats my code
    //---------Fuzzy 2.1 prelauch----------

//-----iNPUT SETPOINT-------
float inputec;
float inputph;

//----INPUT ERROR---------------
float ph;
float hasilec;

//----------fuzzy declare-------------
#include <Fuzzy.h>
Fuzzy *fuzzy = new Fuzzy();

//----fuzzy input Error pH-----
FuzzySet *LN        = new FuzzySet(-2, -2, -1.5, -1);
FuzzySet *FN        = new FuzzySet(-1.5, -1, -1, -0.5);
FuzzySet *SN        = new FuzzySet(-1, -0.5, -0.5, 0);
FuzzySet *ZERO01    = new FuzzySet(-0.5, 0, 0, 0.5);
FuzzySet *sp        = new FuzzySet(0, 0.5, 0.5, 1);
FuzzySet *FP        = new FuzzySet(0.5, 1, 1, 1.5);
FuzzySet *LP        = new FuzzySet(1, 1.5, 2, 2);

//----Fuzzy input error EC----
FuzzySet *N6       = new FuzzySet(-2, -2, -1.8, -1.6);
FuzzySet *N5       = new FuzzySet(-1.8, -1.6, -1.6, -1.4);
FuzzySet *N4       = new FuzzySet(-1.6, -1.3, -1.3, -1);
FuzzySet *N3       = new FuzzySet(-1.2, -1, -1, -0.8);
FuzzySet *N2       = new FuzzySet(-1, -0.7, -0.7, -0.4);
FuzzySet *N1       = new FuzzySet(-0.6, -0.4, -0.4, -0.2);
FuzzySet *ZERO02   = new FuzzySet(-0.4, -0.2, 0, 0);

//----Fuzzy Output phD-----
FuzzySet *ZERO1       = new FuzzySet(0, 0, 0, 2);
FuzzySet *SEBENTAR1     = new FuzzySet(10, 20, 20, 30);
FuzzySet *SEDANG1       = new FuzzySet(20, 30, 40, 50);
FuzzySet *LAMA1         = new FuzzySet(40, 50, 60, 60);

//---Fuzzy Output phU------
FuzzySet *ZERO2        = new FuzzySet(0, 0, 0, 2);
FuzzySet *SEBENTAR2    = new FuzzySet(5, 10, 10, 15);
FuzzySet *SEDANG2      = new FuzzySet(10, 15, 20, 25);
FuzzySet *LAMA2        = new FuzzySet(20, 25, 30, 30);

//---Fuzzy Output ABMIX------
FuzzySet *ZERO3         = new FuzzySet(0, 0, 0, 2);
FuzzySet *SEBENTAR3     = new FuzzySet(20, 40, 40, 60);
FuzzySet *SEDANG3       = new FuzzySet(40, 60, 80, 100);
FuzzySet *LAMA3         = new FuzzySet(80, 100, 120, 120);

//---------- EC declare---------------
#include <Wire.h>
#include "DFRobot_EC10.h"
#include <EEPROM.h>
int EC_PIN = A2;
float voltage, ecValue, temperature = 25;
DFRobot_EC10 ec;

//-----------PPM declare --------------
#include <EEPROM.h>
#include "GravityTDS.h"
#define TdsSensorPin A1
GravityTDS gravityTds;
float temperatureppm = 25;
float tdsValue = 0;

//--------------pH declare---------------
#include <Wire.h>
#include <EEPROM.h>
float ph_H;
int pHSense = A0;
int samples = 5;
float adc_resolution = 1024.0;

//---------POMPA-----------
int pump1 = 5;
int pump2 = 6;
int pump3 = 7;
float pompa1;
float pompa2;
float pompa3;
unsigned long prev_pump1    = 0;
unsigned long prev_pump2    = 0;
unsigned long prev_pump3    = 0;
unsigned long initiate_start = 0;
int pump_state1 = false;
int pump_state2 = false;
int pump_state3 = false;

//-------Deklarasi Fungsi--------
#include "Fuzzy_Rules.h"
#include "Fuzzy_Set.h"
#include "PH.h"
#include "TDS.h"

void setup()
{
  Serial.begin(9600);
  //----FUZZY INITIATE-------
  sets();
  rules();

  //-----PH INITIATE---------

  //-----PPM INITIATE----------
  Serial.begin(115200);
  gravityTds.setPin(TdsSensorPin);
  gravityTds.setAref(5.0);  //reference voltage on ADC, default 5.0V on Arduino UNO
  gravityTds.setAdcRange(1024);  //1024 for 10bit ADC;4096 for 12bit ADC
  gravityTds.begin();  //initialization

  //-----Pin Output-----
  pinMode(pump1, OUTPUT);// Ph Up
  pinMode(pump2, OUTPUT);// Ph Down
  pinMode(pump3, OUTPUT);// AB-MIX

  //---normally open------
  digitalWrite(pump1, LOW); // Ph Up
  digitalWrite(pump2, LOW); // Ph Down
  digitalWrite(pump3, LOW); // AB-MIX

}

void loop()
{
  //-------------Fungsi Read sensor-----------
  hasilppm();
  ph_s();

  ph = inputph-ph_H;
  hasilec = inputec - tdsValue;

  Serial.print("pH    ");
  Serial.print(ph);
  Serial.print("  ");
  Serial.print("EC ");
  Serial.print(hasilec);
  Serial.println("");
  Serial.print(ph);  Serial.print(" ");
  Serial.print(hasilec);   Serial.print(" ");
  Serial.println(" ");

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa1 = fuzzy->defuzzify(1);//pHDOWN
  float pompa2 = fuzzy->defuzzify(2);//pHUP
  float pompa3 = fuzzy->defuzzify(3);//ABMIX

  //-----------PUMP ALGORITHM--------------------
  long int pompa01 = pompa1*1000;
  long int pompa02 = pompa2*1000;
  long int pompa03 = pompa3*1000;

  unsigned long intiate_start = millis();

  //pompa1
  if(intiate_start-prev_pump1 > pompa01)
  {
    pump_state1 = !pump_state1;

    if(pump_state1)
    {
      digitalWrite(pump1, HIGH);
    }
    else
    {
      digitalWrite(pump1, LOW);
    }
    prev_pump1 = initiate_start;
  }

    //pompa2
  if(intiate_start-prev_pump2 > pompa02)
  {
    pump_state2 = !pump_state2;

    if(pump_state2)
    {
      digitalWrite(pump2, HIGH);
    }
    else
    {
      digitalWrite(pump2, LOW);
    }
    prev_pump2 = initiate_start;
  }

    //pompa3
  if(intiate_start-prev_pump3 > pompa03)
  {
    pump_state3 = !pump_state3;

    if(pump_state3)
    {
      digitalWrite(pump3, HIGH);
    }
    else
    {
      digitalWrite(pump3, LOW);
    }
    prev_pump3 = initiate_start;
  }

  Serial.println("Result= ");
  Serial.println("");
  Serial.print(" Pompa1 pHDOWN: ");
  Serial.println(pompa01);
  Serial.print(" pompa2 phUP  : ");
  Serial.println(pompa02);
  Serial.print(" pompa3 ABMIX : ");
  Serial.println(pompa03);
  Serial.println("");
  Serial.println("");
  Serial.println("");
  delay (2000);

}

im using NO on my relay thx for helping me
my library

https://www.codepile.net/pile/4Nvovokl [Fuzzy_Rules.h]
https://www.codepile.net/pile/96x8EO6y [Fuzzy_set.h]
https://github.com/DFRobot/DFRobot_PH  [PH]
https://github.com/DFRobot/GravityTDS  [TDS]
Fuzzy.h its eFFl library

some library its a standar library for using censor

what is the problem? ... it is unclear what this means ... just looping on relay ..... also, what is the code supposed to do?

Link to the library please.

@jsotola its just a looping on relay not on the censor and fuzzy for reading and calculating again

@EdgarBonet its to long i think

that is my logic
Logic-->
Set pompa1,2,3 to zero
Get fuzzy values
Clean up - make zero if equal or under 0.67-->
Check if any pumps need to run-->
Convert the run time in milisecs-->
Get the present time in milisecs-->
add that to the runtime for each pump-->
Turn the pumps on that need to turn on-->
Find the longest run END time of all the pumps-->
Loop in while for the longest pump run time-->
Turn off pumps as they reach end time--->
but its not get the off just looping on pumps--->

Please, edit your question, and add a link to the particular library you are using. Do not worry about the URL being long.

okay no problem

Please, do not re-publish the code of the library. Instead, add a link to the existing official Web site. It has a Web site, right? Or did you author the library yourself and never published it? Or did you get it on a floppy from a friend?

like fuzzyrules and fuzzy set im minimalize using my library but the some library like TDS and ph from another site let me check it again

Its done maybe like that


text:
controlling 2 sensor and 3 pump using millis
i make a 3 pump for output and im using millis for it, i want to stop if rach the intervalm now in my code its still looping not realy stop for it thx
int pump1 = 5;//pin D5
int pump2 = 6;//pin D6
int pump3 = 7;//pin D7
float pompa1;
float pompa2;
float pompa3;
unsigned long prev_pump1    = 0;
unsigned long prev_pump2    = 0;
unsigned long prev_pump3    = 0;
unsigned long initiate_start = 0;
int pump_state1 = false;
int pump_state2 = false;
int pump_state3 = false;

and after this this is my loop program
  //-----------PUMP ALGORITHM--------------------
  long int pompa01 = pompa1*1000;//interval pump1
  long int pompa02 = pompa2*1000;//interval pump2
  long int pompa03 = pompa3*1000;//interval pump2

  unsigned long initiate_start = millis();

  //pompa1
  if(intiate_start-prev_pump1 > pompa01)
  {
    pump_state1 = !pump_state1;

    if(pump_state1)
    {
      digitalWrite(pump1, HIGH);
    }
    else
    {
      digitalWrite(pump1, LOW);
    }
    prev_pump1 = initiate_start;
  }

    //pompa2
  if(intiate_start-prev_pump2 > pompa02)
  {
    pump_state2 = !pump_state2;

    if(pump_state2)
    {
      digitalWrite(pump2, HIGH);
    }
    else
    {
      digitalWrite(pump2, LOW);
    }
    prev_pump2 = initiate_start;
  }

    //pompa3
  if(intiate_start-prev_pump3 > pompa03)
  {
    pump_state3 = !pump_state3;

    if(pump_state3)
    {
      digitalWrite(pump3, HIGH);
    }
    else
    {
      digitalWrite(pump3, LOW);
    }
    prev_pump3 = initiate_start;
  }

Please, copy-edit your question: make complete sentences, and pay attention to grammar and punctuation. As it stands, it is really hard to decipher.

Side note: The variable names initiate_start and intiate_start are too similar, which makes the code confusing.

This is meant as a complement to Michel Keijzers' answer. I fully agree
with his assessment: code duplication is something to be avoided, as it
greatly hurts maintainability. And I sympathise with him feeling the
urge to implement this as a proper class. ;-)
I would argue, however, that between the simplistic version of the OP's
code, and the fully object-oriented one of that answer, there is an
intermediate step that is worth targeting as the next thing to learn. I
mean: arrays and loops.
Many cases of code duplication follow a pattern roughly like this:
// At the top of the sketch:
some_type data0 = some_value;
some_type data1 = some_other_value;
// etc.

// Within a function:
do_lots_of_stuff(data0);
do_lots_of_stuff(data1);
// etc.

where do_lots_of_stuff() may be a lot of code, rather than a single
function call (and it would indeed not be that bad if it was just a
function call).
The simple solution to this kind of code duplication is to put the
variables in an array, and process them by looping through the array:
// At the top of the sketch:
const int data_count = ...;
some_type[data_count] = {some_value, some_other_value, ...};

// Within a function:
for (int i = 0; i < data_count; i++)
    do_lots_of_stuff(data[i]);

Here is my attempt at applying this technique to the OP's code. Note
that, since there are multiple variables for each pump, we need multiple
arrays:
const int pump_count = 3;
const uint8_t pump_pins[pump_count] = {5, 6, 7};
const uint32_t pump_half_periods[pump_count] = {1000, 2500, 3200};

uint8_t pump_states[pump_count];  // LOW or HIGH
uint32_t pump_last_actuations[pump_count];  // time in ms

void setup() {
    for (int i = 0; i < pump_count; i++) {
        pinMode(pump_pins[i], OUTPUT);
    }
}

void loop() {
    unsigned long now = millis();
    for (int i = 0; i < pump_count; i++) {
        if (now - pump_last_actuations[i] >= pump_half_periods[i]) {
            pump_states[i] = (pump_states[i] == HIGH) ? LOW : HIGH;
            digitalWrite(pump_pins[i], pump_states[i]);
            pump_last_actuations[i] = now;
        }
    }
}

This removes all the duplication, and should be easier to maintain and
debug.
Once one is comfortable with this concept, I would argue the next step
in terms of building abstractions would be to bundle together all the
data relative to one pump into a struct. Then we would have a single
array (the elements of which are structs) instead of a collection of
arrays:
// Data structure describing a pump.
struct Pump {
    const uint8_t pin;
    const uint32_t half_period;  // half period in ms
    uint8_t state;               // LOW or HIGH
    uint32_t last_actuation;     // time in ms
};

const int pump_count = 3;

Pump pumps[pump_count] = {
// pin, half-T, state, last_actuation
    {5, 1000, LOW, 0},
    {6, 2500, LOW, 0},
    {7, 3200, LOW, 0}
};

The body of setup() and loop() would be very similar to the previous
version, but with pump_pins[i] replaced by pumps[i].pin and so on.
The third step in the abstraction ladder would be to embed the code that
handles the data structure with the data itself in a class, as shown
in Michel Keijzers' answer. With the proper methods defined, the main
sketch could be reduced to something like this:
#include "Pump.h"

Pump pumps[] = {
    Pump(5, 1000),
    Pump(6, 2500),
    Pump(7, 3200)
};

void setup() {
    for (Pump &pump : pumps)
        pump.begin();
}

void loop() {
    for (Pump &pump : pumps)
        pump.process();
}

I tried all these methods, and it turns out the first one (with a
collection of arrays) is the one that uses the least lines of code, and
the last one (with a class) uses the most. One could wonder then why use
more advanced abstractions, if they increase the amount of code one has
to type. The reason is, these abstractions become useful when the
program grows in complexity. On can put together all the code that deals
with the pumps in one place (maybe in a separate file), all the code
that deals with sensors in another place... and the main sketch that
puts all the pieces together remains simple.

what is a "half period in ms" ? is it a state time or what

@daffafaiz: The “period” is the time it takes the signal to repeat itself. The “half period” is half the period. “ms” is the symbol for “milliseconds”, a unit of time.

thx for that sir

and sir how if i erase the const it is able to edit isnt ?

@daffafaiz: Excuse me? Can you make a full sentence?

is the const in front of the uint32_t it's for fix data cant change anymore ?

@daffafaiz: Yes, it means we are not going to change that value. If your plan is to change it, then remove the const qualifier.

Note: this is not an answer (my previous version of the answer contained a problem, thanks Edgar Bonet for notifying and a fix for the remainder of the answer). However, I don't want to remove this answer as it may help in removing a lot of duplication. I took the liberty to convert it into a class.
It compiles, but I can't check the functionality but hopefully it helps you to continue. If there are problems, use write commands to send text to the serial to check the times and state.
Sketch:
#include  "Pump.h"

const int NR_OF_PUMPS = 3;

Pump pumps[NR_OF_PUMPS] =
{
  Pump(5, 1.0),
  Pump(6, 2.5),
  Pump(7, 3.2)
};

void setup()
{
}

void loop()
{
  process();
}

void process()
{
  for (int pumpIndex = 0; pumpIndex < NR_OF_PUMPS; pumpIndex++)
  {
    pumps[pumpIndex].Process(millis());
  }
}

Pump.h:
class Pump
{
public:
  Pump::Pump(int pin, float interval);
  void Process(uint32_t currentTime);

private:
  int _pin;
  float _interval;
  uint32_t _prevTime;
  bool _state;
};

Pump.cpp:
#include "Arduino.h"
#include "Pump.h"

Pump::Pump(int pin, float interval)
:
  _pin(pin),
  _interval(interval * 1000.0),
  _prevTime(0),
  _state(false)
{
}

void Pump::Process(uint32_t currentTime)
{
  if (currentTime - _prevTime > _interval)
  {
    _state = !_state;
    digitalWrite(_pin, _state ? HIGH : LOW);
    _prevTime = currentTime;
  }
}

Re “seems that the current time is always put into the prev variables”: the update of the prev variables is within the if condition that controls the actuation of the pump, which is fine. BTW, you forgot to update _prevTime in the example you provide.

@EdgarBonet Good catch, thanks for the improvements.

The
prev_pump3 = initiate_star make the loop forever ? Or what ?

Not that I know, however you have a problem with the typo in the intiate/initiate variable likely.

I solved the typo this however its still lopping :(

Add some print statements to see what's wrong, that's the easiest way to debug these problems

Re “_prevTime(millis())”: global constructors are called before the initialization of the Arduino core. I would avoid calling core functions at this time, even though millis() may be harmless. It is safe to initialize _prevTime to zero, which is the starting value of millis() anyway.

@EdgarBonet I thought about that indeed. I would think the start time is quickly anyway but it could matter. Initially I initialized _prevTime with a separate method during setup but that seemed a bit overdone, as this doesn't seem a time critical application anyway.

Okaaay let me add some println for this thx for helpin me


text:
ESP32-C3 - undefined reference to `esp_ble_gap_start_advertising'
I have a Bluetooth project for an ESP32 devkit and want to compile it for an ESP32-C3. I use the newest ESP32 Arduino core as a component with esp-idf and the following configuration for PlatformIO:
[platformio]
src_dir = src
default_envs = debug

# Common build environment that is used for each of the tasks
[env]
platform = espressif32
framework = espidf

board = esp32-c3-devkitm-1

# 4 MB module version
board_upload.flash_size = 4MB
board_upload.maximum_size = 4194304
board_build.partitions = partitions.csv

# Settings for serial upload
upload_speed = 921600
upload_port = COM2

# Settings for serial console
monitor_speed = 115200
monitor_port = COM2
monitor_filters = esp32_exception_decoder

# Additional packages
platform_packages =

# Aditional build scripts for all environments to run before (`pre`) and after (`post`) the main build script
extra_scripts =

# Common build flags for all environments
build_flags =

lib_deps =
    bblanchon/ArduinoJson@^6.18.0

[env:debug]
build_type = debug

build_flags =
    ${env.build_flags}
    -D DEBUG
    -D APP_VERSION_POST='debug'

lib_deps =
    ${env.lib_deps}

extra_scripts =
    ${env.extra_scripts}

[env:release]
build_type = debug

build_flags =
    ${env.build_flags}
    -D RELEASE

lib_deps =
    ${env.lib_deps}

extra_scripts =
    ${env.extra_scripts}

I use the following toolchain:
 - framework-espidf @ 3.40401.0 (4.4.1)
 - tool-cmake @ 3.16.4
 - tool-esptoolpy @ 1.30300.0 (3.3.0)
 - tool-idf @ 1.0.1
 - tool-mconf @ 1.4060000.20190628 (406.0.0)
 - tool-ninja @ 1.9.0
 - toolchain-riscv32-esp @ 8.4.0+2021r2-patch3

But I got the following error during the linking:
.platformio/packages/toolchain-riscv32-esp/bin/../lib/gcc/riscv32-esp-elf/8.4.0/../../../../riscv32-esp-elf/bin/ld.exe: .pio\build\debug\esp-idf\arduino-esp32\libarduino-esp32.a(BLEAdvertising.o): in function `BLEAdvertising::start()':
components/arduino-esp32/libraries/BLE/src/BLEAdvertising.cpp:247: undefined reference to `esp_ble_gap_start_advertising'
.platformio/packages/toolchain-riscv32-esp/bin/../lib/gcc/riscv32-esp-elf/8.4.0/../../../../riscv32-esp-elf/bin/ld.exe: components/arduino-esp32/libraries/BLE/src/BLEAdvertising.cpp:214: undefined reference to `esp_ble_gap_config_adv_data'
.platformio/packages/toolchain-riscv32-esp/bin/../lib/gcc/riscv32-esp-elf/8.4.0/../../../../riscv32-esp-elf/bin/ld.exe: components/arduino-esp32/libraries/BLE/src/BLEAdvertising.cpp:225: undefined reference to `esp_ble_gap_config_adv_data'

Update 1
A verbose build outputs the following command before the error appears:
riscv32-esp-elf-g++ -o .pio\build\debug\firmware.elf -T memory.ld -u esp_app_desc -u pthread_include_pthread_impl -u pthread_include_pthread_cond_impl -u pthread_include_pthread_local_storage_impl -u pthread_include_pthread_rwlock_impl -u include_esp_phy_override -u start_app -T sections.ld
-u __ubsan_include -T esp32c3.rom.ld -T esp32c3.rom.api.ld -T esp32c3.rom.libgcc.ld -T esp32c3.rom.newlib.ld -T esp32c3.rom.version.ld -T esp32c3.rom.newlib-time.ld -T esp32c3.rom.eco3.ld -u __assert_func -u vfs_include_syscalls_impl -T esp32c3.peripherals.ld -u app_main -u newlib_include_heap_impl -u newlib_include_syscalls_impl -u newlib_include_pthread_impl -u newlib_include_assert_impl -u __cxa_guard_dummy -u __cxx_fatal_exception --specs=nosys.specs -Wl,--Map=C:/Projects/firmware-loader/.pio/build/debug/Firmware-Loader.map -Wl,--cref -Wl,--gc-sections -Wl,--undefined=uxTopUsedPriority -Wl,--wrap=_Unwind_Backtrace -Wl,--wrap=_Unwind_DeleteException -Wl,--wrap=_Unwind_FindEnclosingFunction -Wl,--wrap=_Unwind_Find_FDE
-Wl,--wrap=_Unwind_ForcedUnwind -Wl,--wrap=_Unwind_GetCFA -Wl,--wrap=_Unwind_GetDataRelBase -Wl,--wrap=_Unwind_GetGR -Wl,--wrap=_Unwind_GetIP -Wl,--wrap=_Unwind_GetIPInfo -Wl,--wrap=_Unwind_GetLanguageSpecificData -Wl,--wrap=_Unwind_GetRegionStart -Wl,--wrap=_Unwind_GetTextRelBase -Wl,--wrap=_Unwind_RaiseException -Wl,--wrap=_Unwind_Resume -Wl,--wrap=_Unwind_Resume_or_Rethrow -Wl,--wrap=_Unwind_SetEnableExceptionFdeSorting -Wl,--wrap=_Unwind_SetGR -Wl,--wrap=_Unwind_SetIP -Wl,--wrap=__cxa_call_unexpected -Wl,--wrap=__deregister_frame_info -Wl,--wrap=__deregister_frame_info_bases -Wl,--wrap=__gxx_personality_v0 -Wl,--wrap=__register_frame -Wl,--wrap=__register_frame_info -Wl,--wrap=__register_frame_info_bases -Wl,--wrap=__register_frame_info_table -Wl,--wrap=__register_frame_info_table_bases -Wl,--wrap=__register_frame_table -fno-lto -fno-rtti -march=rv32imc -nostartfiles -Og -g2 -ggdb2 .pio\build\debug\src\Devices\JERRY\jerry.o .pio\build\debug\src\Devices\Memory\memory.o .pio\build\debug\src\Devices\TOM\I2CM.o .pio\build\debug\src\Devices\TOM\tom.o .pio\build\debug\src\Loader\loader.o .pio\build\debug\src\Version\version.o .pio\build\debug\src\main.o -L.pio\build\debug -LC:\.platformio\packages\framework-espidf\components\bt\controller\lib_esp32c3_family\esp32c3 -LC:\.platformio\packages\framework-espidf\components\esp_wifi\lib\esp32c3 -LC:\.platformio\packages\framework-espidf\components\esp_phy\lib\esp32c3 -L.pio\build\debug\esp-idf\esp_system\ld -LC:\.platformio\packages\framework-espidf\components\esp_rom\esp32c3\ld -LC:\.platformio\packages\framework-espidf\components\esp_wifi\lib\esp32c3 -LC:\.platformio\packages\framework-espidf\components\soc\esp32c3\ld -Wl,--start-group .pio\build\debug\esp-idf\esp_ringbuf\libesp_ringbuf.a .pio\build\debug\esp-idf\asio\libasio.a .pio\build\debug\esp-idf\protobuf-c\libprotobuf-c.a .pio\build\debug\esp-idf\esp_lcd\libesp_lcd.a .pio\build\debug\esp-idf\mdns\libmdns.a .pio\build\debug\esp-idf\protocomm\libprotocomm.a .pio\build\debug\esp-idf\cbor\libcbor.a .pio\build\debug\esp-idf\cmock\libcmock.a .pio\build\debug\esp-idf\unity\libunity.a .pio\build\debug\esp-idf\bt\libbt.a .pio\build\debug\esp-idf\coap\libcoap.a .pio\build\debug\esp-idf\esp_adc_cal\libesp_adc_cal.a .pio\build\debug\esp-idf\esp_hid\libesp_hid.a .pio\build\debug\esp-idf\wear_levelling\libwear_levelling.a .pio\build\debug\esp-idf\esp_local_ctrl\libesp_local_ctrl.a .pio\build\debug\esp-idf\esp_websocket_client\libesp_websocket_client.a .pio\build\debug\esp-idf\expat\libexpat.a .pio\build\debug\esp-idf\fatfs\libfatfs.a .pio\build\debug\esp-idf\freemodbus\libfreemodbus.a .pio\build\debug\esp-idf\spiffs\libspiffs.a .pio\build\debug\esp-idf\openssl\libopenssl.a .pio\build\debug\esp-idf\libsodium\liblibsodium.a .pio\build\debug\esp-idf\jsmn\libjsmn.a .pio\build\debug\esp-idf\mqtt\libmqtt.a .pio\build\debug\esp-idf\json\libjson.a .pio\build\debug\esp-idf\wifi_provisioning\libwifi_provisioning.a .pio\build\debug\esp-idf\arduino-esp32\libarduino-esp32.a .pio\build\debug\esp-idf\RAK3172\libRAK3172.a .pio\build\debug\esp-idf\app_trace\libapp_trace.a .pio\build\debug\esp-idf\app_update\libapp_update.a .pio\build\debug\esp-idf\bootloader_support\libbootloader_support.a .pio\build\debug\esp-idf\console\libconsole.a .pio\build\debug\esp-idf\cxx\libcxx.a .pio\build\debug\esp-idf\driver\libdriver.a .pio\build\debug\esp-idf\efuse\libefuse.a .pio\build\debug\esp-idf\esp-tls\libesp-tls.a .pio\build\debug\esp-idf\esp_common\libesp_common.a .pio\build\debug\esp-idf\esp_event\libesp_event.a .pio\build\debug\esp-idf\esp_gdbstub\libesp_gdbstub.a .pio\build\debug\esp-idf\esp_http_client\libesp_http_client.a .pio\build\debug\esp-idf\esp_http_server\libesp_http_server.a .pio\build\debug\esp-idf\esp_https_ota\libesp_https_ota.a .pio\build\debug\esp-idf\esp_hw_support\libesp_hw_support.a .pio\build\debug\esp-idf\esp_ipc\libesp_ipc.a .pio\build\debug\esp-idf\esp_netif\libesp_netif.a .pio\build\debug\esp-idf\esp_phy\libesp_phy.a .pio\build\debug\esp-idf\esp_pm\libesp_pm.a .pio\build\debug\esp-idf\esp_rom\libesp_rom.a .pio\build\debug\esp-idf\esp_serial_slave_link\libesp_serial_slave_link.a .pio\build\debug\esp-idf\esp_system\libesp_system.a .pio\build\debug\esp-idf\esp_timer\libesp_timer.a .pio\build\debug\esp-idf\esp_wifi\libesp_wifi.a .pio\build\debug\esp-idf\espcoredump\libespcoredump.a .pio\build\debug\esp-idf\freertos\libfreertos.a .pio\build\debug\esp-idf\hal\libhal.a .pio\build\debug\esp-idf\heap\libheap.a .pio\build\debug\esp-idf\log\liblog.a .pio\build\debug\esp-idf\lwip\liblwip.a .pio\build\debug\esp-idf\mbedtls\libmbedtls.a .pio\build\debug\esp-idf\newlib\libnewlib.a .pio\build\debug\esp-idf\nghttp\libnghttp.a .pio\build\debug\esp-idf\nvs_flash\libnvs_flash.a .pio\build\debug\esp-idf\pthread\libpthread.a .pio\build\debug\esp-idf\riscv\libriscv.a .pio\build\debug\esp-idf\sdmmc\libsdmmc.a .pio\build\debug\esp-idf\soc\libsoc.a .pio\build\debug\esp-idf\spi_flash\libspi_flash.a .pio\build\debug\esp-idf\tcp_transport\libtcp_transport.a .pio\build\debug\esp-idf\tcpip_adapter\libtcpip_adapter.a .pio\build\debug\esp-idf\vfs\libvfs.a .pio\build\debug\esp-idf\wpa_supplicant\libwpa_supplicant.a .pio\build\debug\esp-idf\mbedtls\mbedtls\library\libmbedcrypto.a .pio\build\debug\esp-idf\mbedtls\mbedtls\library\libmbedtls.a .pio\build\debug\esp-idf\mbedtls\mbedtls\library\libmbedx509.a -lbtdm_app -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lbtbb -lgcov -lc -lm -lstdc++ -lgcc -Wl,--end-group

Update 2
It looks like libbt.a isn´t linked. May this cause this issue? How can I fix it or where do I find the required part in the build system of pio?

Is there a way to see which components have been linked or tried to be linked in PlatformIO?

@NickS. please take a look at my updated question. I have inserted the last command output in verbose build.

CONFIG_BT_BLE_42_FEATURES_SUPPORTED=y

I have had a very similar issue just now. In short, the solution was to rename library file from .c to .cpp
Extended explanation. My platformio.ini:
[env:esp32doit-devkit-v1]
platform = espressif32
board = esp32doit-devkit-v1
framework = arduino

I am using third-party library which I build from source. This library is provided by two  "lib_name.c" and "lib_name.h" files, which I have put into a lib/lib_name/ directory according to Platformio README file.
It was failing during linkage until I renamed "lib_name.c" to "lib_name.cpp", header file remained untouched.


text:
Can we generate 20kHz tone with normal buzzer in arduino?
Can normal buzzer be used for generating high frequency audio and if this is possible then can normal microphone module be able to detect the same frequency range(15 kHz - 20 kHz).
Here is the specifications of this buzzer:-
Rated Voltage : 6V DC
Operating Voltage : 4 to 8V DC
Rated Current* : ≤30mA
Sound Output at 10cm* : ≥85dB
Resonant Frequency : 2300 ±300Hz
Tone : Continuous
Operating Temperature : -25°C to +80°C
Storage Temperature : -30°C to +85°C
Weight : 2g
*Value applying at rated voltage (DC)

That depends entirely on the response range of the transducers in question. Read the datasheets.

I am asking about cheap piezo buzzer

@astrick Please provide more information. For example a link to the product. Do you have just the piezo itself? We cannot really say much without knowing the product. Otherwise you would need to just test it. "Normal" microphones should also have a statement about the frequency range in their documentation. Otherwise again you would need to test yourself.

Piezo transducers have a resonant frequency, specified in the datasheet.

@Majenko this is having resonant frequency of 2300. Can it transmit more than that?

Only at very low efficiency, i.e, very quietly.

@astrick Are you sure, that this is a passive buzzer (which is directly driven by an AC signal)? The "Rated voltage: 6V DC" suggest, that it already sounds, when you apply just the 6V DC. That would mean, that it is an active buzzer, which creates the sound frequency itself. You cannot drive such a buzzer with your own frequency. You can test this, if you connect it to the 5V of the Arduino. It it sounds continuously in that case, it is an active buzzer

@chrisl Thanks for sharing this information. So that means I need to purchase a passive buzzer?

For 20kHz you need to buy a piezo transducer with a 20kHz resonant frequency.

What exactly is it you are trying to achieve?

@Majenko I want to transmit 20kHz sound and then receive it using microphone

No, that's what you think to want to do. Not what you want to achieve. Why do you want to transmit and receive 20kHz sound?

@Majenko Communication between 2 devices which we cannot hear

@astrick Then you want a pair of matched ultrasonic transducers, an amplifier / driver circuit and modulator circuit, and a band-pass filter / demodulator circuit. Not a speaker and a microphone.

An arduino is very well capable of producing a 20KHz signal. You can use a PWM signal on one of the PWM pins, generate the signal by alternating a pin high and low with a few microseconds in between or you can use a buzzer with an input signal that can play a continuous tone at a specified frequency. I really can't see if the module you show can generate a tone based on the input.
Detecting a tone, however is somewhat difficult. You need an analog microphone amplifier, an ADC (analog-to-digital-converter) and some processing to detect a frequency in the signal data.
The usual microphone modules that are sold for arduino's are mostly just noise detectors and generate a signal when loud noise is present.

Note that the PWM frequencies on the UNO are only 490 or 980 Hz, so the normal digitalWrite() approach won't work. If you are going to "roll your own" PWM as suggested, you can use any output.  The built-in ADC will work fine, but it uses 0-5 VDC range.  You can make a simple circuit to convert an amplified AC signal to this range. See https://www.daqarta.com/dw_rrll.htm

thanks Boggy, I completely missed the internal ADC. Because of the way that the ADC probably works internally, I doubt that you can sample this at more than 10kHz. We need at least 40 kHz to detect a 20kHz signal.

Hacky, the DaquinOscope that I mentioned can do burst sampling (1024 samples) at over 1 MHz for single-channel and over 47 kHz for 2 channels at 8 bits, and only slightly slower for 10 bits.  But you are correct if you are talking about interrupt-driven sampling, which tops out around 30 kHz.

As others have noted, the frequency range of the buzzer is given in the data sheet.  This is a mechanical property, like the tone of a bell; you can't change it electrically.  So if you really need to generate high frequency audio, you need a different type of device.  Something like a speaker whose output is controlled by its input signal.  You don't mention what you are planning on using this for, which might make a difference in your options.  There are inexpensive piezo tweeters that work in this range, but they typically have very ragged frequency responses.  Actually, most transducers in this range do, but dynamic types tend to be better, though more expensive and less efficient.
If you want to generate controllable high frequencies with Arduino, you might want to look at my open-source DaqPort sketch.  This is intended to be controlled by a computer over USB and includes data acquisition as well as generation, but the oscillator portion can run as a stand-alone.  The sketch is included with my Daqarta software, which is free for Arduino use.  Daqarta includes the Arduino_Oscillators mini-app, which is described here: https://www.daqarta.com/dw_rrss.htm   The oscillators are also used by the DaquinOscope mini-app https://www.daqarta.com/dw_rrss.htm which does simultaneous acquisition, but it uses the computer for display so it's not stand-alone.
Microphones should not be a problem; many inexpensive electrets can handle this range.  But we really need to know more about your plans.

Can I use this microphone for this ?

Astrick, I can't tell from those specs, which talk only about the preamp bandwidth and not the mic itself.  The photo shows a mic on the board, but never mentions it at all.  If you buy this and it won't go as high as you need, you might be able to replace the mic capsule.  You can get these at places like Digi-Key.  Make sure you get omnidirectional for the flattest response; directional mics have terrible responses.


text:
Unable to make a really basic sketch work
I've been learning how to encapsulate my code within functions, and one of the examples I worked on is a simple INPUT_PULLUP button. When I upload the sketch from the arduino website everything works, so I know it's not a hardware issue. However, with the code below the button will just not go LOW.
I just don't see what the issue is, and I'm feeling really hopeless that I can't even get the simple thing done. I would be grateful for any advice.
int button_pin = 2;
int button_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button_pin, INPUT_PULLUP);
}

void loop() {
  Button();
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state = LOW) {
    Serial.println(button_state);
  };
};

You have an error in the if statement. For checking equality, you need to use == (double equal sign). A single = is an assignment. So you are actually assigning the value LOW to button_state. And an assignment will return the value, that you assigned, in this case LOW, aka 0, aka false. Thus the if statement will never be entered

Thanks Chris, I will try this and report. I don't know what I would do without you people. I wasted several hours on this yesterday trying everything I could think of with no success.

#define button_pin 2  //defining button pin as pin 2
bool button_state = 0; //button state is either 0/1 so using bool
void Button();
void setup()
{
    Serial.begin(9600);
    pinMode(button_pin, INPUT_PULLUP); //Setting input as input pullup
}

void loop()
{
    Button();
}

void Button()
{

    button_state = digitalRead(button_pin); //Read button state
    if (button_state == LOW)
    {
        Serial.println(button_state); //print button state when it is low
    }
}

In your code, you have used = operator in place of == in the if loop. Just if you change it, it will start working also you can use my above code it is same as yours just I have made some minor changes such as using bool in place of int and use of #define in place of pin declaration where you used int

Thank you very much for taking the time to answer. It's really helpful and I appreciate it.

@ZhelyazkoGrudov I am glad it helped you out. Good luck :)