body:
I'm currently facing an issue using **delay()** and **millis()** functions in an external cpp file.
The issue is that when I used delay() in my main program (meaning .ino file) it works well but when I call the same function in an external cpp file, I'm stuck in the delay function. Concerning the setup, the .hpp linked to the used cpp is well included in the .ino file and the librairy Arduino.h is included in my cpp. I also tried to replace delay by a loop using millis but the value returned by millis is always 0.
I'm using an Arduino mega2560 and a water level sensor in the follwing example. The Arduino IDE version is 1.8.16.

Here is an extract from my ino file:

    #include <Arduino.h>
    #include "DS3231.h"
    #include "MyGardenClock.hpp"
    #include "sensors.hpp"
    #include <LiquidCrystal.h>
    #include "Keypad.h"
    #include <Wire.h>

    ///Time object creation
    DS3231 clock; //Clock object -> contains basic Real Time Clock functions
    RTCDateTime dt; //Struct from DS3231 lib - contains date and time
    mG_RTC myClock; //Object that contains specific clock functions to my project like printing date and time on the lcd...

    ///LCD object creation
    //--Pin allocation
    const int rs = 2, en = 1, d4 = 4, d5 = 7, d6 = 8, d7 = 10;
    //--LCD dynamic object creation
    LiquidCrystal* pLCD = new LiquidCrystal(rs, en, d4, d5, d6, d7);

    ///Keypad parametrization and object creation
    //Define col nb and row nb
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    //define the cymbols on the buttons of the keypads
    char hexaKeys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {52, 50, 48, 46}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {44, 42, 40, 38}; //connect to the column pinouts of the keypad
    //Keypad dynamic object creation
    Keypad* pKpd = new Keypad(makeKeymap(hexaKeys),rowPins,colPins,ROWS,COLS);

    ///Sensors object creation
    //WaterLvl Sensors
    //--Pin allocation
    const int WtrLvlAnalogPin = 8; //pin used to read value from water lvl sensor
    const int WtrLvlPowerPin = 35; //pin used to power the sensor before reading a value
    //--WaterLvl dynamic object creation
    Water_Lvl_Sensor* pWtrLvlSens = new Water_Lvl_Sensor(WtrLvlAnalogPin,WtrLvlPowerPin); //contains the delay and millis functions that don't work

    /////////// TEST FUNCTIONS ///////////
    void testLCD_Kpd(Keypad*,LiquidCrystal*); //test lcd and keypad
    void testWtrLvlSens(Water_Lvl_Sensor*,LiquidCrystal*); //test water lvl sensor

    void setup()
    {
        Serial.begin(9600);
        pLCD->begin(16,2);
        testLCD_Kpd(pKpd,pLCD);
        testWtrLvlSens(pWtrLvlSens,pLCD);

    }

    void loop()
    {

    }
    ////////////////////// TEST FUNCTIONS ///////////////////////////
    void testLCD_Kpd(Keypad* pKpd, LiquidCrystal* pLCD)
    {
       char test;
       test ='i';

       pLCD->print("Hello");
       do
       {
        test = pKpd->waitForKey();
       }while(test=='i');
       pLCD->clear();
       delay(3000); //This one work well
       pLCD->print("test = ");
       pLCD->print(test);

    }

    void testWtrLvlSens(Water_Lvl_Sensor* pWLS,LiquidCrystal* plcd)
    {
      int wtrLvl;
      wtrLvl = pWLS->getCurrentWaterLvlValue();
      plcd->setCursor(0,1);
      plcd->print("wtrLvl = ");
      plcd->print(wtrLvl);

    }

Here is an extract from my cpp file:

    #include <Arduino.h>
    #include "sensors.hpp"

    /********************************************
    *   CLASS WATER LvL SENSOR DESCRIPTION      *
    ********************************************/
    ///Constructor
    //-- Assign pin number (analog & digital)
    //-- Define pinMode for VCC + set to low
    //-- read and store actual waterLevelValue as initial val
    Water_Lvl_Sensor::Water_Lvl_Sensor(int anPinNb, int DigPinNb)
    {
      //Variable used for millis
      unsigned long prevTime;
      unsigned long currentTime;
      const unsigned long delayTime = 100;

      Serial.begin(9600); //to debug

      //Assign analog and digital pin numbers
      analogPinNumber = anPinNb;
      VCC_digitalPinNumber = DigPinNb;
      pinMode(VCC_digitalPinNumber, OUTPUT); //Digital pin to power the sensor
      digitalWrite(VCC_digitalPinNumber,HIGH);//Turn sensor ON before reading initial value

      //delay(100); //not working ???
      prevTime = millis(); //get and store actual time
      do
      {
        currentTime = millis(); //get actual time
        Serial.println(currentTime); //print actual time (debug only)
      }while(currentTime<(prevTime+delayTime)); //while time spent < 100

      currentValue = analogRead(analogPinNumber); //read analog value

      digitalWrite(VCC_digitalPinNumber,LOW); //turn sensor OFF
      historyValue = currentValue; //init history val
      minValue = 0; //default value - sensor dry
      maxValue = 520; //default value - sensor under water
    }

Does anyone has a solution?

I hope I've given enough details. If not, please feel free to ask.

Thanks!

title: Delay() and millis() functions don't work in cpp external files

Answers: 1

body:
The Arduino framework does some initializing for you before going into `setup()` and `loop()`, for example configuring Timer0 correctly for `millis()`, `delay()` and siblings. This is done in the `main()` function, which then after the first initializing calls `setup()` and `loop()`.

But the creation of globally defined objects (and thus the execution of their constructors) is done even before the `main()` function. At that time neither `millis()`, nor `delay()` will work, since the hardware Timer0 is needed to be configured correctly for them to work. The hardware timer generates interrupts with a specific frequency and in the corresponding ISR (Interrupt Service Routine) the variable for `millis()` is incremented. If the Timer0 isn't configured, it's interrupt cannot trigger and thus `millis()` will stay zero. So you cannot do all that in the constructor of the object, or you always need to create the object in `setup()` or `loop()`.

For this very reason most hardware related Arduino libraries use a `.begin()` method to initialize the hardware related stuff. That function can be called on the global object in the `setup()` function, when everything else is already configured correctly.

**What to do now?** Create a `.begin()` method for your class. Move all the code from the constructor (except for the pin number assignment) into this `.begin()` function. And then call that function in `setup()`.


body:
I read this answer https://arduino.stackexchange.com/a/51878 to a different, but related question. It seems like VIN on the NodeMCU is directly or via diode connected to the USB connector.

![](https://i.stack.imgur.com/AW6ER.png)

Image source: https://arduino.stackexchange.com/a/76119

I'm going to run my NodeMCU with a 5 V power supply connected to the USB connector. And I also need approximately 5 V for another part. So I was thinking of connecting it to VIN of the NodeMCU. So I don't want to power the NodeMCU from VIN, but I want to draw power from VIN for another part.

Is that a bad move or perfectly fine? And if it's okay, how do I find out the maximum current? Because I think the line from USB connector to VIN has some limits, so to not damage the board?

title: How do I find out the maximum current through VIN on a NodeMCU board?

Answers: 2

body:
Just found at least a partial answer in this answer https://arduino.stackexchange.com/a/61030 to a different question:

> The component that blew up is a diode. It is designed to protect the USB from voltage being injected into the board. That diode can handle an absolute maximum of 1A. (...) the ESP8266 itself can take more than half that 1A power budget when communicating.

That sounds to me that beginning at about 500 mA, I will risk damaging the NodeMCU if I use VIN as a power supply. So to play it safe, I should probably stay below 250 mA...? Just a guess though. Not a perfect answer yet.

body:
You cannot power items from the VIN pin of the NodeMCU V3.

The power circuit is like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/wXlJs.png)

<!-- End schematic -->

As you can see no current can flow out of the VIN pin because of diode D2.

You could, though, draw current out of the VU pin, though (situated at the top left of the board when the text is normally oriented) which is directly connected to the USB port's 5V pin.  How much current can you draw? Well, there's nothing in the circuit to limit it, so whatever the USB port that the board is connected to will provide (less enough to run the ESP8266 module).

If you want to draw 1A through the VU pin and the power supply is rated for 2A there should be no problem. The traces for the VU pin are *reasonably* chunky.

A better solution though would be to power the NodeMCU board and your external components through separate power feeds from the power supply - that way there can be no interference from the board.


body:
Where are the source files containing the definitions and the HAL functions located for the Due?

I am trying to do CMSIS programming.

title: Where are source files for Due?

Answers: 1

body: The Arduino Core for supporting Arduino Due is called ArduinoCore-Sam, which can be found at https://github.com/arduino/ArduinoCore-sam, inside the `system` directory, you will find the CMSIS device driver.


