body:
My teacher gave us a performance output about doing a dancing christmas lights in tinkercad. But I don't know what to do about the codes. He left  an instruction to us about what to do. I follow it but the tinkercad keep telling that...

```
Sorry, it seems like your code has some errors.
Close
 In function 'void setup()':
13:5: error: a function-definition is not allowed here before '{' token
21:7: error: a function-definition is not allowed here before '{' token
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
 exit status 1
```

**And here's the code that I've entered...**

```
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i =0; i <11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
}
  {
  void setup()
    {
     for (int i=0; i <11; i++)
     {
       pinMode(ledPins[i],OUTPUT);
     }
  }
    {
      void loop()
      {
        int i = 0;
        while (i<10)

        {
          {
            digitalWrite(ledPins{i],HIGH);
            delay(100);
            digitalWrite(ledPins[i],LOW);
            i++;
                                }
                         }
                         i = 10;
                         while (i >0
                                {
                                  digitalWrite(ledPins[i],HIGH;
                                               delay(100);
                                               digitalWrite(ledPins[i],LOW;
                                                            i--;
                                                            }
                                                            }

```

And here's the instruction of my teaher for the codes...

6. Initialize variables
Use array to initialize variables.
Set ledPin as the name of the variable and initialize the Arduino pins that you’re going to use.
Never forget to end each statement with semicolon

7. Set all pin to output
Use function void setup ()
Create a for () loop for array manipulation.
Initialize the for loop with i=0; since we will start the dancing lights with all LEDs turned off.
Initialize the condition i<11; since we need to turn on the 10 LEDs.

Set the increment to i++ because we need to iterate until it reaches the last LED.
Configure pin using pinMode().
Place a curly bracket before and after the for loop and pinMode().
8. Create a loop
Use function void loop().
Create a variable, i = 0.
Use while() for continuous looping
First while() is used to run your light from right to left.

Second while() is used to run your light from left to right.
Place a curly bracket before and after your statement block
Never forget to end each statement with semicolon

title: What's wrong with my codes/

Answers: 1

body:
I changed it, so it at least compiles.

    int ledPins[]={3,4,5,6,7,8,9,10,11,12};
    void setup()
    {
      for(int i=0; i < 11; i++)
      {
        pinMode(ledPins[i],OUTPUT);
      }
    }

    void loop()
    {
      int i = 0;
      while (i < 10)
      {
        digitalWrite(ledPins[i],HIGH);
        delay(100);
        digitalWrite(ledPins[i],LOW);
        i++;
      }
      i = 10;
      while (i > 0)
      {
        digitalWrite(ledPins[i],HIGH);
        delay(100);
        digitalWrite(ledPins[i],LOW);
        i--;
      }
    }


body:
I want to use this library: https://www.arduino.cc/en/Reference/Stepper

    #include <Stepper.h>

The wiring for my driver is shown here:

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

https://www.pololu.com/product/1182

From the library, I'm stuck at the motor pins:

    #define motorSteps 200
    #define motorPin1 2    // STEP pin
    #define motorPin2 3    // DIR pin

    Stepper myStepper(motorSteps, motorPin1, motorPin2);

**Is this library not compatible with this stepper motor driver? Or what needs to be defined for it to work?**

More details on the library are here: http://www.tigoe.com/pcomp/code/circuits/motors/stepper-motors

The basic section of my code that works without the library is this:

    digitalWrite(stepPin, HIGH);
    delay(wait);
    digitalWrite(stepPin, LOW);
    delay(wait);

Yet, the two-wire circuit part of the library uses motorPin1 and motorPin2 in a way I don't understand:

    switch (thisStep) {
      case 0:  // 01
        digitalWrite(motor_pin_1, LOW);
        digitalWrite(motor_pin_2, HIGH);
      break;
      case 1:  // 11
        digitalWrite(motor_pin_1, HIGH);
        digitalWrite(motor_pin_2, HIGH);
      break;
      case 2:  // 10
        digitalWrite(motor_pin_1, HIGH);
        digitalWrite(motor_pin_2, LOW);
      break;
      case 3:  // 00
        digitalWrite(motor_pin_1, LOW);
        digitalWrite(motor_pin_2, LOW);
      break;
    }

https://github.com/arduino-libraries/Stepper/blob/master/src/Stepper.cpp

How should `motorPin1` and `motorPin2` be defined?

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

title: Use the stepper motor library with the A4988 driver?

Answers: 1

body:
That library is not compatible with the A4988. It is intended to do the same job that the A4988 does. You provide a step direction and an instruction to step, and it does the stepping for you.

To use the A4988 you just set a pin HIGH or LOW for the direction, then toggle another pin to make it step. You don't really need a library for that.

However if you do want to abstract it with a library and add lots of cool extra features then you should look at [AccelStepper](https://github.com/waspinator/AccelStepper) which supports 2-wire drivers like the A4988.


body:
I'm trying to convert the string that I receive from the Websocket to uint8_t that I can copy to the data bytes of CAN protocol frame. I'm using an ESP32 chip and programming it on an Arduino IDE. The string that it receives from the websocket is "0322F12155555555".

```
#include <WiFi.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <esp32_can.h>
#include <SPI.h>
#include <string.h>

uint8_t payload1;
char payload2[100];
...
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
...
// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num,
                      WStype_t type,
                      uint8_t * payload,
                      size_t length) {
...
      Serial.printf("[%u] Received text: %s\n", client_num, payload);
      strcpy(payload2, (const char*)payload);
      payload1 = (uint8_t)(payload2);
...
```
Error:
```
error: cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]
       payload1 = (uint8_t)(payload2);
                                    ^

```
I'm segmenting the data into an array later, but I'm not confident that my cast is correct. Can someone please help with this? Thanks

-- Keith

title: Need help: Cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]

Answers: 1

body:
You can't just cast a string to a numeric type - C just doesn't work that way. What you're actually casting is the *address in memory* that the string resides at.

Instead you need to take the *content* of the string and interpret it.

For instance, you might take each pair of characters and combine them into a HEX value in a string that you then interpret as a number. That could be done a number of ways.

For example:

    char temp[3]; // Temporary space for the conversion string
    // Copy two characters into the temporary string
    temp[0] = payload[0];
    temp[1] = payload[1];
    // and terminate the string properly
    temp[2] = 0;
    // Convert the string using base 16
    uint8_t val = strtol(temp, NULL, 16);

In your example string you have 16 characters, which would be 8 bytes of data. So you could put it in a loop:

    char temp[3]; // Temporary space for the conversion string
    uint8_t vals[8]; // Array to store your values

    // Iterate over the values
    for (int i = 0; i < 8; i++) {
        // Copy two characters into the temporary string
        temp[0] = payload[i * 2];
        temp[1] = payload[i * 2 + 1];
        // and terminate the string properly
        temp[2] = 0;
        // Convert the string using base 16
        vals[i] = strtol(temp, NULL, 16);
    }

Of course there are "lighter" ways of doing it that don't involve an intermediate string or the `strtol()` function.  For example I often use this little function:

```
uint8_t h2d(char hex) {
 if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
 return(hex & 0xf);
}
```

That takes a single character and converts it from hex to decimal. So you can combine that with bit shifting and OR to create a byte from two characters:

    val = h2d(payload[0]) << 4 | h2d(payload[1]);

In your loop that would look like:

    for (int i = 0; i < 8; i++) {
        // Convert the string using base 16
        vals[i] = h2d(payload[i * 2]) << 4 | h2d(payload[i * 2 + 1]);
    }


body:
I've redone a previous [Arduino sketch][1] I posted in which I was having trouble capturing encoder counts within critical statements, having no luck properly attaching and detaching interrupts.  I've studied various ISR sketches but haven't been able to produce anything that caters to my needs.

I now have a switch case in which a DC motor with CPR encoder correctly rotates back and forth between specified boundaries if it alone is in the void loop.  However, once enclosed within a critical statement (I want this action to occur only if a button is pressed), the DC motor continues to rotate only one direction.

I need assistance in where to properly attach and detach these interrupts and how to correctly pass the encoder value to the next action.  Below is what I've done so far and any help would greatly be appreciated.

    #define enA 9
    #define in1 6
    #define in2 7

    const int button1Pin = 8;

    int button1State = 0;

    volatile long temp, counter = 0;

    long local_counter=counter;

    enum {IdleState, ForwardState, BackwardState} State;

    void setup() {

      Serial.begin(9600);

      pinMode(enA, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);

      Serial.begin (9600);
      pinMode(2, INPUT_PULLUP);
      pinMode(3, INPUT_PULLUP);

      attachInterrupt(0, ai0, RISING);
      attachInterrupt(1, ai1, RISING);

      pinMode(button1Pin, INPUT);

      State = IdleState;
    }

    void loop() {

      button1State = digitalRead(button1Pin);

       if( counter != temp ){
       Serial.print("counter = ");
       Serial.print (counter);
       Serial.print("     local counter = ");
       Serial.println(local_counter);
       temp = counter;
       }

       //if (button1State == HIGH) {

              switch (State) {

                  case IdleState:
                    halt ();

                  if (counter<2000)
                    State = ForwardState;
                  break;

                  case ForwardState:
                    clockwise();

                  if (counter>=2000)
                    State = BackwardState;
                  break;

                  case BackwardState:
                    counterclockwise();

                  if (counter <=0)
                    State = ForwardState;
                  break;

              } // end switch
       //  }

    }

    void ai0() {
      if(digitalRead(3)==LOW) {
      counter++;
      }else{
      counter--;
      }
      }

    void ai1() {
      if(digitalRead(2)==LOW) {
      counter--;
      }else{
      counter++;
      }
      }

    void clockwise (){
        analogWrite(enA, 255);
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
      }

    void counterclockwise () {
        analogWrite(enA, 255);
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
      }

    void halt () {
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
    }

An explanation of my setup is as follows:

My button is a tactile button on breadboard (connected to pin 8 of an Arduino Uno),  with 5V supply from Arduino. Pins 6 of the Arduino is connected input 1 of the [L298N motor driver][2], pin 7 of Arduino connected to input 2 of the motor driver, and pin 9 of the Adruino connected to the enable of the motor driver.  Them motor driver is being supplied by an external 12V supply which is also power the [12V DC geared motor with encoder][3].  The encoder outputs are connected to pin 2 and 3 of the Arduino.

  [1]: https://arduino.stackexchange.com/questions/77741/for-statement-within-if-statement
  [2]: https://www.amazon.com/Qunqi-Controller-Module-Stepper-Arduino/dp/B014KMHSW6/ref=sr_1_11?crid=1QT6MXX93Z57C&dchild=1&keywords=l298n motor driver&qid=1598798898&sprefix=l298n ,aps,153&sr=8-11
  [3]: https://www.amazon.com/gp/product/B073S6DCRQ/ref=ppx_yo_dt_b_asin_title_o07_s00?ie=UTF8&psc=1

title: Interrupts Within Critical Statements

Answers: 1

body:
The way I see it, the state should go back to IdleState if the button is not pressed. Just putting the switch-case inside the if-statement will result in the motor continue rotating the way it was rotating when the button is released.

    if (button1State == LOW ) {
      State = IdleState;
      counter=2000;
    }
    else if(button1State==HIGH && State==IdleState ) {
      counter = 0;
    }

    switch(State) {
      ...

Depending on what it is you want to do, you might want to add another state (say `StoppedState`), where the motors are halted, just like IdleState, but you don't get a state change if `counter<2000`. Then you don't have to change the `counter` variable.

    if (button1State == LOW ) {
      State = StoppedState;
    }
    else if(button1State==HIGH && State==StoppedState ) {
      State = IdleState;
    }

    switch(State) {
      case StoppedState:
        halt ();
        break;
      case IdleState:
        ...

PS please indent the if statements inside you `case`s.


body:
**In short:** I have an Input Capture code and a Power-Saving code combined into one program.  Both are adapted from Nick Gammon's examples that work fine independently.  When I combined them into one code it only reads the data every other time a **single pulse** is sent to be captured every 20 seconds. The board sleeps during one idle cycle between the 20 second readings, then wakes up but misses the first reading, and then it stays awake during the next idle cycle and reads the pulse correctly at the 40 second mark for the second reading.  And repeats.  The references of these two Nick Gammon codes are listed in the program.

**Details:** Adafruit BlueFruit Feather 32u4 w/nrf51 in the Arduino 1.8.10 IDE.  Using Nick Gammon's example for Input Capture an external incoming pulse of around 800 us (micro sec) long pulse is being measured by (ICP3) Input Capture #3 (rewritten from ICP1) on Pin D13 (PC7) (removed the LED). Works good.

Then I had a separate program that puts the board into deep-sleep and using INT0 (D3) to wake it up with an external interrupt signal.    Since I was not able to figure out how to use the Input Capture as an ISR Interrupt to wake up the board, I ran the same external pulse signal also to the D3 (INT0) pin. So when the pulse hits both D3 (INT0) and D13 (ICP3) at the same time, and D3 wakes up the board via INT0 and then the ICP3 can capture the pulse and measure it.  Then right after that, or several seconds later, can go back to sleep until the next pulse arrives on D13 (ICP3).  I spaced the external 800us single pulses 20 seconds apart to make it easier to diagnose.  If I remove the line that places the board into sleep "sleep_cpu ();" I get a nice single-shot signal pulse measurement every 20 seconds.   Since I am not using the USB-detach and reconnect feature, after the board goes to sleep it disconnects, but I am monitoring the power usage  via a Fluke mA meter and I can see when it sleep and when it wakes up, and also monitoring the external pulse going to D13 (ICP3) and D3 (INT0) on the Oscope.

Notes: The Input Capture is listed under the Interrupts, but at a much lower priority then INTo or INT1.
I do not need an active USB during the readings or sleep, because using  BLE to send the data.  The code I posted has the BLE portion removed the make it simpler to troubleshoot. The 800us external single-shot pulse is rock solid I have it showing on the Oscope, at the proper magnitude (0 to 3.3V) and intervals. I am trying to have the CPU sleep between readings.  Can be right after the reading or a few seconds later. Interrupts have to be alive and ready to capture in case the 20 seconds becomes 1 or 2 seconds intervals (in real life).

```
// Time the interval between two consecutive pulses.Frequency timer using input //capture unit #3 on 32u4
// Author: Nick Gammon
// Date: 31 August 2013  http://www.gammon.com.au/timers
//  References: here:  http://www.gammon.com.au/forum/?id=11504&reply=12#reply12    //and  here:  https://www.gammon.com.au/power Sketch J
// Info here: http://gammon.com.au/interrupts
//Freq (Hz)     Per (µs)
// 8,000,000*   0.125us  or 125ns per clock tick at 8mghz

#include "LowPower.h"
//part of work around for BOSD missing functionality in 32u4.
//Not needed for 328p MCUs for sleep.

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/interrupt.h>
#include "avr/io.h"
#include <math.h>
#include <Arduino.h>

// Input: Pin D13 (PC7, ICP3) adafruit 32u  which is Timer3 Capture Input pin ,   //removed D13 LED by cutting trace or by removing resistor before LED13

const int wakeUpPin = 3;
volatile boolean first;
volatile boolean triggered;
volatile unsigned long overflowCount;
volatile unsigned long startTime;
volatile unsigned long finishTime;
volatile unsigned long elapsedTime;

//////START: ISR TIMER/COUNTER PULSE ROUTINE ON D13 INPUT-CAPTURE #3 on 32u4 ////
//https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html   //http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM-timer3

// timer overflows (every 65536 counts)
ISR (TIMER3_OVF_vect) //1 3

{
        overflowCount++;
}  // end of TIMER3_OVF_vect

ISR (TIMER3_CAPT_vect)   // 1 3
  {
       // cancel sleep as a precaution  (added here from Power Save)
      sleep_disable();

   // grab counter value before it changes any more
  unsigned int timer3CounterValue;
  timer3CounterValue = ICR3;
// see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // if just missed an overflow
  if ((TIFR3 & bit (TOV3)) && timer3CounterValue < 0x7FFF)  // 1 3     //http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM-timer3
    overflowCopy++;

  // wait until we noticed last one
  if (triggered)
    return;

  if (first)
    {
    startTime = (overflowCopy << 16) + timer3CounterValue;
    first = false;
    return;
    }

  finishTime = (overflowCopy << 16) + timer3CounterValue;
  triggered = true;
  TIMSK3 = 0;    // no more interrupts for now   // 1 3    //http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM-timer3
  }  // end of TIMER3_CAPT_vect

/////////////////////////ENF OF: TIMER/COUNTER PULSE MEASURE ROUTINE////////////

////////PREPARE FOR INTERRUPTS ROUTINE FOR TIMER/COUNTER CAPTURE////////////////

void prepareForInterrupts ()
  {

  noInterrupts ();  // protected code
  first = true;
  triggered = false;  // re-arm for next time
  // reset Timer 1
  TCCR3A = 0;   // 1 3
  TCCR3B = 0;    // 1 3

  TIFR3 = bit (ICF3) | bit (TOV3);  // clear flags so we don't get a bogus interrupt    // 1 3
  TCNT3 = 0;          // Counter to zero   // 1 3
  overflowCount = 0;  // Therefore no overflows yet

  // Timer 3 - counts clock pulses
  TIMSK3 = bit (TOIE3) | bit (ICIE3);   // interrupt on Timer 3 overflow and input capture
  // start Timer 1, no prescaler
  TCCR3B =  bit (CS30) | bit (ICES3);

// plus Input Capture Edge Select (rising on D13)
//TCCR1B &= ~(1<<ICES1);
//ICP set to trigger on falling/rising edge
//   Bit 6 - ICES1: Input Capture Edge select    Select edge detection for //input capture function.          0 = Capture on falling edge  1 = Capture on //rising edge

  interrupts ();
  }  // end of prepare For Interrupts

///END OF:   PREPARE FOR INTERRUPTS ROUTINE FOR TIMER/COUNTER////////////

///POWER SAVING -SIGNAL INTERRUPT WAKEUP ISR ON D3 on 32u4 or D2 on 328p///

void wakeUp ()
 {
  // cancel sleep as a precaution
     sleep_disable();
  // precautionary while we do other stuff
   detachInterrupt(digitalPinToInterrupt(wakeUpPin));
//D3 for 32u4 and D2 for 328p (INT0)
 }  // end of wakeUp
////POWER SAVING ROUTINE - WAKEUP ISR-END/////////////////

////////SET UP VOID ///////////////////////////////////////////

void setup(void)
{
 pinMode(wakeUpPin, INPUT); //this is pin D3 (INT0) on 32u4 and D2 (INT0) on 328p
digitalWrite (wakeUpPin, LOW);
// enable pull-down on D3 (on 32u4 D3 is INT0) for Wake INTERRUPT   - PART OF //POWER SAVING ROUTINE WITH INT0 SIGNAL on D3 on 32u4 (or D2 on 328p)

 Serial.begin(115200);

  pinMode(13, INPUT);
//This is the input/measure pin (LED taken off or LED13 resistor removed)
   analogWrite(13, LOW);  //must pull up or down to stop noise and floating

  // set up for interrupts
  prepareForInterrupts ();

}   // <= this is for the SET UP () ///////

////////////////////////END OF SETUP SEGMENT/////////////////

//////START OF MAIN LOOP/////////////

void loop(void)
{

   // wait till we have a reading
if (!triggered) //if "triggered" is NOT TRUE  (i.e. NOT TRIGGERED) then STOP HERE
 return;

unsigned long  elapsedTime = (finishTime - startTime);
//period count between start and stop times

Serial.print ("Start time: ");
Serial.print(startTime);
Serial.print (" counts.  ");
Serial.print ("Finish time: ");
Serial.print(finishTime );
Serial.print (" counts.  ");
Serial.print ("Elapsed time: ");
Serial.print (elapsedTime);
Serial.println (" counts.   ");

 // Delay before next measurement update
 delayMicroseconds(1000) ;

 prepareForInterrupts ();
//  goes back up outside LOOP to RESET conditions for next INPUT CAPTURE ISR AND //OVERFLOW ISR TIMER/COUNTER reading, clear registers, etc

///START: POWER SAVING ROUTINE USING D3 (INT0) on 32u4  (D2 is INT0 on 328p) //INTERRUPT FROM PULSE OR USER SWITCH////////////

//delayMicroseconds(3000000) ;
// DELAY SO SLEEP ONLY CAN HAPPEN EVERY 3 sec =>  3000000 us (micro sec)

 delay(500);// MUST have delay to allow power down process to proceed

      // disable ADC
      ADCSRA = 0;

      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      sleep_enable();

  // Do not interrupt before we go to sleep, or the ISR will detach interrupts and we won't wake.
      noInterrupts ();

  // will be called when INT0 (pin D2 for 328p) or D3 for 32u4 goes HIGH//
     attachInterrupt(digitalPinToInterrupt(wakeUpPin), wakeUp, RISING);

// [External Interrupts] //3 for 32u4 and 2 for 328p (INT0)  Use RISING as //trigger for (INT0 on D2 for 328p and) INT0 on D3 on 32u4 from op AMP.  Same //signal as the D13 INPUT CAPTURE TIMER from op Amp OUT
     EIFR = bit (INTF0);  // clear flag for interrupt 0
     EIFR = bit (INTF1);  // clear flag for interrupt 1
//  added just for good measure to cover both D2 and D3 INT pins

// turn off brown-out enable in software, BODS does not work with 32u4, only //328p.  Work around is to use "low-power.h" library, not implemented here
// BODS must be set to one and BODSE must be set to zero within four clock cycles
       // MCUCR = bit (BODS) | bit (BODSE);
       // The BODS bit is automatically cleared after three clock cycles
       // MCUCR = bit (BODS);

//We are guaranteed that the sleep_cpu call will be done as the processor //executes the next instruction after interrupts are turned on.
        interrupts ();  // one cycle
     // sleep_cpu ();   // one cycle    //*****DISABLED BECAUSE KEEPS DOUBLING
                                        //DATA SEND TIME, AND ONLY WAKES UP HALF
                                        //THE TIME

///////END OF POWER SAVING ROUTINE///////////////////////////////////////////////

}
///////////////////////END OF MAIN LOOP///////////////////

```

title: Input Capture with Sleep Enabled on ATM32u4 board only works every second reading in SLEEP mode

Answers: 1

body:
It seems to me your problem lies here:

> `set_sleep_mode (SLEEP_MODE_PWR_DOWN);`

In this mode, all the synchronous peripherals are turned off, including
your timer. However, you need this timer for generating the input
capture interrupt. You also want it to be running in order to count the
overflows, otherwise the values captured would be meaningless.

In order to keep the timer running, you have to use `SLEEP_MODE_IDLE`,
which is the default sleep mode anyway. This mode puts the CPU to sleep
while keeping the peripherals running. If you are afraid this may have
too high a power consumption, you can selectively [turn off all the
peripherals you do not need][pwr]. Note that you cannot selectively
_enable_ peripherals in other sleep modes.

[pwr]: https://www.nongnu.org/avr-libc/user-manual/group__avr__power.html


body:
I am using the Adafruit BME280 library in my sketch. In the example sketches, they have included the Wire, SPI and the Adafruit_Sensor library. However, I see that in the Adafruit_BME280 library header file, these libraries are already included. So I tried commenting out them in my sketch and it still works. So I wonder if there are still cases or any specific reason to include them twice?

Additionally, if a library is included/referenced twice like mentioned above, wouldn't it increase the size of the sketch unnecessarily?

[![Screenshot of Adafruit_BME280 header file][1]][1]

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

Example Sketch that comes with the library

    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    #define BME_SCK 13
    #define BME_MISO 12
    #define BME_MOSI 11
    #define BME_CS 10

    #define SEALEVELPRESSURE_HPA (1013.25)

    Adafruit_BME280 bme; // I2C
    //Adafruit_BME280 bme(BME_CS); // hardware SPI
    //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

    unsigned long delayTime;

    void setup() {
        Serial.begin(9600);
        while(!Serial);    // time to get serial running
        Serial.println(F("BME280 test"));

        unsigned status;

        // default settings
        status = bme.begin();
        // You can also pass in a Wire library object like &Wire2
        // status = bme.begin(0x76, &Wire2)
        if (!status) {
            Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
            Serial.print("SensorID was: 0x"); Serial.println(bme.sensorID(),16);
            Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
            Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
            Serial.print("        ID of 0x60 represents a BME 280.\n");
            Serial.print("        ID of 0x61 represents a BME 680.\n");
            while (1) delay(10);
        }

        Serial.println("-- Default Test --");
        delayTime = 1000;

        Serial.println();
    }

    void loop() {
        printValues();
        delay(delayTime);
    }

    void printValues() {
        Serial.print("Temperature = ");
        Serial.print(bme.readTemperature());
        Serial.println(" *C");

        Serial.print("Pressure = ");

        Serial.print(bme.readPressure() / 100.0F);
        Serial.println(" hPa");

        Serial.print("Approx. Altitude = ");
        Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
        Serial.println(" m");

        Serial.print("Humidity = ");
        Serial.print(bme.readHumidity());
        Serial.println(" %");

        Serial.println();
    }

title: is it necessary to include libraries that are specified in the header file already?

Answers: 1

body:
Historically it was necessary, yes. In times past the IDE would look only in your sketch to find the list of libraries to compile and link. However much progress has been made in recursive library searching, whereby the IDE can now find libraries that are included by other libraries.

I am not sure when that change was implemented, but it was a long time coming and is only recently that it's worked.

So if you are distributing code for other people to use then it's a good idea to still add the libraries in the sketch - just in case they're using an older version of the IDE that can't find the libraries included by other libraries.


body:
So I've got this code
```

String GetTimeString(){
    strftime(dateArray, 100, dateFormat, getTimeInfo());
    dateString = String(dateArray);
    Serial.println(dateString);
    return dateString;
}
```
Being called later like this:
```
document["Time"] = GetTimeString();
```

But the resulting object looks like this:

>September 12 2020 09:49:04
>{"DryBulbTemp":80.762,"WetBulbTemp":72.74606,"Pressure":398.9942,"Humidity":68.32129,"Time":null}

So it behaves this way no matter if I print what comes out of the function immediately before the assignment to the "Time" property.  Is ArduinoJson just broken?

title: ArduinoJson is not adding string to JsonObject. ArduinoJson broken?

Answers: 1

body:
ArduinoJson 6 works with fixed memory allocation.

When you create a [`JsonDocument`](https://arduinojson.org/v6/api/jsondocument/), you must specify its memory capacity.
If the capacity is too small, [some parts will be missing](https://arduinojson.org/v6/faq/why-is-the-output-incomplete/).

The solution is to increase the capacity of the [`JsonDocument`](https://arduinojson.org/v6/api/jsondocument/).
Use the [ArduinoJson Assistant](https://arduinojson.org/v6/assistant/) to know the memory requirements for your project.


body:
I'm using an Arduino Mega to control motors via PWM and Adafruit DRV8871 motor drivers.  I also use TIMER1 for a timed interrupt.  After adding the TIMER1 interrupt I discovered I had problems with motor control, which I finally tracked down to using pins 11 & 12 for PWM simultaneously with using TIMER1 for timed interrupts.

My initial thought was to change the timer used for the ISR to avoid the pin 11/12 conflict, but now I'm uncertain as to what the restrictions are for using pins associated with timers.  I now realize that pins associated with a timer interrupt can't be used for PWM using analogWrite(int val), but can they be used as general purpose digital outputs?

For instance, if I change from TIMER1 to TIMER0 for my timer interrupt, that appears to change the pin dependency from 11/12 to 4/13.  I don't use pin 13, but I do use pin 4 as a digital output.  Will using pin 4 as a digital output still work properly?

TIA,

Frank

title: Timers, PWM pins and digital outputs on Arduino Mega

Answers: 1

body:
You can use them for any purpose other than PWM.  You can even use them for PWM as long as the settings for the timer allow you to produce the waveform you want.

The reason PWM broke was that you had changed the settings for the timer.  The timer is what controls the PWM.  When you changed those settings you either turned the PWM function off or set some setting where it wouldn't work.  Then the pins associated with that timer didn't get PWM anymore.  You can do anything else you want that doesn't involve the timer including use the pin for input or output or any other special function it has not related to the timer.

If you change the timer interrupt to TIMER0, then you run the risk of delay, millis, and micros stop working right.  They depend on the TIMER0 overflow interrupt running at a set interval to count time.  It depends on how you set the timer up.

I would suggest you do some reading on how these timers work.  The Datasheet for the ATMega328P chip is a great place to start.


body:
I am trying to make a auto fish feeder to feed my fish every 6hours. I want to implement RTC module to my code. So far I've been using only an arduino and a servo using this as a code:

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(15);
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
      // Wait for 12h
    delay(6 * 3600000);
}
```

The RTC module I have is the DS1302. It's library cn be downloaded [here](http://www.rinkydinkelectronics.com/library.php?id=5)
The code for the clock is this:

```
// DS1302_Serial_Hard
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
// web: http://www.RinkyDinkElectronics.com/
//
// A quick demo of how to use my DS1302-library to
// retrieve time- and date-date for you to manipulate.
//
// I assume you know how to connect the DS1302.
// DS1302:  CE pin    -> Arduino Digital 2
//          I/O pin   -> Arduino Digital 3
//          SCLK pin  -> Arduino Digital 4

#include <DS1302.h>

// Init the DS1302
DS1302 rtc(2, 3, 4);

// Init a Time-data structure
Time t;

void setup()
{
  // Set the clock to run-mode, and disable the write protection
  rtc.halt(false);
  rtc.writeProtect(false);

  // Setup Serial connection
  Serial.begin(9600);

  // The following lines can be commented out to use the values already stored in the DS1302
  rtc.setDOW(FRIDAY);        // Set Day-of-Week to FRIDAY
  rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  rtc.setDate(6, 8, 2010);   // Set the date to August 6th, 2010
}

void loop()
{
  // Get data from the DS1302
  t = rtc.getTime();

  // Send date over serial connection
  Serial.print("Today is the ");
  Serial.print(t.date, DEC);
  Serial.print(". day of ");
  Serial.print(rtc.getMonthStr());
  Serial.print(" in the year ");
  Serial.print(t.year, DEC);
  Serial.println(".");

  // Send Day-of-Week and time
  Serial.print("It is the ");
  Serial.print(t.dow, DEC);
  Serial.print(". day of the week (counting monday as the 1th), and it has passed ");
  Serial.print(t.hour, DEC);
  Serial.print(" hour(s), ");
  Serial.print(t.min, DEC);
  Serial.print(" minute(s) and ");
  Serial.print(t.sec, DEC);
  Serial.println(" second(s) since midnight.");

  // Send a divider for readability
  Serial.println("  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -");

  // Wait one second before repeating :)
  delay (1000);
}
```

So the question here is, how can I set up my code to work with RTC, in order to move the servo every 6 hours?

title: How to rotate servo every 12 hours using RTC module?

Answers: 1

body: You have to spend some time and practice coding, it does not come over night. As far as your timing look up for an alarm clock sketch that will do what you want.  Once you understand that you should only have to add a few lines of code. As far as open source the tools you are using are open source. Remember there are people out there that are expertes and there people just starting so expect what you find to fall some in that range of quality.


body:
I have an 8Mhz ATM32u4 that is able to read external pulse inputs at 125ns ticks using InputCapture3 (PC7) on its 16-bit timer.  Is there a magical way (bitbanging?) to get around 10ns tick resolution to read pulses?  Edit:  like ADC conversions to allow 16-bit systems 24-bit accuracy via creative coding, etc.

If there is no magic, I should use a faster CPU?  I am limited in coding pretty much to AVR type CPUs in the Arduino IDE.  So wondering what AVR CPU would be fast enough for a 10ns tick that is incorporated already into like a Nano, UNO, etc?

Unless I am able to use Pin Interrupts that are able to read at 10ns intervals, then I could use ARM CPU types with Arduino IDE code which does not require me to dive deep into register level language.

Or, is there a stand-alone analog or digital IC that is able to read at 10ns intervals pulses that an Arduino can process?

Thank you.

Edit:  I would need to measure the length of a one-shot pulse only, not a continuous or changing signal. Down to 70us length with an accuracy of at least 18ns tick, but preferably 10ns to account for hardware, etc inaccuracies. This one-shot pulse could repeat not more frequently then 1 second apart, but likely several seconds apart. The signal is two positive square waves forming a pulse measuring not less than 70us from the positive rising edge to rising edge. The system measures the pulse length and sends it the user (serial, BLE, etc).

Edit 2: someone suggested a "one-shot pulse stretcher". Interesting concept...   The more I am looking into it, the more I think it's a very viable hardware solution to the AVR's processing speed limitation. One may say that this is hardware "bitbanging" by streching out the short pulse to a proportionally longer one that the MCU capture process can measure reliably/accurately. An example is this old IC from Linear Tech. See Fig 12 and Fig 13.    https://www.analog.com/media/en/technical-documentation/data-sheets/6752fc.pdf

http://www.anderswallin.net/2014/02/pulse-stretcher-v1/
[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/UpmId.jpg
  [2]: https://i.stack.imgur.com/YOGuh.png

The shortest expected pulse would be about 70us which needs to be measured at (around) a resolution of 18ns for the accuracy I need.  So I went with 10ns for design to allow for some accuracy "overhead".  That is between 4000-7000 counts/ticks  (18ns-10ns ticks) for the 70us signal.

If I stretch this same 70us signal to be measured with the pulse-stretcher to 700us and use the currently available 125ns tick interval of the ATM32u4, I should arrive in theory to about the same accuracy as using an 18ns tick for a 70us signal to be measured.

Here is a similar problem that was answered: https://electronics.stackexchange.com/questions/46922/lengthening-a-5-ns-pulse

title: Is there a way to get about a 10ns Timer resolution from an AVR CPU?

Answers: 2

body:
There is nothing you can do on the AVR processors that I know of, which can run on from a quite slow clock, and I think up to 24 MHz. Since your Uno / Leonardo / Micro run at 16 MHz that would be only an incremental speed improvement (to clock them at 24 MHz).

Your idea of bit-banging is interesting, but in general bit-banging is a last resort when you need extra things the hardware doesn't provide (like an extra SPI port) and in general will be slower, not faster, because it involves code rather than inbuilt hardware.

Running at 16 MHz each clock pulse is 62.5 ns which means that is the absolute most resolution it could count. I don't see why you can't count at the rate of 62.5 ns (rather than 125 ns), however that isn't 10 ns resolution.

> Or, is there a stand-alone analog or digital IC that is able to read at 10ns intervals pulses that an Arduino can process?

Very likely. There are probably dedicated counting chips that would do that for you. I haven't looked, but it is the sort of thing there would be a market for. Such a chip would probably use I2C or SPI to communicate, which is easy enough to interface to.

body:
1 ns is a billionth of a second. A 1 gHz clock has a cycle time of 1 ns. If you have a timer that's able to count single clock pulses you'd need a 1 gHz clock to get to 1 ns resolution. for 10 ns, you'd need a 100 mHz clock.

You won't get close to 10 ns resolution with an 8 mHz clocked device.


body:
```
#include <DS1302.h>
#include <Servo.h>
Time t;
Servo myservo;
int Hour;
int Min;
int Sec;
// Init the DS1302
DS1302 rtc(2, 3, 4);

void setup()
{
myservo.attach(9);
myservo.write(45);
// Set the clock to run-mode, and disable the write protection
rtc.halt(false);
rtc.writeProtect(false);
Serial.begin(9200);
// The following lines can be commented out to use the values already stored in the DS1302
//rtc.setDOW(SUNDAY); // Set Day-of-Week to SUNDAY
//rtc.setTime(8, 59, 50); // Set the time to 12:00:00 (24hr format)
//rtc.setDate(8, 25, 2019); // Set the date to August 25th, 2019
}

void loop()
{
t = rtc.getTime();
Hour = t.hour;
Min = t.min;
Sec = t.sec;
 Serial.print(Hour);
 Serial.print(":");
 Serial.print(Min);
 Serial.print(":");
 Serial.println(Sec);

//set the time for fish feeding
if ((Hour== 2 && Min== 0 && Sec== 2)||(Hour== 21 && Min== 0 && Sec== 2)) {
myservo.write(0);
delay (300);
myservo.write(45);
delay (300);}
}
```

title: what is wrong with this code? It doesn't work

Answers: 2

body:
**Explanation about the multiple time execution**

    if ((Hour== 9 && Min== 14)||(Hour== 21 && Min== 0)) {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
     }

1. Assume the time is 9:14:00 (9 hours, 14 minutes, 00 seconds).. the `if` condition passes.
2. The for loop will get executed. The duration needed to complete the loop is roughly 5 seconds.
3. Later, it will again go to the if condition. The time will be now 9:14:06.. it means, the condition will pass again.. the motor will again rotate.. this will repeat for about 11 times.. until the time changes to 9:15:00 or more.
4.  So the solution is to give a delay, before exiting the `if` loop if you wait for a minute with

    delay(60000);

then, the next 'if' condition will fail and works as per your expectation.

 _____________________
**Part 2:**

debugging:

            if ((Hour== 9 && Min== 14)||(Hour== 21 && Min== 0)) {
              for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
                // in steps of 1 degree
                myservo.write(pos);              // tell servo to go to position in variable 'pos'
                delay(15);
                Serial.println("moving");
        ....

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

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

body: I think the problem is that you have given the baud rate as 9200 but the minimum baud rate is 9600(Serial.begin(9600)). And change the baud rate in the serial monitor.


body:
My goal is to reduce pins being used for micro-controllers with limited pins, or projects requiring a few different digital input values.

How I intend to do so is by using ADC pins to gather four specific different values through resistors with analogRead, which would otherwise need 2 pins (!A+!B, !A+B, A+!B, and A+B).

    value = analogRead(adcPin1) >> 8;

This would give, if properly wired, 4 possible results like some sort of "Quartary bit", as analogRead yields a 10-bit response.

So my questions are the following:

- Can analogRead be sufficiently reliable to tell the difference between four possible values?
- What would the wiring/casing/etc. need to look like to prevent any errors?

Thanks!

title: Reliably using analogRead as a compact digitalRead

Answers: 0


body:
I hooked up 4 7Seg leds (CC) with NPN transistors on the cathode of each digit. I am using 74HC595 shift register connected in the circuit in a pretty common fashion. The code I am running is the basic scanning code for the 7seg. The problem is that I see the scanned numbers on other LED digits too. Attached is the image. I call them "ghosts". The circuit I am using has an Atmega328 with an internal 8MHz Osc. The resistors on the segments are 220Ohm and 4 BC547's on the cathodes of the digits with 1kOhm resistors on their base.
[![enter image description here][1]][1]

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

below is the code:

void loop() {

      cathode_high(); // blank the screen

      break_number(number);

      display_number();
     delay(1);

}

void break_number(int num) { // seperate the input number into 4 single digits

  first_digit = num / 1000;
  digits[0] = first_digit;

  int first_left = num - (first_digit * 1000);
  second_digit = first_left / 100;
  digits[1] = second_digit;
  int second_left = first_left - (second_digit * 100);
  third_digit = second_left / 10;
  digits[2] = third_digit;
  fourth_digit = second_left - (third_digit * 10);
  digits[3] = fourth_digit;

}

void display_number() { //scanning

  cathode_high();
  digitalWrite(latch, LOW);
  shiftOut(data, clk, LSBFIRST, numbers[digits[count]]);
  digitalWrite(CAS[count], HIGH);
  digitalWrite(latch, HIGH);
  count++;
  if (count == 4) {
    count = 0;
  }
}

void cathode_high() { //turn off all 4 digit
  digitalWrite(CA_1, LOW);
  digitalWrite(CA_2, LOW);
  digitalWrite(CA_3, LOW);
  digitalWrite(CA_4, LOW);
}

Any help would be highly appreciated. Thanx in advance!

title: Atmega328 and 4Digit 7 Segment ghost blinking!

Answers: 1

body:
You change cathodes (digits) before latching in the new data. So for a spit second the data for the previous digits is shown on the current digit.

Swapping `digitalWrite(CAS[count], HIGH);` and `digitalWrite(latch, HIGH);` should fix that.


body:
Im using `AsyncUDP` in an ESP32 project, where I initialize `AsyncUDP udpSender` and call `udpSender.write(sendbuffer, sendbuffer_size)` from both cores, with different buffers on each core.

One core is continually collecting GY-91 (accel/gyro/magnet) sensor data many times a second and sending it via UDP multiple times a second (after every collection), and the other one is collecting some other data like temperature once a second, as well as responding to commands a server sends.

So I'm basically using one sender on both cores and wondering if this is "thread-safe", if that terminology even applies to this scenario.

Can this cause problems? Is there a specific way this should be done? Like using semaphores?

title: ESP32 send UDP packets from both cores

Answers: 1

body:
I don't know if it's thread safe or not. However I would be inclined to play it sage and use a queue and notifications.

1. Create a queue
2. Create a "sender" thread that waits for notification then sends anything in the queue through UDP
3. Create any number of "sensor" threads that place items into the queue then notify the sender thread.


body:
    #include <SoftwareSerial.h>
    SoftwareSerial my (D6,D7); //(Rx,Tx)
    String msg;

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

    void gas()
    {

      Serial.println(msg);
      if (msg == "0")
      {
        Serial.println("Gas Leakage !!");
      }
      if(msg == "1") {
        delay(1);
      }
    }

    void loop() {

      msg = my.readStringUntil('\n');
      gas();
    }

//I am using software serial to exchange data from Arduino UNO to NodeMCU, i am receiving the data correctly but the "if statement condition" is not working with it. how can i make the if statement work?

title: Serial Communication, if statement not working

Answers: 1

body:
You are using `Serial.println()` to send the message. That function will add the combination `\r\n` as line ending to your message, which are the ASCII codes for return carriage and newline.

In your receiving code, you read until `\n`, so your message now reads `"0\r"`, which is of course not equal to `"0"`. Thus the if condition will never trigger.

When using `msg[0] == '0'` you are taking the first character out of the string and compare that to the character `'0'` (especially note the difference between `"0"`, which is a string, and `'0'`, which is a single character). Since you are only using the first character of the string, the `\r` is out of the picture; you aren't using it.

**What to do now?**

- You could send your message only with the `\n` character as line ending. For this only use `Serial.print()` instead of `Serial.println()` and add the line `Serial.print("\n");` directly after you send your message.

- You could write your own read-until code and just ditch every occurrence of the `\r` character.

- You can use `msg.trim()` to remove any white space characters at the start or end of your string, including the `\r` at the end. Then you can use the code, that you already wrote.

---

Note, that using `String`s on an Arduino is mostly considered evil. Especially if you want to use the code for a longer period or you are using `String` very often. The memory for a `String` is allocated dynamically, which can easily lead to heap fragmentation. For a better and longer explanation, look at [The Evils of Arduino Strings][1], a blog entry from Majenko, who is one of our biggest contributors here.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


body:
I was experimenting with external power supplies and noticed that the only way the Arduino can communicate with an externally powered sensor (through SPI) is when the GND pin under power AND the GND pin under AREF on the UNO is connected to the external ground?

From what I understand, both these pins are connected to the boards mutual ground (i.e. they are already internally connected)?

In the attached image both the orange and yellow wires were required and would not work individually.

I feel that either this shouldn't be the case or I am simply missing something and would appreciate an explanation.

Thanks!

[![Physical setup][1]][1]

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

title: Grounding Arduino UNO with external voltage source

Answers: 1

body:
The circuit in the image shows the plan of the Arduino Uno, as you can see the GND pin under AREF and in the GND under the Power pin VCC are connected.[![enter image description here][1]][1]

you can double-check this with a tester and figure it out.
so yes, they are internally connected.

now, in your breadboard you have connected GND to VIN, that's the problem, Vin is an input voltage that is regulated to supply 3.3V and 5V.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/btVk0.png
  [2]: https://i.stack.imgur.com/JOinj.png

So remember to share grounds with external voltage supplies (DC-DC), that set the circuit to the same reference.


body:
I've been trying to connect an MPU6050 to my MKR WIFI 1010 following [these general instructions][1] and using the I2CDev library, but I keep running into problems.

For a while the Arduino just didn't show up as connected in the IDE when all the pins were connected, which I think I've gathered was due to a lack of pull-up resistors for the SCL/SDA pins. Adding 10 kOhm pull-up resistors helped a little (in making the Arduino visible) but it would hang when trying to upload the example sketch. 2.2 kOhm resistors seemed to do the trick, where now the example sketches ([MPU6050_DMP6][2] or [MPU6050_raw][3]) can be uploaded. They still fail to read any actual values, however. The raw sketch gives 0 for everything, and the DMP6 sketch prints
```
Initializing I2C devices...
Testing device connections...
MPU6050 connection failed

Send any character to begin DMP programming and demo:
Initializing DMP...
DMP Initialization failed (code 1)
```

Does anyone know why the sensor still fails to give any measurements? I connect VCC and GND from the sensor to VCC (3.3V) and GND from my Arduino. SCL and SDA from the sensor are connected to VCC via 2.2 kOhm resistors and to the SCL and SDA pins of the Arduino (12 and 11). And INT from the sensor is connected to digital pin 2. (I tried this on a couple other pins like 0 and 1 since it seems from [the tech specs][4] that 2 is not an External Interrupt pin, but that didn't change anything.)

The sensor and examples worked without any extra effort on my Arduino Uno, but unfortunately I fried that with a 12V power supply by accident. I'll probably just get another Uno, but I'm curious why this didn't work, if I'm missing something about I2C or the MKR WIFI.

I'll also note that I had to add
```
define #BUFFER_LENGTH 64
```
to wire.h in order to get sketches including I2Cdev to compile (following these [instructions][5]).

  [1]: https://www.electronicshub.org/getting-started-arduino-mpu6050/
  [2]: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_DMP6/MPU6050_DMP6.ino
  [3]: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_raw/MPU6050_raw.ino
  [4]: https://store.arduino.cc/usa/mkr-wifi-1010
  [5]: https://forum.arduino.cc/index.php?topic=508669.0

title: How do I connect an MPU6050 sensor to an Arduino MKR WIFI 1010?

Answers: 1

body: The sensor was indeed broken, and I had no problems after ordering a new one.


body:
I would like help to continuously loop over my output pins after each sleep cycle.  I am trying to increment through each output pin during each successive interrupt.  Introducing this myIteration function causes immediate incrementing to final output pin and eliminates sleeping.

**EDIT**
To clarify a bit and clean up the code, I am having trouble getting the loop to increment over the output pins each time the interrupt is triggered.  It stays on the initialized pin value after each interrupt.

The reason I separate the if (state=HIGH) into two consecutive statements is because when I do not the debug LED remains on.

```
#include <LowPower.h>

const byte interrupt_pin = 2;                             // declare interrupt pin for PIR trigger
int musicPins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11};          // Initialize pins that play music in array, elements from 0 to 8
volatile byte state = LOW;                                // trigger threshold starts low
int pinCount = 9;
int previous = 0;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);                           // use builtin LED for debug
  pinMode(interrupt_pin, INPUT);                          // set interrupt pin as input

    for (int thisPin = 0; thisPin < pinCount; thisPin++) {      // set all music pins as High to start with no music during sensor initialization
    digitalWrite(musicPins[thisPin], HIGH);
    }
    for (int thisPin = 0; thisPin < pinCount; thisPin++) {      // set all music pins as outputs
    pinMode(musicPins[thisPin], OUTPUT);
    }

  delay(5000);                                            // wait so sensor can initialize
}

void loop() {

  attachInterrupt(digitalPinToInterrupt(interrupt_pin),interrupt_routine,RISING); // must attach each loop
  LowPower.powerDown(SLEEP_FOREVER,ADC_OFF,BOD_OFF);      // MCU sleep until interrupt
  detachInterrupt(digitalPinToInterrupt(interrupt_pin));  // remove interrupt

  if (previous==10){                                      // when variable gets to 10 reset to zero
    previous=0;
  }

  if (state==HIGH){                                       // PIR senses motion, sends high signal
    digitalWrite(LED_BUILTIN,HIGH);                       // debug LED turns on
    myOnIteration();                                      // musicPin number x turns on
    delay(100);                                           // wait to stabilize
    digitalWrite(LED_BUILTIN,LOW);                        // debug LED turns off
  }
  if (state==HIGH){                                       // separate statements to guarantee next steps happen
    myOffIteration();                                     // musicPin number x turns off
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);       // sleep for 8s after musicPin plays

  }

  previous++;                                             // increment before attaching next interrupt

}

////////Functions//////////
void interrupt_routine(){
  state = HIGH;
}

void myOnIteration() {                                    // cycle through output pins turning on once per interrupt
for (int count = previous; count < pinCount; count++) {
        digitalWrite(musicPins[count], LOW);
      }
}

void myOffIteration() {                                   // cycle through output pins turning off once per interrupt
for (int count = previous; count < pinCount; count++) {
        digitalWrite(musicPins[count], HIGH);
      }
}
```

title: For Loop function to iterate through outputs after interrupt

Answers: 1

body: Original code is updated with final version. A motion sensing interrupt iterates over multiple voice playback output pins and sleeps at low power for rest of time.


body:
I want to convert a hexadecimal string or an array of bytes to binary data.
For example, if i have a string like
`'424D368403'`
my output should be like
`b'BM6\x84\x03'`
The python code `binascii.unhexlify('424D368403')` gives the correct output.
But, I want to do this in arduino code.
Can someone help me in creating an arduino code / command in getting desired output?

title: Arduino code equivalent for python code binascii.unhexlify command

Answers: 0


body:
I have a project where I put an ESP32 to deep sleep for a certain amount of time, eg: 1h

To be able to self-awaken a cable must be connected from GPIO 16 to the reset pin, so basically the ESP pulls down pin 16 and causes itself to reset.

I also need the possibility to manually waken up the ESP, so in parallel to this cable I connect a button to GND, so I can manually reset the ESP and waken it up.

However I need to be able to tell if the ESP has awaken itself because one hour has passed or if it has been manually awaken.

I cannot connect the ESP to a internet time provider to check the time, so my first though wasto connect the button also to an input and read it when the ESP starts.

However the ESP won't start until the button forcing RST low is released and then it's too late to read it and see if it was pressed.

Is there a way that I can tell if the ESP was manually reset or if it woke up by itself?

title: Knowing if ESP32 wakes up itself or manually

Answers: 1

body:
I think you're getting confused between the ESP32 and the ESP8266. There is no need to connect GPIO16 to reset on the ESP32.

Instead the ESP32 has the "ULP" - Ultra Low-power Processor in it (essentially the RTC processor) which is what sends wakeup signals to the ESP32 cores. It is this which wakes the system up after an hour.

The ULP can also trigger a wakeup from other sources - most often used to wake up from an external signal, such as your button. But this only works if that signal is connected to one of the RTC input pins (GPIOs 34 to 39), or certain interrupt enabled pins (you can read more about what can wake the system up [here](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/sleep_modes.html#wakeup-sources)).

Once a wakeup has happened you can then query the ULP to find out why it woke the ESP32 up using the [`esp_sleep_get_wakeup_cause()`](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/sleep_modes.html#_CPPv426esp_sleep_get_wakeup_causev) function.


body:
I don't understand the following Debounce code. (The complete code is at the bottom.) From what I understand, when the pin reads something, we wait at least 50 milliseconds before performing anything. But doesn't the reading variable get reset every loop iteration, so `reading` equals zero in the inner if-condition in every iteration.

What I think is the sequence of events: loop(), loop(), loop(), "loop(), button press, reading=1, set lastDebounceTime, first if condition fails because we have to wait, set lastButtonState=1", loop(), loop(),loop(),"loop() enough time has passed, but since no button press at in this iteration and the last few, reading and lastButtonState equal zero", loop(), ... .

However, this code works.

Why do we save `reading` in a local variable? Won't the code virtually always be this, then:
```
if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if 0 != buttonState) {
      buttonState = 0;

...
```
Entire code:

```
/*
  Debounce

  Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
  press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a
  minimum delay between toggles to debounce the circuit (i.e. to ignore noise).

  The circuit:
  - LED attached from pin 13 to ground
  - pushbutton attached from pin 2 to +5V
  - 10 kilohm resistor attached from pin 2 to ground

  - Note: On most Arduino boards, there is already an LED on the board connected
    to pin 13, so you don't need any extra components for this example.

  created 21 Nov 2006
  by David A. Mellis
  modified 30 Aug 2011
  by Limor Fried
  modified 28 Dec 2012
  by Mike Walters
  modified 30 Aug 2016
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Debounce
*/

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading. Next time through the loop, it'll be the lastButtonState:
  lastButtonState = reading;
}