body:
Heres the code i've Wrote i feel like the issue lies in how ive used the if statement

    int ledPinS = 13; //Classifies pin 13 as Connected to an LED
                    //Flashes every second
    int ledPinM = 12; //Classifies pin 13 as Connected to an LED
                    //Flashes every minuite

    byte seconds;

    byte minutes;

      void setup() {
       pinMode(ledPinS, OUTPUT);
       digitalWrite(ledPinS, LOW);
       pinMode(ledPinM, OUTPUT);
       digitalWrite(ledPinM, LOW);
      }

        void loop() {
         while (seconds<=59){//flash every second and reset when Seconds =59
         delay(900);
         digitalWrite(ledPinS,HIGH);
         delay(100);
         digitalWrite(ledPinS,LOW);
         seconds++;
        }
     delay(200);   // flash ledPin M Once when Seconds = 59
     digitalWrite(ledPinM,HIGH);
     delay(100);
     digitalWrite(ledPinM,LOW);
     seconds = 0;
     minutes++; // add a minute
     if(minutes=5){ // if minutes = 5 flash ledPinM twice and reset
              delay(200);
            digitalWrite(ledPinM,HIGH);
            delay(100);
            digitalWrite(ledPinM,LOW);
            delay(200);
            digitalWrite(ledPinM,HIGH);
            delay(100);
            digitalWrite(ledPinM,LOW);
            minutes = 0;
        }
    }

Any Help would be Appreciated.

title: Trying to program a Led Counter Want a Led to flash every 5 minutes however it flashes twice every second (Noob)

Answers: 1

body:
Although your code is formatted horribly, it does appear to be mostly correct.

I also  recommend making your pin numbers "const int". This tells the compiler that they cannot be changed. Otherwise you could change those values in your code accidentally.

You also have un-initialized variables. Best practice would be to declare and initialise them at the same time. E.g.

    byte seconds = 0;

Props for adding comments, though. Well done there.