```
(Debounce code taken from: https://www.arduino.cc/en/tutorial/debounce.)

title: Understanding Debounce code

Answers: 1

body:
loop() does not need any time and repeats permanently.

`lastButtonState` is `reading` from previous loop run.

As long as the button bounces, `lastDebounceTime` is updated.

Only when the button has settled (either pressed or released), the condition

      ((millis() - lastDebounceTime) > debounceDelay)

becomes `true` and the code is executed -> if `buttonState` (the previous **debounced** state) and `reading` show a change to HIGH, the led state is toggled.

Not sure if this explanation makes anything clearer, as it is clear already as it stands, IMO.


body:
I have this project where I control a bluetooth audio module with an arduino. In this case, I have used an arduino nano. But then, I have been meaning to add volume control to the project so I use a pt2257. But the sounds that it gives to me is my audio plus heavy buzzing sound and no matter how much attenuation that I set the volume doesnt seems to change. Can anyone help me?

Here is the schematics that I use for the PT2257:

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

I have tried giving Vdd 5V from arduino, and also 5V from a seperate power supply. But it seems there is no difference.

Here is the code that i use:
```Arduino
    void setup() {
      delay(1000);
      Wire.begin();
      Serial.begin(115200);
    }
    void loop() {
      Wire.beginTransmission(Volume_address);
      Wire.write(0b011100000);    // set low attenuation
      Serial.print("result 1: ");
      Serial.println(Wire.endTransmission());
      delay(2000);
      Wire.beginTransmission(Volume_address);
      Wire.write(0b11111111);  // set full attenuation
      Serial.print("result 2: ");
      Serial.println(Wire.endTransmission());
      delay(2000);
    }