You need an extra equals sign in your if statement.

    if (minutes = 5) {

should be

    if (minutes == 5) {

Classic mistake. We've all done it. You are assigning the value of 5 to minutes instead of checking for equality. This will always return true.


body:
I would like to save the height of a tank in case of power outage with EEPROM and every time I reboot the board. However, I could not do so after using EEPROM.commit() , EEPROM.get and EEPROM.put as the reading of the height tank changes every time I tried to reboot it . Am I using it wrongly?

I used EEPROM.get , EEPROM.put , EEPROM.commit in the void setup section so that it will save the data during boot up. However, the tank height just change whenever I changed to a different tank with different height after boot up.

How could I recalibrate the height of the tank if I would like to change to another tank one day, can I just click the RST button on the ESP8266 board?

Thank you

```
#include <LiquidCrystal_I2C.h>  //1602 LCD library
#include <Wire.h>
#include <EEPROM.h>
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>  //NodeMCU ESP8266 library
#include <BlynkSimpleEsp8266.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

WidgetLED led1(V2);

char auth[] = ""; //Enter your Auth token
char ssid[] = ""; //Enter your WIFI name
char pass[] = ""; //Enter your WIFI password

BlynkTimer timer;
bool pinValue = 1;

long duration;
int distance;
int percentage;
int addr=0;
float tankheight, val;

#define trig D7
#define echo D8
#define relay D5

void setup() {
  Serial.begin(9600);
  EEPROM.begin(512);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(relay, OUTPUT);
  Wire.begin(D2, D1);
  lcd.init();
  lcd.backlight();
  Blynk.begin(auth, ssid, pass);
  digitalWrite(trig, LOW);
  delayMicroseconds(4);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  tankheight = duration * 0.034 / 2;
  Serial.print("Tank height");
  Serial.print(tankheight);
  EEPROM.put(addr, tankheight);
  EEPROM.commit();
  val=EEPROM.get(addr, tankheight);
  Serial.print("Addr");
  Serial.print(val);
  timer.setInterval(1L, Wlevel);
  digitalWrite(relay, HIGH);
}

BLYNK_CONNECTED(){
  Blynk.syncAll();

  }

BLYNK_WRITE(V0) {
  pinValue = param.asInt();

}

void loop() {
  Blynk.run();
  timer.run();
  WiFi.setSleepMode(WIFI_NONE_SLEEP);

}

void Wlevel(){  // Initialize detecting water level and relay)
  {
  digitalWrite(trig, LOW);
  delayMicroseconds(4);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2;
  percentage= map(distance,val,10 ,0, 100);

  Blynk.virtualWrite(V1, percentage);

  if(percentage<0)
  {
    percentage = 0;
  }
  else if(percentage>100)
  {
    percentage = 100;
  }

 }

 if (pinValue == 1)
    {
       if (percentage < 100)
       {
          digitalWrite(relay, LOW);
          Serial.print("Water level:");
          Serial.print(percentage);
          Serial.print("%");
          Serial.println(" Pump is ON");
          led1.on();
          lcd.setCursor(0,0);
          lcd.print("Water Lvl:");
          lcd.print(percentage);
          lcd.print("%  ");
          lcd.setCursor(0,1);
          lcd.print("Pump: ON  (AUTO)");

       }

       else
       {
          digitalWrite(relay, HIGH);
          Serial.println("Water level is 100%   Pump is OFF");
          led1.off();
          lcd.setCursor(0, 0);
          lcd.print("Water Lvl:");
          lcd.print(percentage);
          lcd.print("%  ");
          lcd.setCursor(0,1);
          lcd.print("Pump: OFF (AUTO)");

       }
    }
   else
    {
      digitalWrite(relay, HIGH);
      Serial.print("Water level:");
      Serial.print(percentage);
      Serial.print("%");
      Serial.println("System is OFF, Check Blynk");
      lcd.setCursor(0,0);
      lcd.print("Water Lvl:");
      lcd.print(percentage);
      lcd.print("%  ");
      lcd.setCursor(0,1);
      lcd.print("System is OFF   ");
      led1.off();

    }

   }

title: How to save sensor value in EEPROM? (ESP8266)?

Answers: 1

body:
Use a different button - you may have to wire something up...

In the loop, read the button and only if it is pressed should you re-calibrate and set the value to eeprom.  You can do it in setup too but then you would have to reboot with the button pressed to trigger re-calibration.

You can also read a serial command in the loop.  Anything external that can be triggered with a separate intent to re-calibrate would work.  A power outage resembles the normal reset too much.  To execute different behavior in two different scenarios, you must be able to detect which scenario you are in.


body:
I'm super new to the c++ programming world (currently taking the class now) and I'm in need of some assistance with some coding that's way beyond my knowledge at the moment. I have to write a code for Arduino interfacing with servo motor, ezButton, water-proof sensor and ada fruit motor shield.

the project entails building a moveable arm that holds a hot metal post that needs to be submerged into water for cleaning, BUT before it can be submerged I need to give the metal time to cool so it doesn't fracture. (Question 1, how do I delay the servo motor from moving to allow the metal to cool.) After the metal is submerged for cleaning, the servo motor needs to move back to the starting position ONLY if the temperature is less than 50 degrees Celsius. (Question 2, how do I make the servo motor dependent on temperature.)
```

#include <OneWire.h>
#include <DallasTemperature.h>
#include <AFMotor.h>
#include <Servo.h>
#include <ezButton.h>

#define ONE_WIRE_BUS 2
#define LOOP_STATE_STOPPED 0
#define LOOP_STATE_STARTED 1

OneWire oneWire (ONE_WIRE_BUS);
DallasTemperature sensors (&oneWire);

ezButton button(7);
int loopState = LOOP_STATE_STOPPED;

Servo name_servo;
int servo_position = 0;
int Celsius = 0;

void setup() {
  sensors.begin();
  Serial.begin(9600);
  name_servo.attach (10);

  button.setDebounceTime(50);
 }

void loop() {
  button.loop();

if (button.isPressed()) {
    if (loopState == LOOP_STATE_STOPPED)
      loopState = LOOP_STATE_STARTED;
    else // if(loopState == LOOP_STATE_STARTED)
      loopState = LOOP_STATE_STOPPED;
  }

if (loopState == LOOP_STATE_STARTED) {
    sensors.requestTemperatures();
    Celsius = sensors.getTempCByIndex(0);
    Serial.print(Celsius);
    Serial.print(" C  ");
    delay(1000);

//ADD COOLING PERIOD (3min)

  for (servo_position = 0; servo_position <=180; servo_position +=1){
      name_servo.write(servo_position);
      delay(10);
      ;
   }

// ADD CONDITIONAL STATEMENT (if temp < 50, motor returns from 180 to 0)

  for (servo_position=180; servo_position >= 0; servo_position -=1){
      name_servo.write(servo_position);
      delay(10);

    }
  }
}

```

title: 1.) How do I delay a servo motor from turning in a loop? 2.) How do I make a servo motor's change in position dependent on temperature?

Answers: 0


body:
I understand how compiler compile our code to make binary code. Then we can use avr gcc to upload bin code to atmega chips via programer (USB ISP) or via USB serial (required bootloader).
I'm using ESP32 for a while and notice they work in difference way. As far as I know
1. It  not required Arduino  bootloader.
2. It not reset when re-open serial monitor.
3. It use external memory chip.
4. It have boot and reset button
5. The USB Serial connect to ESP32 and we can upload bin code with it. (maybe the only way)
6. In IDE it run python scrip (esptool.py)
I wonder how the process going and how each element work for its part for completely understand the process.

title: How Arduino IDE work with ESP32?

Answers: 1

body:
The ESP32 has a bootloader that uses serial embedded in its internal ROM. Whether that bootloader runs or not depends on the state of certain IO pins when the ESP32 starts up.

Those states are controlled by a small circuit that is triggered by the serial control lines (DTR and RTS).

On the Arduino there isn't that requirement, and the bootloader always runs when the chip resets, so a much simpler circuit is used to trigger a reset using just the DTR signal.

So for an Arduino whenever the serial port is opened the DTR signal resets the board. But for the ESP32 the RTS signal also has to be asserted along with the DTR signal in the right sequence to both set the correct IO pins and to reset the chip.

Whether the target device has internal flash or an external flash chip makes no difference. It is the bootloader's job to get the data into that flash. The AVR chips have a way of interfacing with the internal flash (ISP) to program it without a bootloader, but the ESP32, as it has external flash, doesn't need that (you can interface directly with the flash chip if you so wish).

The software on the PC that communicates with the bootloader has to speak the "language" the bootloader expects. Each family of chips has its own bootloader (some don't even have a bootloader, but that's another story) which speaks its own language. On the AVR chips that's usually a variant of the STK500 protocol, and the program `avrdude` is what communicates with it to send the program to flash. On the ESP32 (and the ESP8266 too) it's `esptool.py` that does the job. On chipKIT boards it's `pic32prog`. On Digipark it's `micronucleus`. There's as many upload programs as there are families of boards. Some programs, like `avrdude` and `pic32prog` are more flexible and can also talk to hardware programmers (USBASP, PICkit2 etc), but in general the upload program is written specifically for a particular bootloader.


body:
I have a Arduino Mega with LCD TFT 2.4"" with reading 5v signal on A8 pin (Arduino mega pin) from a raspberry pi (just to test). They are grounded together. When the Arduino is without the LCD, the analog reading works fine (4.8V,same from multimeter). But when I assembly the LCD, even if I just assembly VCC and ground, the analog read increasce around of 0.2V measure. I already tried to change the voltage input with a potentiometer and I still receiving a measure error of 0.2V.  External energy supply to the LCD makes the things works, but I wouldn't like to have a external supply just to the screen.

What I'm doing wrong or what I can do ?

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

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

title: LCD TFT 2.4"" changes the values of analog read of Arduino Mega

Answers: 2

body:
 * The short answer is to beef up your power supply:

Don't use small batteries or power supplies.  For instance use D Size Cells instead of 9 Volt Cells.  Or use a 3 Amp power supply instead of a 100mAmp power supply.

 * The longer answer:

Make sure you have mitigated any power problems.  Like long or thin power lines.  Long or thin wires have more resistance.  And the more current you pull over that resistance the less voltage you will have at the far end.  Remember it follows the rule:

Voltage = Resistance * Current
------------------------------

 * Probably the best answer:

Check the ADC specification of the processor and make sure your voltage reference is not adversely affected by power fluctuations.  Some processors, like most used on Arduinos, have the ability to switch between internal references and external references.  Most designers who really need a good ADC response will design an external reference and instruct the processor to use the external over the internal reference.  For most Arduinos the function to call to switch references is ["analogReference()"][1].  You can read more about this command and external references [here][2].

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/
  [2]: https://support.arduino.cc/hc/en-us/articles/360018922239-What-is-the-AREF-pin-for-

body:
MCUFriend went through a number of revisions of the same 2.4" TFT shield over time. I guess it depended on what TFT screens they could get hold of cheapest at any given moment. I have two versions here, neither of which are the same as yours. Both have their own voltage regulator onboard for the 3.3V power (which yours doesn't). Both of them also have resistors present on the cathode of the back light - *which yours doesn't.*

I would imagine for this revision they mistakenly though the TFT screen's back light didn't require any current limiting resistors and omitted them, with the end result that connecting the TFT screen to the Arduino drags down the 5V voltage to that of the combined forward voltage of the LEDs in the back light circuit.

In short: your TFT screen is designed badly. Fixing it would require modifying the shield on a trace-level basis. Not easy.


body:
I am currently trying to connect four Bitcraze PMW3901 sensors to an Arduino NANO, but I seem to have issues with the SPI. When I connect two sensors using the code below, it works perfectly: I am able to retrieve the X and Y data from the serial port for both sensors.

```
include "Bitcraze_PMW3901.h"

 Bitcraze_PMW3901 flow(10);
 Bitcraze_PMW3901 flow2(9);

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

  if (!flow.begin()) {
    Serial.println("Initialization of the flow sensor 1 failed");
    while(1) { }
  }

  if (!flow2.begin()) {
    Serial.println("Initialization of the flow sensor 2 failed");
    while(1) { }
  }

}

int i =0;
int16_t deltaX,deltaY;
int16_t deltaX2,deltaY2;

void loop() {
  if ((i % 2) == 0) {
    digitalWrite(10, LOW); // sets the digital pin 10 on
    flow.readMotionCount(&deltaX, &deltaY);
    digitalWrite(10, HIGH);  // sets the digital pin 9 off
  }

  if ((i % 2) == 1) {
    digitalWrite(9, LOW); // sets the digital pin 10 on
    flow2.readMotionCount(&deltaX2, &deltaY2);
    digitalWrite(9, HIGH);  // sets the digital pin 9 off
  }

    i = i + 1;
    Serial.print("X1:");
    Serial.print(deltaX);
    Serial.print("\t");
    Serial.print("Y1:");
    Serial.print(deltaY);
    Serial.print("\t");
    Serial.print("X2: ");
    Serial.print(deltaX2);
    Serial.print("\t");
    Serial.print("Y2:");
    Serial.print(deltaY2);
    Serial.print("\n");

}
```

However, when I try to add a third Bitcraze PMW3901 sensor I cannot seem to be able to initilize it. Still, I declare a separete SS as

> Bitcraze_PMW3901 flow3(6);

and add the initialization code in the setup() function as follows

> if (!flow3.begin()) {
>     Serial.println("Initialization of the flow sensor 3 failed");
>     while(1) { }
>   }

What I get is the sentence "Initialization of the flow sensor 3 failed" or "Initialization of the flow sensor 1 failed" (it depends and I don't really understand why, since the code is always the same) printed on the serial port window.

I have already checked my sensors: they all work separetely and two-by-two. Do you have any suggestions? I hope I have managed to explain the problem clearly, otherwise please let me know if I can add or specify something more. Thank you in advance for your help!

title: SPI problem with Bitcraze PMW3901 sensors and Arduino NANO

Answers: 0


body:
My question is about something that is happening ONLY when I use external power supply. When I use the power from the Arduino Mega directly, there is no problem. However, I need to use an external power supply, because I need to drive 42 servos. I believe this is related to the Arduino and external power supply not being powered on at exactly the same time, which is rather difficult given that the Arduino has some boot-up time.

When I connect a single 1 of [these servos][1] to any Arduino board directly (I have tried multiple boards), everything works as expected, in the sense that when I kill power to the Arduino, the servo stops, and when restarted, the program runs again and the servo continues working from the exact same position as when stopped. There is no default or initial sentinel value that the servo "jumps" to. Here is the sketch of this circuit working just fine w/ 1 servo:

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

However, when I connect an external power supply this setup even with a single servo, the servo "jumps" immediately to position ~90 (which would be the middle given that it has a 0-180 range). I need external power for my real project because I have 42 such servos that I am driving. After this initial "jump to position", the Arduino program continues as normal and all 42 servos are working as expected. But this "jump to position" is very disruptive! There are various parts connected to these servos. When I power up the system, the whole thing jumps to position immediately sometimes causing some damage to the system that I have to repair manually. It is extremely painful to watch 42 servos snap to position so quickly and so much of the system move so fast as a result.

I believe this has something to do with the control wires still connected to the Arduino, but the power and ground connected to the external power supply. So if the entire system (both Arduino and external power supply) is not powered on at exactly the time, then the servos are getting power without control or control without power and the incoming voltage sets them to some initial position, either by design or by undefined behavior.

But I don't know how to wire a circuit that allows the external power exactly after the pins have been attached to the servos in the `setup()` function of the Arduino program, so the servos have control and power at the same time... Should I be trying to do this? How can I make sure all these servos and their control pins are all powered and attached at the same time?

Here is a rough wiring diagram of my system with only 1 servo (problem still exists):

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

I am using an Arduino Mega 2560 (I think rev3).

Here is the external power supply (5V 30A DC):
https://www.amazon.com/dp/B01HJA3OUG

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

[![enter image description here][5]][5]

Here are the servos:
https://www.adafruit.com/product/169

I am using the Arduino `Servo` library, which does work w/ these servos and my board.

I used appropriate gauge wire for the DC amperage to drive these servos. They all seem to have enough power to run after this initial "jump to position". But I really want to avoid this!

**UPDATE 10/7:**

I put this delay in the `setup()` function to give me time to plug in the external power supply at a specific point after bootup:

      // LONG DELAY WAITING FOR EXTERNAL POWER TO BE APPLIED; LED blink
      pinMode(LED_BUILTIN, OUTPUT);
      start = curr = millis();
      while (curr - start <= 10000)
      {
        curr = millis();
        if (curr - prev >= 1000)
        {
          prev = curr;
          if (state == LOW)
            state = HIGH;
          else
            state = LOW;
        }
        digitalWrite(LED_BUILTIN, state);
      }

If I put this code *after* the calls to attach the servo pins (i.e. `servo1.attach(1)`, then the jump happens immediately when I plug external power supply in. If I put this code *before* the servos are attached, then there is no jump at first when external power supply is plugged in, but then immediately after the delay code above finishes. This tells me that the jump is happening when the control wires are attached (i.e. `servo1.attach(1)` is called). However, this still doesn't give me any solution... If external power supply is applied either before or after when the servo control pins are connected, it jumps!

Why do these servos NOT jump when connected w/ power from the board, but jump when connected w/ external power supply?!

**This must mean that either the actual amount of external power supplied to these servos is different than the Arduino is supplying (and thus causing different behavior) or it's the fact that the power ground and control pins are not all connected at the exact same time (and thus causing different behavior).**

  [1]: https://www.adafruit.com/product/169
  [2]: https://i.stack.imgur.com/ibQO0.png
  [3]: https://i.stack.imgur.com/Q3QJo.jpg
  [4]: https://i.stack.imgur.com/ivQtT.jpg
  [5]: https://i.stack.imgur.com/KuIbm.jpg

title: Servos "jump to fixed position" at startup when powered by external power supply only, but not by board

Answers: 0


body:
I try to change time on windows to test my programing condition but RTC usually keep old time when i change time on windows and re-upload the code . I'm also removing the battery  and cut the power it is still not working.

here is my set up and library is https://github.com/adafruit/RTClib
```
void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);
   Serial.println("ESP start...");
  pinMode(Ledpin, OUTPUT);
  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, HIGH);

  delay(3000); // wait for console opening