```
[Here is the link to PT2257 datasheet if you need it][2]

EDIT:
Here is how I connect CSR8645 Output to my active speaker, before I add a attenuation IC. It works like a charm like this, but I need to add a volume control.

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

  [1]: https://i.stack.imgur.com/7uJLX.png
  [2]: http://www.princeton.com.tw/Portals/0/Product/PT2257.pdf
  [3]: https://i.stack.imgur.com/xxXzh.png

title: PT2257 only gives me heavy buzzing sound

Answers: 1

body:
many amps and BT audio chips use `differential` input/outputs. none of the inputs nor outputs are considered grounds.

the `Lp(left,postivie) Ln, Rp and Rn` on your audio chip should be connected to loads directly. Ln or Rn are not audio grounds. so you can't use simple POT volume controls or any processor or amplifier chip that doesn't support differential IOs. so, you can't use PT2257 in this circuit.

for better understanding here are two audio signal types:

 1. the simple, well known one, which consists of `GND and an audio IN per channel`. you can use many amplifiers, processors (e.h. PT2257) and POT volume controls. and one end of the output (e.g. speaker) is connected to GND.
 2. the differntial audio signal which consists of a GND and a pair of `IN+,IN- per channel`. you can't use the soulutions mentioned above. for example, if you wanted to amplify the output signal of the bluetooth chip, you have to use something like PAM8302, 2.5W mono class D audio amp **per channel**. note the IOs:

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

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


body:
I'm currently in a planning phase for a project.
I want to read some sensor data over Modbus TCP, do some simple calculations on the Arduino and publish the results over MQTT. Which means I have 2 RJ-45s and two different protocols.

Given a Arduino Mega with an Ethernet shield.
Does it work if I simply add a network switch and connect the sensor and an internet router to it, and use both protocols in parallel?
Or are there any problems running such a thing on only one Arduino?

title: Modbus TCP together with MQTT over same ethernet

Answers: 1

body:
> Does it work if I simply add a network switch and connect the sensor and an internet router to it, and use both protocols in parallel?

Kind of, yes. You just connect both the MODBUS device and the Arduino to the network provided by the router. The Arduino is just a normal network device - the IP address for it allocated by the router, as is the MODBUS device.

Any device can communicate with any other device in a network.


body:
I want to build a device to measure deceleration force when a car brakes. I am using a MPU6050 for get data and I read from it acceleration on X,Y,Z axes in m/s2 and also it gives me gyro in degrees/second.
My question is how can I use these gyro values to correct acceleration? Basically when apply brake the position of the axes are changing .
Also I guess I need to calculate the deviation as well if the car goes to the left or right during brake process.
Any ideas, hints will be very appreciated
Thank you very much

title: Get deceleration (negative acceleration when apply brake force)

Answers: 0


body:
My final goal is to replicate the process with which the PC programs the arduino.
I have gone through the commands.h file and made a couple of attempts to get the logic right. But no success at flashing the arduino.
Is there any way to view the Hex commands that are written to the arduino from the PC? Something like verbose but list every hex command.
My idea is that I will just replicate the same commands and try uploading hex files from SD card.

title: log STK500v2 commands while flashing a Mega

Answers: 1

body:
Add the flag `-vvvv` to the `avrdude` command. That will show you the flow of data between the computer and the Arduino.

You can copy and paste the executed command from the IDE and run it in a terminal / command window adding the flag manually. Or you could modify the platform.txt file for the AVR core.


body:
I decided to make a pcb based on the atsam3x8e (microcontroller used in Arduino Due). For the design I copied most of the layout that I found [on this site][1] and looked at the official Arduino Due schematic as well but decided that I didn't need everything. This is the schematic that I made and the pcb:

[![enter image description here][2]][2]
[![My schematic][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]

The problem is that my laptop doesn't see the "Arduino Due / atsam" when I connect the USB to my pc with a USB cable (with data lines). I understood that the chip chips with the SAMBA bootloader in ROM and that it should be programmable via native usb connection to the chip.

I supply 3V3 with a bench power supply.
Then I tried to follow the checklist for this microcontroller: [checklist][6].
All voltages seem to arrive on the chip. VDDout makes a 1.7 voltage as it should.
I have a clocksignal on my 12Mhz crystal. I don't have a clock signal on my 32khz crystal but when measuring on an official arduino due I also didn't see a clock signal here so I guess this oscillator isn't always on.

I made some wire patches: decoupling cap were not ground referenced and one oscillator pin of 12 Mhz wasn't connected.

Any ideas on how I could further debug this?

  [1]: https://digibird1.wordpress.com/arduino-due-clone-based-on-the-atmel-sam3x8e-kicad-design/
  [2]: https://i.stack.imgur.com/L3FB1.jpg
  [3]: https://i.stack.imgur.com/zBtRW.jpg
  [4]: https://i.stack.imgur.com/5QFuK.jpg
  [5]: https://i.stack.imgur.com/6ywGR.jpg
  [6]: https://www.microchip.com/wwwAppNotes/AppNotes.aspx?appnote=en591608

title: Getting atsam3x8e (Arduino Due) to work

Answers: 0


body:
**Datasheet**  https://github.com/espressif/esp-hosted/files/5190376/ESP-32F.pdf

The below code is not working.
I can see only White screen
```

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#define TFT_CS        26 // Hallowing display control pins: chip select
#define TFT_RST       16 // Display reset
#define TFT_DC        17 // Display data/command select
#define TFT_BACKLIGHT  13 // Display backlight pin

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 19  // Data out
#define TFT_SCLK 18  // Clock out
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

void setup(void) {
  Serial.begin(115200);
  Serial.print(F("Hello! ST77xx TFT Test"));

  //#ifdef ADAFRUIT_HALLOWING
  // HalloWing is a special case. It uses a ST7735R display just like the
  // breakout board, but the orientation and backlight control are different.
  tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
  pinMode(TFT_BACKLIGHT, OUTPUT);
  digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
  //#else
  // Use this initializer if using a 1.8" TFT screen:
  //  tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

  // OR use this initializer (uncomment) if using a 1.44" TFT:
  //  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 0.96" 180x60 TFT:
  //  tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

  // OR use this initializer (uncomment) if using a 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240
  //#endif

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  testdrawtext("Hello World asdf sdf adfsdf sdf sdf sdf sdf sdf ", ST77XX_BLACK);
  delay(1000);

  Serial.println("done");
  delay(1000);
}

void loop() {
  tft.invertDisplay(true);
  delay(500);
  tft.invertDisplay(false);
  delay(500);
}

void testdrawtext(char *text, uint16_t color) {
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);
}

```

title: Arduino ESP32F-TFT-1.44 Driver

Answers: 1

body:
```
#include <WiFi.h>

#include <time.h>
#include "AudioFileSourcePROGMEM.h"
#include "AudioGeneratorTalkie.h"
#include "AudioOutputI2S.h"