if (! rtc.begin()) {
  Serial.println("Couldn't find RTC");
 while (1);
}

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

}
```

title: RTC DS3231 always remember the old time

Answers: 0


body:
I recently wrote a simple script to...we'll say, "flash some LED's" and uploaded it to an attiny45. In short, the script cycles through 3 LED's and turns them on for a specified frequency, in a specified direction. With a button, I can cycle through different modes. There are 7 modes (default (LED's OFF), then 3 different speeds forwards and 3 different speeds backwards).

The script works fine-ish, however I've noticed that in order to read from the button input properly, the function that turns the LED's ON and OFF must be completed, meaning that for the longer cycles, the user may have to hold the button until the function completes. This is further complicated during the shorter cycles, where the input may detect multiple button-presses (despite adding a delay following the digital read.

NOTE: I could just make the delay longer, but this doesn't fix the issue during lower frequencies, when the function may take multiple seconds to complete.

I feel the best way to sort this (though I'd be open to other ideas) is to use the attachInterrupt() function; however, it doesn't work. The button no longer works and I'm not sure why.

    // Pin Variables
    int led1 = 2;
    int led2 = 3;
    int led3 = 4;
    int leds[] = {led1, led2, led3};
    int modePin = 0; // (physical pin 5 on the IC)

    // Mode Speeds and setting
    int fastTime = 100;
    int mediumTime = 300;
    int slowTime = 1000;
    int offTime = 100;
    int mode = 0;

    void setup() {
      for (int i=0; i<3; i++){
        pinMode(leds[i], OUTPUT);
        digitalWrite(leds[i], LOW);
      }
      attachInterrupt(modePin, callMode, RISING);
    }

    void loop() {
      // If we get here, reset and go back to default (all LED's OFF)
      if (mode >= 7) {
        mode = 0;
      }
    }

    void callMode(){
      ++mode;
      //TIME: 1000, 300, 100 (milliseconds)
       switch (mode) {
         case 0:
           // Default, OFF
           for (int i=0; i<3; i++){
             digitalWrite(leds[i], LOW);
           }
           break;
         case 1:
           // Forward, Fast
           ledMode(fastTime, offTime, true);
           break;
         case 2:
           // Forward, Medium
           ledMode(mediumTime, offTime, true);
           break;
         case 3:
           // Forward, Slow
           ledMode(slowTime, offTime, true);
           break;
         case 4:
           // Backwards, Fast
           ledMode(fastTime, offTime, false);
           break;
         case 5:
           // Backwards, Medium
           ledMode(mediumTime, offTime, false);
           break;
         case 6:
           // Backwards, Slow
           ledMode(slowTime, offTime, false);
           break;
         case 7:
           // Return to Zero
           for (int i=0; i<3; i++){
              digitalWrite(leds[i], LOW);
           }
           mode = 0;
           break;
       }
    }

    void ledMode(int onTime, int offTime, bool forward){
      if (forward) {
        for (int i = 0; i <= 2; i++) {
          digitalWrite(leds[i], HIGH);
          delay(onTime);
          digitalWrite(leds[i], LOW);
          delay(offTime);
        }
      }
      else {
        for (int i = 2; i >= 0; i--) {
          digitalWrite(leds[i], HIGH);
          delay(onTime);
          digitalWrite(leds[i], LOW);
          delay(offTime);
        }
      }
    }

NOTE: callMode() and ledMode() are only split up into different functions because I know that the function passed to attachInterrupt() cannot contain any delays(). So each time the button is pressed, the mode variable should increment and then the switch-statement should cause the next mode to run. When we reach 7, let's reset to zero and enter the default/OFF mode.

I've been racking my head for a few days on this and not sure what the problem is. Perhaps I can only use the attachInterrupt() function to some other pin? Perhaps I'm not using that function correctly?

Thank you in advance for any and all help you can provide.

-Joe

title: Adding an Interrupt to ATtiny45 with Arduino

Answers: 1

body:
Interrupts are overkill for this kind of ultra-slow problems, and they
can introduce some extra complexity. Here the best solution seems (to me
at least) to lie in the approach of the [Blink Without Delay][bwod]
Arduino tutorial. Obviously, it must be adapted. In that tutorial, the
system switches between only two states (LED off or on). Here the
cycling of the LEDs goes through six phases:

0. all LEDs are off
1. LED[0] is on
2. all LEDs are off
3. LED[1] is on
4. all LEDs are off
5. LED[2] is on

The basic algorithm is the same: when `millis()` tells us it is time to
move to the next phase, we do so and update the state of the LEDs.

Note that I numbered the phases in such a way that the last bit
(`phase&1`) tells us whether an LED is on, and in that case the
remaining bits (`phase>>1`) hold the index of the LED that is on.

Here is how to cycle the LEDs at a fixed speed:

```c++
if (millis() - last_change >= phase_time) {
    last_change += phase_time;

    /* If an LED is on, turn it off. */
    if (phase & 1)
        digitalWrite(leds[phase >> 1], LOW);

    /* Move to the next phase. */
    if (++phase >= 6) phase = 0;

    /* Turn on the LED if needed. */
    if (phase & 1)
        digitalWrite(leds[phase >> 1], HIGH);
}
```

On top of this you need a [finite state machine][fsm] that cycles
between the different modes (speeds and directions). In order to avoid
code repetition, I would split this mode into a “state” that can OFF,
FORWARD or BACKWARDS, and an index into an array of delay times (with 0,
1, 2 meaning fast, medium and slow, respectively).

Putting it all together (warning: not tested):

```c++
const uint8_t leds[] = { 2, 3, 4 };
const uint32_t times[] = { 100, 300, 1000 };

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

enum { OFF, FORWARD, BACKWARDS } state = OFF;  // global state
uint8_t time_idx;      // index in times[] (0 = fast)
int8_t phase;          // 0 = all off, 1 = led[0] on, 2 = all off...
uint32_t last_change;  // last time the phase changed