#ifndef STASSID
#define STASSID "WIFI_SSID"
#define STAPSK  "WIFI_PASSWORD"
#endif

const char *ssid = STASSID;
const char *pass = STAPSK;

long timezone = 7;
byte daysavetime = 1;

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#define TFT_CS        26 // Hallowing display control pins: chip select
#define TFT_RST       16 // Display reset
#define TFT_DC        17 // Display data/command select
#define TFT_BACKLIGHT  13 // Display backlight pin

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 23  // Data out
#define TFT_SCLK 18  // Clock out
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

AudioGeneratorTalkie *talkie;
AudioOutputI2S *out;

bool GetLocalTime(struct tm * info, uint32_t ms) {
  uint32_t count = ms / 10;
  time_t now;

  time(&now);
  localtime_r(&now, info);

  if (info->tm_year > (2016 - 1900)) {
    return true;
  }

  while (count--) {
    delay(10);
    time(&now);
    localtime_r(&now, info);
    if (info->tm_year > (2016 - 1900)) {
      return true;
    }
  }
  return false;
}

int threshold = 40;
bool touch1detected = false;
bool touch2detected = false;

void gotTouch1() {
  touch1detected = true;
}

void gotTouch2() {
  touch2detected = true;
}
void initLCD() {
  tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
  pinMode(TFT_BACKLIGHT, OUTPUT);
  digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);

}
void setup(void) {

  touchAttachInterrupt(T2, gotTouch1, threshold);
  touchAttachInterrupt(T0, gotTouch2, threshold);

  Serial.begin(115200);
  Serial.print(F("Hello! ST77xx TFT Test"));

  initLCD();

  /*
    delay(1000);

    // tft print function!
    tftPrintTest();
    delay(4000);

    // a single pixel
    tft.drawPixel(tft.width() / 2, tft.height() / 2, ST77XX_GREEN);
    delay(500);

    // line draw test
    testlines(ST77XX_YELLOW);
    delay(500);

    // optimized lines
    testfastlines(ST77XX_RED, ST77XX_BLUE);
    delay(500);

    testdrawrects(ST77XX_GREEN);
    delay(500);

    testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
    delay(500);

    tft.fillScreen(ST77XX_BLACK);
    testfillcircles(10, ST77XX_BLUE);
    testdrawcircles(10, ST77XX_WHITE);
    delay(500);

    testroundrects();
    delay(500);

    testtriangles();
    delay(500);

    mediabuttons();
    delay(500);

    Serial.println("done");
    delay(1000);

    //*/

  Serial.print("Connecting to ");
  Serial.println(ssid);
  testdrawtext("Connecting to ", ST77XX_WHITE);

  WiFi.begin(ssid, pass);

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

  Serial.println("WiFi connected");

  tft.fillScreen(ST77XX_BLACK);
  testdrawtext(strcat("WiFi connected ", ""), ST77XX_WHITE);
  clearText();
  delay(1000);

  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Contacting Time Server");

  configTime(3600 * timezone, daysavetime * 3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org");
  struct tm tmstruct ;
  do {
    tmstruct.tm_year = 0;
    Serial.printf(".");
    GetLocalTime(&tmstruct, 5000);
    delay(100);
  } while (tmstruct.tm_year < 100);

  audioLogger = &Serial;
  out = new AudioOutputI2S(0, 1);
  talkie = new AudioGeneratorTalkie();
  talkie->begin(nullptr, out);
}

char temp[300];

int alarmHours = 5;
int alarmMinutes = 44;

void loop() {
  //  tft.invertDisplay(true);
  //  delay(500);
  //  tft.invertDisplay(false);
  //  delay(500);

  struct tm tmstruct ;
  tmstruct.tm_year = 0;
  GetLocalTime(&tmstruct, 5000);
//  Serial.printf("\nNow is : %d-d-d d:d:d Alarm - : -\n",
//                tmstruct.tm_year + 1900, tmstruct.tm_mon + 1,
//                tmstruct.tm_mday, tmstruct.tm_hour,
//                tmstruct.tm_min, tmstruct.tm_sec,
//                alarmHours, alarmMinutes);
  Serial.printf("\nNow is : d:d:d\n",
                tmstruct.tm_hour,
                tmstruct.tm_min, tmstruct.tm_sec);

  //  sprintf(temp, "%d-d-d% 02d:d:d Alarm - : -\n", tmstruct.tm_year + 1900, tmstruct.tm_mon + 1, tmstruct.tm_mday, tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec, alarmHours, alarmMinutes);
  sprintf(temp, "d:d:d", tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec);

  if (60 * alarmHours + alarmMinutes <= 60 * tmstruct.tm_hour + tmstruct.tm_min) {
    Serial.printf("-Alarm-");
    Serial.printf("\n** Now is : %d-d-d d:d:d Alarm - : -\n",
                  tmstruct.tm_year + 1900, tmstruct.tm_mon + 1,
                  tmstruct.tm_mday, tmstruct.tm_hour,
                  tmstruct.tm_min, tmstruct.tm_sec,
                  alarmHours, alarmMinutes);
    //    sayTime(tmstruct.tm_hour, tmstruct.tm_min, talkie);
    //    initLCD();
  }

  //  clearText();

  tft.fillRect(40, 30, 50, 10, ST77XX_BLACK );
  //  testdrawtext(temp, ST77XX_WHITE);
  tft.setCursor(40, 30);
  tft.setTextColor(ST77XX_WHITE);
  //  tft.setTextWrap(true);
  tft.print(temp);

  delay(1000);

  if (touch1detected) {
    touch1detected = false;
    Serial.println("Touch 1 detected");
    alarmMinutes = alarmMinutes + 10;
  }
  if (touch2detected) {
    touch2detected = false;
    Serial.println("Touch 2 detected");
    alarmMinutes = alarmMinutes + 10;
  }
}

void testlines(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x = 0; x < tft.width(); x += 6) {
    tft.drawLine(0, 0, x, tft.height() - 1, color);
    delay(0);
  }
  for (int16_t y = 0; y < tft.height(); y += 6) {
    tft.drawLine(0, 0, tft.width() - 1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x = 0; x < tft.width(); x += 6) {
    tft.drawLine(tft.width() - 1, 0, x, tft.height() - 1, color);
    delay(0);
  }
  for (int16_t y = 0; y < tft.height(); y += 6) {
    tft.drawLine(tft.width() - 1, 0, 0, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x = 0; x < tft.width(); x += 6) {
    tft.drawLine(0, tft.height() - 1, x, 0, color);
    delay(0);
  }
  for (int16_t y = 0; y < tft.height(); y += 6) {
    tft.drawLine(0, tft.height() - 1, tft.width() - 1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x = 0; x < tft.width(); x += 6) {
    tft.drawLine(tft.width() - 1, tft.height() - 1, x, 0, color);
    delay(0);
  }
  for (int16_t y = 0; y < tft.height(); y += 6) {
    tft.drawLine(tft.width() - 1, tft.height() - 1, 0, y, color);
    delay(0);
  }
}

char prevText[300];

void clearText() {
  testdrawtext(prevText, ST77XX_BLACK);
}

void testdrawtext(char *text, uint16_t color) {
  strcpy(prevText, text);
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);
}

void testfastlines(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t y = 0; y < tft.height(); y += 5) {
    tft.drawFastHLine(0, y, tft.width(), color1);
  }
  for (int16_t x = 0; x < tft.width(); x += 5) {
    tft.drawFastVLine(x, 0, tft.height(), color2);
  }
}

void testdrawrects(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x = 0; x < tft.width(); x += 6) {
    tft.drawRect(tft.width() / 2 - x / 2, tft.height() / 2 - x / 2 , x, x, color);
  }
}