void loop() {

    /* Change mode on button press. */
    if (button_pressed()) {
        if (state == OFF) {
            state = FORWARD;
            time_idx = 0;  // start fast
        } else {
            time_idx++;    // slow down
            if (time_idx >= 3) {  // change direction or stop
                time_idx = 0;
                if (state == FORWARD)
                    state = BACKWARDS;
                else              // state is BACKWARDS
                    state = OFF;
            }
        }
    }

    /* Cycle the LEDs. */
    if (state != OFF && millis() - last_change >= times[time_idx]) {
        last_change += times[time_idx];

        /* If an LED is on, turn it off. */
        if (phase & 1)
            digitalWrite(leds[phase >> 1], LOW);

        /* Move to the next phase. */
        if (state == FORWARD) {
            if (++phase >= 6) phase = 0;
        } else {  // BACKWARDS
            if (--phase < 0) phase = 5;
        }

        /* Turn on the LED if needed. */
        if (phase & 1)
            digitalWrite(leds[phase >> 1], HIGH);
    }
}
```

I did not write the `button_pressed()` function, which is meant to
debounce the button and detect the “just pressed” transition. It is left
as an exercise to the reader (or you can just use a [debouncing
library][Bounce2]).

[bwod]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
[fsm]: https://majenko.co.uk/blog/finite-state-machine
[Bounce2]: https://github.com/thomasfredericks/Bounce2


body:
I installed a fresh copy of Ubuntu 20.04, and Arduino IDE1.8.16. At the beginning adding user to `dialout` group enabled uploading sketch to Aruino AVR family, and ESP32, but still ESP8266 gives this error:

    Sketch uses 260889 bytes (24%) of program storage space. Maximum is 1044464 bytes.
    Global variables use 27980 bytes (34%) of dynamic memory, leaving 53940 bytes for local variables. Maximum is 81920 bytes.
    esptool.py v3.0
    Serial port /dev/ttyUSB0
    Connecting........_____....._____....._____....._____....._____....._____....._____
    Traceback (most recent call last):
      File "/home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/upload.py", line 66, in <module>
        esptool.main(cmdline)
      File "/home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool/esptool.py", line 3552, in main
        esp.connect(args.before, args.connect_attempts)
      File "/home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool/esptool.py", line 529, in connect
        raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
    esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
    esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

So I tried to erase flash using `esptool.py` :

    guy@desktop:~$ esptool --chip  auto --port /dev/ttyUSB0 erase_flash
    esptool.py v2.8
    Serial port /dev/ttyUSB0
    Connecting........_____....._____....._____....._____....._____....._____....._____

    A fatal error occurred: Failed to connect to Espressif device: Timed out waiting for packet header

Since AVR's and ESP32 work properly using USB's and ACM's I can guess that is is not a problem with the ability to access serial comm.

What might it be ?

title: Fail upload sketches to ESP8266 only on Ubunto 20.04.3

Answers: 1

body:
There is something wrong with some new kernels of Ubuntu 20.04 LTS, interfering with ESP8266 core uploading process

`5.4.0-88-generic #99-Ubuntu SMP Thu Sep 23 17:29:00 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux`

I had the same issue and downgraded the kernel to

`5.4.0-86-generic #97-Ubuntu SMP Fri Sep 17 19:19:40 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux`

solved the issue

---
---

The issue happens to ESP8266 core uploading process, with the following tested Ubuntu cores

- `linux-5.11.0-37-generic`
- `linux-5.4.0-89-generic`
- `linux-5.4.0-88-generic`

and tested OK with

- `linux-5.11.0-38-generic`
- `linux-5.11.0-36-generic`
- `linux-5.8.0-48-generic`
- `linux-5.4.0-90-generic`
- `linux-5.4.0-86-generic`

---

### Temporarily fix

To temporarily fix the issue by using working kernel, e.g. `linux-5.4.0-86-generic`

A. Select from GNU GRUB boot menu

- Advanced options for Ubuntu
  - Ubuntu, with Linux 5.4.0-86-generic

- If you don't have that kernel, install by

```
sudo apt install linux-image-5.4.0-86-generic
```

- Reboot and select `5.4.0-86-generic` from GNU GRUB boot menu

---

---

### To save the selected GRUB settings

More info [**GRUB Simple-configuration**](https://www.gnu.org/software/grub/manual/grub/grub.html#Simple-configuration)

1. Edit `/etc/default/grub` by

```
$ sudo gedit /etc/default/grub
```

2. Add to the file

```
 GRUB_DEFAULT=saved
 GRUB_SAVEDEFAULT=true
```

3. Activate the change so that last selected value is used for the next boot.

```
$ sudo update-grub
```

### Update

Just testing OK with latest kernel

- `linux-5.11.0-38-generic`
- `linux-5.4.0-90-generic`

It seems recent kernel release has fixed the issue


body:
When I am using 9V supply with motor driver and Jumper connected so the red LED was blinking but when I did the same using 9V and 15V supply removing the jumper LED didn't blink.
Neither the voltage nor the current drop across the motor was observed. And I didn't found any documentation for using L298n using without a jumper.
[![enter image description here][1]][1]

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

title: Using L298n motor driver without jumper (Voltage Regulator)

Answers: 0


body:
my arduino for the playground adafruit express gets stuck uploading, and is saying that it is not recognizing the ports. <Arduino: 1.8.16 (Windows Store 1.8.51.0) (Windows 10), Board: "Adafruit Circuit Playground"

    Sketch uses 6360 bytes (22%) of program storage space. Maximum is 28672 bytes.

    Global variables use 351 bytes of dynamic memory.

    Forcing reset using 1200bps open/close on port COM13

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    PORTS {COM13, } / {COM13, } => {}

    Uploading using selected port: COM13

    C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM13 -b57600 -D -Uflash:w:C:\Users\Owner\AppData\Local\Temp\arduino_build_570140/sorting_numbers_test.ino.hex:i

    avrdude: Version 6.3-20190619

             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM13

             Using Programmer              : avr109

             Overriding Baud Rate          : 57600

             AVR Part                      : ATmega32U4

             Chip Erase delay              : 9000 us

             PAGEL                         : PD7

             BS2                           : PA0

             RESET disposition             : dedicated

             RETRY pulse                   : SCK

             serial program mode           : yes

             parallel program mode         : yes

             Timeout                       : 200

             StabDelay                     : 100

             CmdexeDelay                   : 25

             SyncLoops                     : 32

             ByteDelay                     : 0

             PollIndex                     : 3

             PollValue                     : 0x53

             Memory Detail                 :

                                      Block Poll               Page                       Polled

               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00

               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00

               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly

             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

    Found programmer: Id = "F"; type = @

        Software Version = �.v; Hardware Version = �.

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: error: buffered memory access not supported. Maybe it isn't

    a butterfly/AVR109 but a AVR910 device?

    avrdude: initialization failed, rc=-1

             Double check connections and try again, or use -F to override

             this check.

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: error: programmer did not respond to command: leave prog mode

    avrdude: butterfly_recv(): programmer is not responding

    avrdude: error: programmer did not respond to command: exit bootloader

    avrdude done.  Thank you.

    the selected serial port

     does not exist or your board is not connected

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.>

title: why is my arduino stuck on uploading?

Answers: 1

body:
* > ...for the playground adafruit express gets stuck...

* `avrdude: initialization failed, rc=-1`

You appear to have selected the "Classic" rather than "Express" version of the board, [which are different things][1].

* The classic you have selected uses an AVR ATMega32u4 like you'd find in the Arduino Micro/Leonardo.

* The "Express" uses an ATSAMD21 chip like an Arduino Zero.

They don't use the same family of microcontroller, bootloader, bootloader protocol, or upload tool. The boards manager package that [supports the Class board][2] is completely different from the [one that supports the Express board][3]; they are divided support along the lines of the AVR (8-bit) vs SAMD (32-bit arm) chips.

In short, choose the "Express" version of the board after you've gone through [setup process for the Express][4].  If you have problems uploading to an Express with the Express board selected, you're likely to see errors [that mention `bossac`][5], but you're not going to see anything about `avrdude`.

  [1]: https://learn.adafruit.com/adafruit-circuit-playground-express/classic-vs-express
  [2]: https://github.com/adafruit/Adafruit_Arduino_Boards/
  [3]: https://github.com/adafruit/ArduinoCore-samd
  [4]: https://learn.adafruit.com/adafruit-circuit-playground-express/set-up-arduino-ide
  [5]: https://github.com/adafruit/ArduinoCore-samd/blob/1.7.5/boards.txt#L201


body:
I am struggeling with a behaviour of my Arduino I do not fully understand.

**Long story short:**

When starting the communication over I2C the Arduino freezes. In my opinion during the "Wire.write()" command.

**Long story and background:**

I want to connect my Arduino Uno to an Arduino MKR Wifi 1010 via I2C. I implemented the code for the communication step by step, so I started with the code below.

**Code for the Master Arduino Uno:**

```
#include <Wire.h>
#include <Arduino.h>

#define SLAVE_ADRESS                            2

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

void setup() {
  Serial.begin(38400);
  while (!Serial) {;} /* Wait for serial interface to be connected and ready for use. */
  Serial.setTimeout(2000);
  Serial.println(F("Serial Connection ready"));
  Wire.begin(); // join i2c bus (address optional for master)
}

void loop() {
  static int LedStatus = 0;
  if (LedStatus == 0)
  {
      LedStatus = 1;
  }
  else
  {
      LedStatus = 0;
  }
  Serial.print(F("Master LED status: "));
  Serial.println(LedStatus);
  Send_Data(SLAVE_ADRESS,LedStatus);
  delay(500);
}n
```

**Code for the Slave Arduino MKR Wifi 1010:**
```

#include <Wire.h>
#include <Arduino.h>

#define NODE_ADDRESS 2

int led = 0;

void setup()
{
  Serial.begin(38400);
  while (!Serial)
  {
        ; /* Wait for serial interface to be connected and ready for use. */
  }
  Serial.setTimeout(1000);

  Wire.begin(NODE_ADDRESS);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes)
{
  led = Wire.read();
  Serial.println("Data reveived!");
  Serial.print("Slave Value led: ");
  Serial.println(led);

}

void loop()
{

}
```

This piece of code works fine as expected.
So I implemented the very same functionality for the master into my projekt.
```
/****************************************************************************/
/*-------------------------------Description--------------------------------*/
/****************************************************************************/

/*
Used board: Arduino Uno

>>> Pin usage overview <<<
0:
1:
2: waterlevel tank sensor low (black sensor wires)
3: waterlevel tank sensor high (red sensor wires)
4: waterlevel reservoir sensor low (not used yet)
5: waterlevel reservoir sensor high (not used yet)
6: pump level tank
7: pump level reservoir
8: water temperature sensor
9: water temperature sensor
10:
11:
12:
13:
A0: EC sensor
A1: pH sensor
A2:
A3:
A4:
A5:
/*

/****************************************************************************/
/*---------------------------------Includes---------------------------------*/
/****************************************************************************/

#include <Arduino.h>
#include <RTClib.h>
#include <TimerOne.h>
#include <Wire.h>
#include "WaterCondition.h"
#include "WaterFlow.h"
#include "Serial.h"

/****************************************************************************/
/*----------------------------------Macros----------------------------------*/
/****************************************************************************/

#define TIMER_INTERVAL                          2000000 // 5sec (timer in microsec)

#define RTC_INIT_TIME_SECOND                    0
#define RTC_INIT_TIME_MINUTE                    0
#define RTC_INIT_TIME_HOUR                      0
#define RTC_INIT_TIME_DAY                       0
#define RTC_INIT_TIME_MONTH                     0
#define RTC_INIT_TIME_YEAR                      0

#define OPERATING_MODE_AUTO                     0
#define OPERATING_MODE_TEST_TEMP_SENSOR         1
#define OPERATING_MODE_TEST_EC_SENSOR           2
#define OPERATING_MODE_TEST_PH_SENSOR           3
#define OPERATING_MODE_TEST_RTC                 4
#define OPERATING_MODE_TEST_WATERLEVEL          5
#define OPERATING_MODE_TEST_COMMUNICATION       6

#define SLAVE_ADRESS                            2 // adress of the slave for communication

/****************************************************************************/
/*-----------------------------Global Variables-----------------------------*/
/****************************************************************************/

/*
OPERATING_MODE 0: Automatic
OPERATING_MODE 1: Testing / Calibration
*/
uint8_t OperatingMode = 0;

/* Used for Serial.h to read the input from serial connection */
extern char StringBuffer[STRING_BUFFER_SIZE];
extern float WaterConPhVolt, WaterConEcVolt, WaterConPhVal, WaterConEcVal, WaterConTempVal;

/****************************************************************************/
/*------------------------------Initialization------------------------------*/
/****************************************************************************/

RTC_DS3231 rtc;
DateTime now;

int freeRam()
{
    extern int __heap_start, *__brkval;
    int v;
    return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/* standard operations */
void ISR_Task(void)
{
    if (OperatingMode == OPERATING_MODE_AUTO) // Automatic
    {
        Serial.println(F("Running in automatic mode"));

        uint8_t min;
        min = now.second(),DEC;
        if ((min == PUMP_TANK_ON_INTERVALL_1) || (min == PUMP_TANK_ON_INTERVALL_2))
        {
            //Serial.println(F("Test: RTC min = 0 or 30");
            //Activate pump
            //Function tbd
        }
        else if ((min == PUMP_TANK_OFF_INTERVALL_1) || (min == PUMP_TANK_OFF_INTERVALL_2))
        {
            //Serial.println(F("Test: RTC min = 20 or 50");
            //Deactivate pump
            //Function tbd
        }
        WaterConTempVal = WaterCon_Sensor_TEMP(0);
        WaterConEcVal = WaterCon_Sensor_EC();
        WaterConPhVal = WaterCon_Sensor_PH();
        if (Waterflow_Tank() == 99)
        {
            // tbd
        }

    }
    else // Testing
    {
        /* >>> Test the temperature sensor <<< */
        if (OperatingMode == OPERATING_MODE_TEST_TEMP_SENSOR)
        {
            Serial.print(F("Water temperature filtered: "));
            Serial.println(WaterCon_Sensor_TEMP(0));
        }

        /* >>> Test the PH sensor <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_PH_SENSOR)
        {
            float test_ph = 0;
            test_ph = WaterCon_Analog_Read(PH_PIN, VOLTAGE_PIN, RESOLUTION_SENSOR_PH);
            Serial.print(F("PH-Sensor-Value raw from 0 - 5000mV: "));
            Serial.println(test_ph);
            Serial.print(F("PH-Value from 0 - 14: "));
            Serial.println(WaterCon_Sensor_PH());
        }

        /* >>> Test the PH sensor <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_EC_SENSOR)
        {
            float test_ec = 0;
            test_ec = WaterCon_Analog_Read(EC_PIN, VOLTAGE_PIN, RESOLUTION_SENSOR_EC);
            Serial.print(F("EC-Sensor-Value raw from 0 - 5000mV: "));
            Serial.println(test_ec);
            Serial.print(F("EC-Value from 0 - 2000uS: "));
            Serial.println(WaterCon_Sensor_EC());
        }

        /* >>> Test the RTC clock <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_RTC)
        {
            Serial.print(F("\nRTC-Time: "));
            Serial.println(now.second(),DEC);
        }

        /* >>> Test the waterlevel sensors <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_WATERLEVEL)
        {
            int WaterLvlSensorLow = 0;
            int WaterLvlSensorHigh = 0;
            WaterLvlSensorLow = digitalRead(TANK_LVL_LOW_PIN);
            WaterLvlSensorHigh = digitalRead(TANK_LVL_HIGH_PIN);

            Serial.print(F("Waterlevel Sensor Low: "));
            Serial.println(WaterLvlSensorLow);
            Serial.print(F("Waterlevel Sensor High: "));
            Serial.println(WaterLvlSensorHigh);
        }

        /* >>> Test the communication over I2C <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_COMMUNICATION)
        {
            static int LedStatus = 0;
            if (LedStatus == 0)
            {
                LedStatus = 1;
            }
            else
            {
                LedStatus = 0;
            }
            Serial.print(F("Master LED status: "));
            Serial.println(LedStatus);
            Send_Data(SLAVE_ADRESS,LedStatus);
        }
    }
}

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

/****************************************************************************/
/*-------------------------Function Implementations-------------------------*/
/****************************************************************************/

void setup() {
    Serial.begin(38400);
    while (!Serial) {;} /* Wait for serial interface to be connected and ready for use. */
    Serial.setTimeout(2000);
    Serial.println(F("Serial Connection ready"));

    /* Initialize sensors */
    Serial.println(F("Setup Sensors"));
    WaterCon_Sensor_Init();
    Waterflow_Sensor_Init();

    /* Initialize RTC */
    Serial.println(F("Setup RTC"));
    rtc.begin();
    Serial.println(F("Test"));

    /* Initialize timers */
    Serial.println(F("Setup Timers"));
    Timer1.initialize(TIMER_INTERVAL);
    Timer1.attachInterrupt(ISR_Task);
    Serial.println(F("Setting the time for the RTC..."));
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

    /* Initialize I2C Master-Slave */
    Wire.begin();
}

void loop()
{
    now = rtc.now();

    delay(200);
    Serial_Read(1);
    /* Change operating mode to automatic */
    if (strcmp("opauto",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to automatic"));
        OperatingMode = 0;
    }
    /* Change operating mode to testing */
    else if (strcmp("optest1",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: temperature sensor"));
        OperatingMode = 1;
    }
    else if (strcmp("optest2",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: EC sensor"));
        OperatingMode = 2;
    }
    else if (strcmp("optest3",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: pH sensor"));
        OperatingMode = 3;
    }
    else if (strcmp("optest4",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: RTC clock"));
        OperatingMode = 4;
    }
    else if (strcmp("optest5",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: Waterlevel Sensors"));
        OperatingMode = 5;
    }
    else if (strcmp("optest6",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: Communication via I2C Master-Slave"));
        OperatingMode = 6;
    }
}
```
Some explanation for you to understand what I am trying to do:
Above you can see the code from the Main.ino file for a hydroponic project. I wanted to realize different operating modes for automatic and testing. So if I encounter a fault, I want to be able to plug the laptop on the USB port and start to read out some information over the serial port. Later this should be accomplished over the air but for the beginning this should be fine.
To achieve this, I put string compare into the loop to notice if the user did some input and respond to it.
I tested that functionality a lot and it worked fine. I am able to jump from any operating mode to another.

There is an external real time clock running for using interrupts and run code at specific times.
During this interrupt I check what operating mode is active and run the respective code. With the string compare I mentioned above I can jumo into the respective code with the next interrupt.

**ISSUE:**
Now I can describe the actual issue. Everytime I enter the "operating mode 6" to test the I2C connection, the Arduino freezes. As you can see I used the very same code inside the "else if" as tested before.
This is the relevant part of the code:
```
        /* >>> Test the communication over I2C <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_COMMUNICATION)
        {
            static int LedStatus = 0;
            if (LedStatus == 0)
            {
                LedStatus = 1;
            }
            else
            {
                LedStatus = 0;
            }
            Serial.print(F("Master LED status: "));
            Serial.println(LedStatus);
            Send_Data(SLAVE_ADRESS,LedStatus);
        }
    }
}

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}
```
In the following picture it looks like the Board freezes during the serial communication when it prints out "Master LED status: ". I testet this by commenting out the serial.print commands and insert a print command between Wire.begin and Wire.write in the code.
[![enter image description here][1]][1]

I think the main problem is caused by the Wire.write function, but I am not able to debug it other than using serial.print commands. But the printed commands do not correlate with the line of code when the board actually freezes. I think I would need real debugger that stops the processor and gives me the possibility to go through the code step by step.
At first I thought this issue was caused because the SRAM got filled. So I put the Serial.print commands in the flash memory and inserted some lines of code for checking the usage of the SRAM and the Stack. You can see the "freeRam()" function in the code, but I removed them for better readability.

Did anyone have a similar issue or do you know what could cause this issue?

Thanks a lot in advance!

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

title: Arduino Uno freezes for unknown reason during code execution

Answers: 1

body:
The program most likely hangs at `Wire.endTransmission();`, because that's where the actual I2C communication happens. `Wire.write()` does nothing but placing the data into the internal buffer of the `Wire` library.

**You experience problems because you are calling interrupt-dependent code inside an ISR, where interrupts are deactivated by default.**

The `Wire` library uses the I2C hardware of the Uno. This hardware generated interrupts for the different stages in the communication (for example generating an interrupt so that the library can place the next data byte in the hardware buffer). That means that the `Wire` library will not work if interrupts are turned of for some reason. It will wait forever for an interrupt that will never come.

When entering an ISR (in this case of the Timer1 interrupt) other interrupts are deactivated by default. At the end of the ISR the compiler will again turn on interrupts. Any interrupts which happen during the execution of the current ISR will be executed after it has exited.

With `Wire.endTransmission()` you currently have a function call in your Timer1 ISR, which will wait for its corresponding I2C ISRs to run, which cannot happen inside the Timer1 ISR.

**What to do now:** You need to restructure your code. You shouldn't do that much stuff in an ISR either way. It needs to be as short as possible to not disturb other interrupt based functions. In the ISR just set a simple 1-byte flag variable. Then in `loop()` check this flag variable. If it is set, you can do the stuff, which currently is in your ISR. And then you reset the flag to be ready for the next ISR setting it again. For this to work correctly you need to ditch the `delay()` call in `loop()`. If you want to do timed things, you can use `millis()` like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. Make sure that nothing can block the `loop()` function for a long period of time (meaning longer than the interval between 2 interrupts or longer than the minimal time resolution, that you want in your system).

---

Note: You thought of the wrong line while debugging, because of your Serial output. But Serial output is only helping to a certain extent with debugging, since it too needs interrupts to work correctly. All the data that gets printed in your ISR will only be send once the ISR exits. `Serial.print()` and its siblings only fill the buffer of the library, while the actual sending is done in the background via ISRs. So the sending stopped when it got stuck at the ISR, but that doesn't mean that this actually was what you printed directly before that line. Even when not having interrupts involved this might not be the case. Just keep that in mind when using Serial prints for debugging.


body:
I'm planning a new custom keyboard project which involves a solenoid being controlled by a Teensy2.0++, and i would like to power everything with just a USB cable.

I don't have much electronics or electrical engineering background but from my research, this is how I think i should be wiring my solenoid up.

I would appreciate if anyone can help me to check if this is correct and doesn't blow anything up.
[![Schematics][1]][1]

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

title: Help needed to check if my solenoid wiring is correct

Answers: 0


body:
I'm using ESP32 and 1 sensor mpu9250(only for test) with tca9548a, connections are:

TCA <-> ESP

VIN - VCC

GND - GND

SDA - GPIO21

SCL - GPIO22

TCA <-> MPU

SD2 - SDA

SC2 - SCL

VIN - VIN

GND - GND

And my code here:

    #include <SparkFunMPU9250-DMP.h>
    #include <Wire.h>

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

      Wire.beginTransmission(TCAADDR);
      Wire.write(1 << i);
      Wire.endTransmission();
    }

    MPU9250_DMP imu;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      tcaselect(2);
      if (imu.begin() != INV_SUCCESS)
      {
        while (1)
        {
          Serial.println("Unable to communicate with MPU-9250");
          Serial.println("Check connections, and try again.");
          Serial.println();
          delay(5000);
        }
      }

      imu.dmpBegin(DMP_FEATURE_6X_LP_QUAT | // Enable 6-axis quat
                   DMP_FEATURE_GYRO_CAL, // Use gyro calibration
                  10); // Set DMP FIFO rate to 10 Hz
                  delay(10000);
    }

    void loop()
    {
      tcaselect(2);
        imu.dmpUpdateFifo();
      float q0 = imu.calcQuat(imu.qw);
      float q1 = imu.calcQuat(imu.qx);
      float q2 = imu.calcQuat(imu.qy);
      float q3 = imu.calcQuat(imu.qz);
      Serial.println("Q: " + String(q0, 4) + ", " +
                        String(q1, 4) + ", " + String(q2, 4) +
                        ", " + String(q3, 4));delay(10);
    }