void testfillrects(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x = tft.width() - 1; x > 6; x -= 6) {
    tft.fillRect(tft.width() / 2 - x / 2, tft.height() / 2 - x / 2 , x, x, color1);
    tft.drawRect(tft.width() / 2 - x / 2, tft.height() / 2 - x / 2 , x, x, color2);
  }
}

void testfillcircles(uint8_t radius, uint16_t color) {
  for (int16_t x = radius; x < tft.width(); x += radius * 2) {
    for (int16_t y = radius; y < tft.height(); y += radius * 2) {
      tft.fillCircle(x, y, radius, color);
    }
  }
}

void testdrawcircles(uint8_t radius, uint16_t color) {
  for (int16_t x = 0; x < tft.width() + radius; x += radius * 2) {
    for (int16_t y = 0; y < tft.height() + radius; y += radius * 2) {
      tft.drawCircle(x, y, radius, color);
    }
  }
}

void testtriangles() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 0xF800;
  int t;
  int w = tft.width() / 2;
  int x = tft.height() - 1;
  int y = 0;
  int z = tft.width();
  for (t = 0 ; t <= 15; t++) {
    tft.drawTriangle(w, y, y, x, z, x, color);
    x -= 4;
    y += 4;
    z -= 4;
    color += 100;
  }
}

void testroundrects() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 100;
  int i;
  int t;
  for (t = 0 ; t <= 4; t += 1) {
    int x = 0;
    int y = 0;
    int w = tft.width() - 2;
    int h = tft.height() - 2;
    for (i = 0 ; i <= 16; i += 1) {
      tft.drawRoundRect(x, y, w, h, 5, color);
      x += 2;
      y += 3;
      w -= 4;
      h -= 6;
      color += 1100;
    }
    color += 100;
  }
}

void tftPrintTest() {
  tft.setTextWrap(false);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 30);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_YELLOW);
  tft.setTextSize(2);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(3);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_BLUE);
  tft.setTextSize(4);
  tft.print(1234.567);
  delay(1500);
  tft.setCursor(0, 0);
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(0);
  tft.println("Hello World!");
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(p, 6);
  tft.println(" Want pi ? ");
  tft.println(" ");
  tft.print(8675309, HEX); // print 8,675,309 out in HEX!
  tft.println(" Print HEX!");
  tft.println(" ");
  tft.setTextColor(ST77XX_WHITE);
  tft.println("Sketch has been");
  tft.println("running for : ");
  tft.setTextColor(ST77XX_MAGENTA);
  tft.print(millis() / 1000);
  tft.setTextColor(ST77XX_WHITE);
  tft.print(" seconds.");
}

void mediabuttons() {
  // play
  tft.fillScreen(ST77XX_BLACK);
  tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
  delay(500);
  // pause
  tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
  delay(500);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
  delay(50);
  // pause color
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}
```


body:
*disclaimer I am new at hardware/circuits*

I am currently trying to connect two MPU-6050 to a single Micro board.
In addition, there are 5 additional buttons to be connected.

I am under the impression to connect multiple devices to the I2C bus, there must be unique addresses. I read there was a way to make unique addresses (https://playground.arduino.cc/Main/MPU-6050/#multiple).

However I am not sure of the wiring or if the voltage/resistors/anything is supposed to be located.

I have a sketch of what it may look like.
[![enter image description here][1]][1]

Can anyone help me verify that this is the proper configuration? Or what a proper configuration would look like?

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

title: Wiring Multiple MPU 6050 to Micro/Lenardo

Answers: 1

body:
Buttons are just buttons. You can have them "active high" with pulldown resistors as you have there (10K is fine. The actual value doesn't really matter, just don't have it too low or excess current will be drawn), or "active low" without resistors and connecting to ground when pushed instead of VCC and use INPUT_PULLUP. The choice is yours. There's no real benefit in this situation to either way of doing it.

The critical part is your AD0 connection. Whether you connect one to ground and leave the other unconnected, or connect one to VCC and leave the other unconnected, depends entirely on the design of the breakout board. It should have a resistor on the AD0 pin internally that either connects it to GND or to VCC. If it connects to GND then you need to link that pin to VCC to override it. If it connects it to VCC (or more likely 3.3V) internally then you need to connect it to GND to override it.

To find out which you will have to either consult the documentation or schematic for the board or measure the voltage at the AD0 pin. If it measures 0V (within a few mV) then it connects to ground and you will have to connect it to VCC to override it. If it measures more (probably nearer 3.3V) then connect it to ground to override it.

Because those chips are 3.3V and the board contains a 3.3V regulator (if your boards are the same as you picture in your wiring diagram) the chances are that the AD0 is pulled up to 3.3V so you just need to connect one to ground.

So it looks to me like your wiring diagram is most likely suitable and correct, pending confirmation of the pullup/pulldown in the AD0 pin.


body:
I am using Arduino UNO with a RTC DS3231 module.
I have connected SDA & SCL pins of RTC DS3231 with Arduino SDA & SCL pins near AREF pin.
RTC module is having attached battery also.
My code is as below :
```
#include <RTClib.h>
#include <Wire.h>
RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
};

void setup() {
  Serial.begin(9600);
  Wire.begin();
  delay(3000);
  //rtc.begin();
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
       // Following line sets the RTC with an explicit date & time
    // for example to set January 27 2017 at 12:56 you would call:
    // rtc.adjust(DateTime(2017, 1, 27, 12, 56, 0));
  }
}

void loop() {
  DateTime now = rtc.now();
  Serial.println("Current Date & Time: ");
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.println("Unix Time: ");
    Serial.print("elapsed ");
    Serial.print(now.unixtime());
    Serial.print(" seconds/");
    Serial.print(now.unixtime() / 86400L);
    Serial.println(" days since 1/1/1970");

    // calculate a date which is 7 days & 30 seconds into the future
    DateTime future (now + TimeSpan(7,0,0,30));

    Serial.println("Future Date & Time (Now + 7days & 30s): ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(1000);

}
```
While running the above command and opening the Serial Monitor, I always get following output:
```
Couldn't find RTC
```
Can anyone help me to correct this problem.

title: DS3231 rtc.begin() always returning false

Answers: 1

body: No fault is there in code. Rather, it was an faulty connection which prevented RTC module from working. Now, after restoration, the RTC module is working fine.


body: I am using FastLED to drive 16 pixels on an addressable  WS2812B RGB LED strip. My application has extremely tight timing constraints. Specifically, I need to turn the LEDs on and off within less than 1 ms. I tried FastLED but it requires a minimum of 2.5 ms to execute the Show command, regardless of the number of LEDs attached. I analyzed another library and that one has the exact same limitation. In fact, I found a snippet of code that said roughly: "if this operation performs in less than 2500 us, then wait idly until the 2500 us have passed. Apparently this wait is necessary due to timing requirements of WS2812x strips. Does anyone have any advise about other addressable RGB LED strips or libraries that can be turned on and off within 1 ms?

title: Can FastLED be made faster?

Answers: 1

body:
By default the fastLed is limiting the refresh rate to 400 fps (i.e. 2.5ms).

You can disable that with `FastLED.setMaxRefreshRate(0);`


body:
I have found the git source for SerialMonitor (`Arduino/app/src/processing/app/*`) but unable to find it in the installed Arduino IDE. I am using Ubuntu 20.04 64-bit.

I want to make changes to it, not so much a terminal emulator but just perform simple ASCII control characters like backspace (0x08). Some advice on replacing it would be appreciated too; I guess it involves `jar` files (I am not a java developer).

I have read elsewhere about (and used) various other terminal-type programs, but of course they stop the IDE from uploading sketches. So not much good for development.

Or if anyone knows of an already-improved Serial Monitor, and how to install it for the IDE, then that could be perfect.

title: Where can I find SerialMonitor.java in installed Arduino IDE 1.8.13?

Answers: 2

body:
You can't just "find and replace" that file.

Java isn't distributed as source code. It's compiled "bytecode" that isn't modifiable by a human.

You would need to download *all* the source code, make your changes to it, and then recompile it.

Or, simpler: just use a more capable serial terminal program, such as "Putty" or "TeraTerm" in Windows, or "Minicom" or "Screen" on Linux. I have no idea what is available for OS X.

body:
After some searching, I found that [Building Arduino - Steps for First Time Setup][1] was good. It was tricky to find; most searches for 'Build Arduino' assume it's a project with an Arduino, rather than the IDE.

By building this way, I could change the source, then inside the `build` folder run `ant run`. So, no need to actually know where it goes.

I had a problem with it grumbling about
`Incorrect IDE installation folder:
Your copy of the IDE is installed in a subfolder of your sketchbook.
Please move the IDE to another folder.`
which would have been more useful if it had said WHAT settings needed changing.

It turns out that `preferences.txt` had a conflict with settings `sketchbook.path` and `runtime.ide.path`. I changed `sketchbook.path`. All is now good.

  [1]: https://github.com/arduino/Arduino/wiki/Building-Arduino


body:
I have a [RDM6300][1] RFID module which I am trying to connect to an [ESP8266][2] by using [rdm6300.h][3] library.

I had it all up an running all along with other components but we had connected to the ESP8266 but we had to move from the breadboard to an actual wired setup. Everything kept on working except for the RFID reader. The way I used to do it was by making a reference to [this][4] approach (more or less):

    #include <rdm6300.h>

    #define RDM6300_RX_PIN 4
    #define READ_LED_PIN 13

    Rdm6300 rdm6300;

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

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

     rdm6300.begin(RDM6300_RX_PIN);

     Serial.println("\nPlace RFID tag near the rdm6300...");
    }

    void loop()
    {
     /* if non-zero tag_id, update() returns true- a new tag is near! */
     if (rdm6300.update())
      Serial.println(rdm6300.get_tag_id(), HEX);

     digitalWrite(READ_LED_PIN, rdm6300.is_tag_near());

     delay(10);
    }

but now, after the re-arrangement it just stopped reading tags. What I did was to disconnect everything from the ESP and leave only the RDM6300 connected to it with the sample code. Unfortunately, it doesn't seem to detect any tags.

In order to test if the components are failing for some reason, I decided to test it by using **SoftwareSerial.h** library on it like this:

    #include <SoftwareSerial.h>
    SoftwareSerial RFID(2, 3); // RX and TX

    int i;

    void setup()
    {
      RFID.begin(9600);    // start serial to RFID reader
      Serial.begin(9600);  // start serial to PC
    }

    void loop()
    {
      if (RFID.available() > 0)
      {
         i = RFID.read();
         Serial.print(i, DEC);
         Serial.print(" ");
      }
    }

and it worked perfectly fine. I was able to read the payload coming from the chip:

> 2 30 31 30 46 33 46 38 44 39 31 32 44 3

But, since I don't want to implement everything related to decoding this serial stream I decided to ask for your opinion what could be wrong here. It used to work without any problem but now it doesn't.

There is something interesting which I also noticed. When I run the first code snipped and change the ESP8266 pin used from 4 to 16(D0) and I upload it, once I move the tag close to the antenna [the hardware light related to this pin][5] starts flashing and when I bring the tag back (away from the antenna) it stops flashing.

This makes me thing that on a hardware level everything is fine but some software issues are happening.

  [1]: https://images-na.ssl-images-amazon.com/images/I/61XYAIQVh6L._AC_SY355_.jpg
  [2]: https://www.elektor.com/media/catalog/product/cache/1404d1bfd8e1ad71cc6f16950ff5c805/1/6/169034-91f-web.jpg
  [3]: https://github.com/arduino12/rdm6300
  [4]: https://github.com/arduino12/rdm6300/blob/master/examples/read_to_serial/read_to_serial.ino
  [5]: https://lowvoltage.github.io/images/NodeMCU-ESP8266-LEDs.jpg

title: RDM6300 library not working on ESP8266

Answers: 1

body:
What fixed the issue for me was to go to Boards manager on Arduino IDE and update to latest version:

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

Then I got the following error when compiling:

> Board generic (platform esp8266, package esp8266) is unknown

In order to fix that, I followed [these][2] instructions.

And, I also removed rdm6300 library from **C:\Program Files\Arduino\libraries** and moved it in **C:\Users\myusername\Documents\Arduino\libraries**

  [1]: https://i.stack.imgur.com/pk7Si.png
  [2]: https://arduino-esp8266.readthedocs.io/en/latest/faq/a04-board-generic-is-unknown.html#how-to-resolve-board-generic-platform-esp8266-package-esp8266-is-unknown-error