I need to get quaternions from the MPU sensor but I'm only getting zeros on the output.

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

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

Library that I used: https://github.com/rupin/SparkFun_MPU-9250-DMP_Arduino_Library

What could be wrong, my connection or library?

title: multiple mpu9250 using tca9548a with esp32

Answers: 1

body:
The solution is that I just removed the tca9548a from the circuit. Then I connected each AD0 pin to the corresponding GPIO ESP32 pins to turn on the sensor, I send a low signal to it, and a high signal to all the others. Thus, the library only works with a sensor whose address is 0x68.

There is example function from my sketch:

    #include <SparkFunMPU9250-DMP.h>

    /*INIT SENSORS*/
    MPU9250_DMP imu;
    MPU9250_DMP imu1;
    const int sensor1 = 18;
    const int sensor2 = 19;

    String IMU_1Update(){
      String res;
        digitalWrite(sensor1, LOW); // 1st sensor enable - 0x68
        digitalWrite(sensor2, HIGH); // 2nd sensor disable - 0x69
      if ( imu1.fifoAvailable() ){
        if ( imu1.dmpUpdateFifo() == INV_SUCCESS){
          float q0 = imu1.calcQuat(imu1.qw);
          float q1 = imu1.calcQuat(imu1.qx);
          float q2 = imu1.calcQuat(imu1.qy);
          float q3 = imu1.calcQuat(imu1.qz);
          Serial.print("G1|");
          Serial.print(q0);
          Serial.print("|");
          Serial.print(q1);
          Serial.print("|");
          Serial.print(q2);
          Serial.print("|");
          Serial.print(q3);
          Serial.println("|");
        }
      }
      return res;
    }


body:
I'm trying to figure out how the Arduino Capacitive Sensing Library https://playground.arduino.cc/Main/CapacitiveSensor/ works. It says:

> When the send pin changes state, it will eventually change the state of the receive pin.

However, when I look at the following schematic, I don't understand why this is the case. It seems like the send pin is set to OUTPUT and HIGH and the receive pin to INPUT with deactivated pull-up. I think it's okay to ignore the capacitance at first, yes? Doesn't all the voltage drop over the resistor R and the receive pin will just be floating and showing LOW or HIGH randomly?

[![schematic][1]][1]

Source: https://playground.arduino.cc/Main/CapacitiveSensor/

  [1]: https://i.stack.imgur.com/92KIv.gif

title: Why does the send pin influence the receive pin with Arduino Capacitive Sensing Library

Answers: 1

body:
If we ignore the capacitance of the input pin, then it would instantly follow the voltage of the send pin. A voltage drop over the resistor only happens if a current is flowing though it, which cannot happen without any capacitance the receive side. Without current a resistor is just a wire.

A floating pin doesn't directly have its state randomly changes between LOW and HIGH. That can only be the result as the voltage on that pin is changes by the noise. We need the noise to not be directly in the logic voltage range, so that the state of the digital input pin is not totally dictated by noise. That often the case. Also the additional capacitance added by the sensing foil helps with filtering the noise.

The actual measurement works as follows: We set the send pin to a known state and wait a bit (to fully load or unload the capacitance on the pin). Then we change the send pin to the other state and count the time until we see that change on the receive pin. That is when the capacitance of the pin is loaded. Then we are doing that procedure many times, averaging the measured time. What the receive pin does outside of the measurements is not important. During the meausrement its state is mainly dictated by us setting the send pin. Though the library might use some optimization to get a better reading. You could read the libraries code to learn more about that.


body:
Note that to get to this point, I used much of the helpful information from the Post
*How to use capactive touch on Adafruit board in Arduino mode?*

I am using a Trinket M0 with the Arduino IDE with the Adafruit_FreeTouch.h library.
Also used the example code found here

https://github.com/adafruit/Adafruit_FreeTouch/blob/master/examples/freetouch/freetouch.ino

I modified the code to use the A0 input as a touch sensor with a wire and aluminum foil.
Using a FET on the digital output A2 to turn a fan on or off when the foil is touched.
I am using a small 12VDC wall transformer (1.25A) and then a DC-DC converter to output 5vdc for the Trinket on the BAT in.  The 12Vdc also supplies power to the small computer fan ( uses about 200ma)

The circuit and code work great when the USB cable from my laptop is connected to the Trinket.
**BUT, when I disconnect the USB cable from the Trinket** and touch the sensor, everything goes unstable.  Fan and built-in led cycle on/off randomly at 0.5sec to 2sec intervals.

I've tried all different parameters for the library including the series resistor, sampling rate and frequency modes. I've checked grounds multiple times and this one is really stumping me.
I suspected fan noise early on so the most interesting experiment I've tried so far IMHO is to remove the 12vdc to the fan but keep it supplying the DC-DC converter for the 5v to the trinket-But, the onboard led has the same instability as when fan is connected.
Lastly, I used an Arduino Uno to develop the code and the circuit earlier and it worked fine without USB cable connected.
I feel so close.
Any suggestions or insights much appreciated.

**Here is my code**

    / touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
    // Note: the pin silkscreened 1 is Analog Pin 0.

    #include "Adafruit_FreeTouch.h"

    Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_0, FREQ_MODE_NONE);
    int led = 13; // blink 'digital' pin 1 - AKA the built in red LED
    int FAN = 2;  //

    void setup() {
    // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(FAN, OUTPUT);
      digitalWrite(led, LOW);
      digitalWrite(FAN, LOW);
      delay(50);
      // Initialize A0 as a touch sensor
      if (! qt_1.begin())
        //Serial.println("Failed to begin qt on pin A0");
        digitalWrite(led, HIGH);    // Turn on the led
    }
    void loop()
    {
      int counter;
      int result = 0;
      counter = millis();
      result = qt_1.measure();
      if (result > 950) {
        digitalWrite(FAN, HIGH);    // Turn on the FAN
        digitalWrite(led, HIGH);    // Turn on the led
      }
      else {
          digitalWrite(FAN, LOW);    // Turn off the FAN
          digitalWrite(led, LOW);    // Turn off the led
      }
      delay(50);
    }

Here is schematic

[![schematic][1]][1]

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

---

Not sure if I'm doing this right by posting an answer?

I didn’t expect this to be as complex!  Unfortunately adding the suggestion to add the capacitors did not change anything.
But the answer makes sense to me because when I think of why it worked so well on my Arduino Uno development circuit, it could have been because I was using the Capacitive Sense library which utilized two pins that to my understanding measured a RC type of decay to achieve the touch sensing.

Too bad that the Trinket doesn’t operate the same way.  And my programming skills are not strong enough to come up with a similar design solution as the Arduino Uno RC sensing.
So, I will try the idea in the answer where I implement the “side by side with a gap” touch sensor just for learnings sake.  I’ve seen these touch sensors often as traces on a pcb.

But I should share what my ultimate design goal is.
That is to make a touch sensitive art lamp that has a steel body. The lamps are diodes and diodes strips which will be brightness controlled with a PWM input.  So, there is no need for an AC connection other than for the wall transformer which supplies DC.  The design needs to sense a touch whenever someone touches anywhere on the lamp body so that the SW can simulate a three-way switch.  So, a “side by side” gap doesn’t work in this application.  I was hopeful that the Trinket would work since I had everything working in my Arduino proto.  And I’m really looking for a “small” trinket type board solution to fit in the lamp.  In the past I have been successful achieving this functionality with AC power lamps by using those replacement touch circuit modules for 3-way AC switched bulbs.  But for this I wanted to use LED energy saving light sources with a microcontroller.

I think I will try to research “dedicated or discrete” touch sensing circuits that can give me digital input to the Trinket when a touch is sensed on the lamp body.
Any other suggestions/comments are greatly appreciated.
Cheers

title: Capacitive touch on Adafruit Trinket M0 goes unstable when USB cable from laptop is disconnected

Answers: 1

body:
The problem is most likely your power supply coupled with the poor design of the capacitive sensing system.

The capacitive sensing is done by measuring the capacitance between your foil plate and "ground". That "ground" is usually a connection through the USB cable and your computer's power supply through the earth wire of your power cable to the physical ground, so you are then between the two "plates" of the capacitor.  That ground connection is "clean". For a laptop the "ground" is usually just the case of the laptop or metal parts of the internals. This has no, or little, power supply noise.

However when you use a USB power supply you no longer have that "clean" connection. Instead your "ground" is going through the negative lead of the USB into the negative rail of the USB power supply which is then capacitively coupled to the neutral of the mains through a "class Y" capacitor across the transformer (there to remove inductive switching noise). That capacitor handles some quite high voltages and lots of noise, so you get that noise also reflected into your USB "ground", meaning the ground that you are using in your capsense "capacitor" is really quite noisy. Noisy enough to make your readings meaningless. On some laptops you may even notice a change when you plug the charger in compared to running on batteries for this same reason. (It's also why some early aluminium Apple laptops could give you an electric shock if you used them while plugged in...)

If you look at proper capacitive sensing arrangements you will see that the aren't just a bit of metal foil. They are properly arranged traces on a PCB which not only include the "sense" side but also the "ground" side of the capacitor. Your finger then affects the capacitance between these two points, not between a bit of foil and the floor of your room.

You should get a piece of cardboard and glue two pieces of foil side by side on it with a small gap between them. Then connect one of them to the Arduino's ground and the other to your input pin. Then recalibrate your readings to work with the new arrangement. You should find it far more stable and reliable.


body:
For a school project I need to connect an Arduino with an accelerometer gyroscope sensor and 2 mini servo motors. Of course I need a battery for this. However, I don’t know what battery I need for this. I have no clue where to start. Does anyone know which battery I can use? Or how I can find this out? I added links of the sensor, Arduino and servo motors that I have below.

Thanks in advance! :)

Sensor:
https://www.tinytronics.nl/shop/nl/sensoren/acceleratie-rotatie/mpu-6500-accelerometer-gyroscope-6dof-module-3.3v-5v

Arduino uno:
https://www.tinytronics.nl/shop/nl/development-boards/microcontroller-boards/arduino-compatible/uno-r3-met-usb-kabel

Mini servo motor:
https://www.tinytronics.nl/shop/nl/mechanica-en-actuatoren/motoren/servomotoren/ts90d-mini-servo-1.6kg-continuous

title: What external battery do I need?

Answers: 0