text:
How do I stop my servo from repeating the loop and perform the rest of the functions?
The project has a makeshift meter (via a half circle cutout and a servo motor operated lever). On program start (button 2), the lever will move to the left hand side at the 9 o'clock position. Once in place, after a short delay, the program will accept input from the button 1 and keep a count while moving the lever toward the 3 o’clock position stopping at at 10-2 w 2 sec delay. When it reaches the position, it stops the count and remembers it.
Repeat same thing but with buttons 4 and 5 respectively. Really important that the count is saved for both buttons 1 and 5.
Pressing button 3 will measure the inputs of button 5 and display them on the meter as a ratio of button 5 presses over button 1 + button 5 presses. If it leans right, that means you had more presses in the first stage than second (for ease of understanding I’ll probably have instructions that say to start with right hand so that leaning right means right hand dominance and left is left handed). Below is a picture of my set up.
*I numbered the buttons 1-5 left to right not by the pin number.
The problem I have is that after button 2 or 4 get pushed the servo just keeps moving to the seven positions I have set as a timer over and over.
#include <Servo.h>

const int button1 = 2;   // button 1 pin/left hand main pin
const int button2 = 3;   // button 2 pin/left start pin
const int button3 = 4;   // button 3 pin/right hand main pin
const int button4 = 5;   // button 4 pin/right start pin
const int button5 = 6;   // button 5 pin/results pin
const int servoPin = 9;  // servo motor pin

int count1 = 0;          // counter for button 1
int count2 = 0;          // counter for button 5

Servo servo;             // servo motor object

void setup() {
  // set button pins as inputs
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);
  pinMode(button5, INPUT);

  servo.attach(servoPin); // attach servo motor to pin
}

void loop() {
  if (digitalRead(button2) == HIGH) {  // if button 2 is pressed
    // move servo motor to 9 o'clock position
    servo.write(180);
    delay(500);  // wait for servo to reach position

    // start accepting input from button 1
    while (digitalRead(button1) == LOW) {
      count1++;  // increment counter
      // move servo motor to 3 o'clock position
      servo.write(180);
      delay(2000);  // wait for servo to reach position
      servo.write(150);
      delay(2000);  // wait for servo to reach position
      servo.write(120);
      delay(2000);  // wait for servo to reach position
      servo.write(90);
      delay(2000);  // wait for servo to reach position
      servo.write(60);
      delay(2000);  // wait for servo to reach position
      servo.write(30);
      delay(2000);  // wait for servo to reach position
      servo.write(0);
      delay(2000);  // wait for servo to reach position

    }

    // repeat the same process for button 4
    while (digitalRead(button4) == LOW) {
      count2++;  // increment counter
      // move servo motor to 3 o'clock position
      servo.write(180);
      delay(2000);  // wait for servo to reach position
      servo.write(150);
      delay(2000);  // wait for servo to reach position
      servo.write(120);
      delay(2000);  // wait for servo to reach position
      servo.write(90);
      delay(2000);  // wait for servo to reach position
      servo.write(60);
      delay(2000);  // wait for servo to reach position
      servo.write(30);
      delay(2000);  // wait for servo to reach position
      servo.write(0);
      delay(2000);  // wait for servo to reach position
    }
  }

  if (digitalRead(button3) == LOW) {  // if button 3 is pressed
    // calculate ratio of button 4 presses to total button presses
    float ratio = (float)count2 / (count1 + count2);

    // Display ratio on meter
    servo.write(90 + (int)(ratio * 90));
  }
}

keep a count while moving the lever toward the 3 o’clock ... your code does not do any counting while the servo is moving

Could you explain please?

your code is move servo, pause, move servo, pause, etc.etc there is no other code while the servo is moving

You might want to learn about finite state machines and experiment with them. This approach will most probably be the appropriate one.

You won't correctly count the button presses unless you do some sort of debouncing. There are libraries that can handle that for you. Also, as pointed out by the busybee, you will have to learn about finite state machines. I recommend this tutorial by Majenko.

You have pulldown resistors on all your buttons, so all of your input pins are LOW when nobody is touching the buttons. When you press a button, the input goes HIGH. In your code, when you do
  if (digitalRead(button2) == HIGH) {  // if button 2 is pressed

it enters the if block, if the button is pressed, because the button2 input is high when the button is pressed. Then you move the servo to position 180 and wait a bit. The next line
    while (digitalRead(button1) == LOW) {

enters the while loop if the input pin is low. The input pin is that, when the button is NOT pressed, because of the pulldown resistor and that is why the servo starts moving when button2 is pressed, unless button1 is also pressed when you press button2. To stop that, change the LOW to HIGH in the while loop condition. Then it will only enter the while loop when the button is pressed and skip it if it is not pressed..
As suggested by the busybee, you might benefit from studying state machines.

Same problem in
while (digitalRead(button4) == LOW) {

and
if (digitalRead(button3) == LOW) {  // if button 3 is pressed


text:
How to fix serial communication?
I am trying to use serial communication to open and close a Blue Robotics Newton gripper. The gripper works with normal commands, but when I try to use serial communication to control it, it is extremely slow and my commands do not correspond to the action I would like. For example, I'll write a "o" in the serial monitor and the gripper will not open.
Does anyone know what is wrong?
#include "Servo.h"

#define GRIPPER_PWM_PIN   10    // Gripper PWM output pin
#define OPEN_TIME         5.0   // Gripper open time (seconds)
#define CLOSE_TIME        5.0   // Gripper close time (seconds)

#define OPEN_PWM_US       1100  // Gripper open PWM output (us)
#define CLOSE_PWM_US      1900  // Gripper close PWM output (us)
int incomingByte =0; // for incoming serial data
Servo gripper;

void setup() {
 // Attach gripper to proper pin
 gripper.attach(GRIPPER_PWM_PIN);
 Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

}

void loop() {
 if (Serial.available() > 0){
   incomingByte = Serial.read();
   if (incomingByte == 'o')
   {
     // Open the gripper
     gripper.writeMicroseconds(1100);
     // Let the gripper open up (microseconds)
     delay(OPEN_TIME*1000);
   }

   if (incomingByte == 'c')
   {
     // Close the gripper
     gripper.writeMicroseconds(1900);
     // Let the gripper close for a while (microseconds)
     delay(CLOSE_TIME*1000);
   }
 }
}

maybe remove the 5 seconds delays or don't send commands at that time.

Why do you even have this 5 second delay? I don't see any sense in it.

Ok this worked - how do I accept it as an answer!? Many thanks

You have a big 5s delay in your code, right after both serial commands. You don't need a delay there; it does not do anything. But it makes your code unresponsive. So you can simply remove it.
I guess you wanted to do some timed thing there and accidentally left it there.  But in general you should not use any big delay() in any code. As you have seen, it makes your code unresponsive, as the Arduino doesn't do anything during this time. Instead look at the BlinkWithoutDelay example, that comes with the Arduino IDE (Its a really important principle to learn). It uses the millis() function (or alternatively the micros() function) to check, if it is time to do something. If yes, it will execute this, if not, it will exit fast and give the rest of the code an opportunity to execute. Much like you would bake a pizza: You start the baking and then regularly  check the clock, if it is time to take the pizza out. In between you can do other things, like reacting go messages on your phone. Its the same principle, just in code.

Great advice! Thank you very much

source: Stack Exchange

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

sort: votes


text:
Gamepad connection using Pro Micro(ATMEGA32u4 + HC-05
I have been working on making a HID compatible Gamepad using Pro Micro and HC-05 module. I have successfully configured the class of HC-05 module to appear as an Input device(A gamepad) on my PC without changing the firmware of the HC-05. However, after the bluetooth device gets paired there is no option showing to connect to it. My question is how do I start the blutooth connection?
Note: The class of device calculator tells you the hex for the class of device you want to make.

you said that the device pairs successfuly and it is seen as a gamepad ... that means it is connected ... what option are you trying to find?

@jsotola For audio devices I have to explicitly press a connect button, even after the device is paired(for windows). Also I tried looking for the device in device manager but I couldn't find it there. Maybe I am missing something. I also tried sending a hex message on loop using the arduino but still nothing. The message was, "0xFD 0x06 0x00 0x00 0x00 0x00 0x55 0xAA" as I saw on a blog.

This link helps you to connect the Gamepad to the pc - https://mitxela.com/projects/bluetooth_hid_gamepad

@MojtabaJahaniDarestani I've actually tried that blog before. Unfortunately the RN42 firmwares available online aren't compatible with any of my three different HC-05s. And after seeing that I could alter the class of BT device from the base HC-05 firmware I thought maybe I won't have to flash another firmware and someone might have figured it out.

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


text:
Copy outbound data of Serial to Serial1 for Pro Micro
I am working on a bluetooth HID device. There are libraries which make HID devices a cake walk if you are making a wired version of your HID device.
I managed to configure my bluetooth module to appear as a HID device to the system, it however does nothing yet.
I figured if I route the serial data, that my wired version of device is sending to the system on Serial, to Serial1 my bluetooth device will function the same way the wired device worked.
If I am not wrong, code that I came across, maps RX of Serial to TX of Serial1.
Void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
}
void loop(){
     if(Serial.available()){
      char get= Serial.read();
      Serial1.Write(get);
     }
}

What I want to do is map the TX pin of Serial to TX pin of Serial1 of the pro micro.

What is your actual question?  As I understood, you want to forward the data, that you receive on Serial to the Serial1 interface. That's exactly what your code does (except for the spelling error with the big W in Serial1.Write(get)).

Re “map the TX pin of Serial to TX pin of Serial1”: you are rather forwarding from Serial’s RX to Serial1’s TX.

@chrisl I don't want to forward the data that I receive on Serial, I want to forward the data that Serial is sending to the system.

@EdgarBonet I want to forward TX of Serial to TX of Serial1. Is there a way to do that? Maybe there's a register where data is stored before writing it on the Serial?

Maybe the context is missing in your question. When you want to send the same data to Serial and Serial1, just always use Serial.write() and Serial1.write() together with the same data. Or is there any reason, why you cannot do this?

@chrisl I am using the ArduinoJoystick library by MHeironimus. Whatever communication it does over the Serial connection is done underneath. I went through it's code but couldn't find anything similar to Serial.begin(). It does however use the DynamicHID library which in turn uses the PluggableUSB library. I don't have an electronics background so I couldn't understand much there.

Thats because the ArduinoJoystick library does not use Serial. It configures the micro to act as HID-USB device. That is completely different to Serial communication. Thus you cannot just send that over a Serial interface

What bluetooth device do you use?

Let us continue this discussion in chat.


text:
How to use LCD display HD44780 with arduino without using any library
My professor wants me to implement a display to an old project prototype we had laying around on the lab.
But he wants me NOT to use LiquidCrystal.h library or any other to achieve that.
I read HD44780 datasheet and tried lots of tweaking and hacking stuff to finally write my name "AUGUSTO" on the screen. The problem is: "lots of tweaking and hacking stuff" which turns my code into trash and kind of impossible to implement it on other project. Eg: when I accidentally short circuit arduino, display "freezes" emtpty and does not work anymore so I have to upload a generic LiquidCrystal.h example code in order to "reset" the whole thing.
My code:
/*
 * Driving LCD Display without library
 * Augusto
 */

//PINS(RS to D7): (2,3,4,6,7,8,9,10,11,12,13);

// WRITE HITACHI (datasheet)

/*
 *     RS RW D7 D6 D5 D4 D3 D2 D1 D0
 * 2.  0  0  0  0  1  1  0  0  *  * -> Function set
 * 3.  0  0  0  0  0  0  1  1  1  0 -> Display ON/OFF control
 * 4.  0  0  0  0  0  0  0  1  1  0 -> Entry Mode set (INCREMENT)
 * 5.  1  0  0  1  0  0  1  0  0  0 -> H
 * 6.  1  0  0  1  0  0  1  0  0  1 -> I
 * 7.  ...
 * 8.  1  0  0  1  0  0  1  0  0  1 -> I (HITACHI)
 * 9.  0  0  0  0  0  0  0  1  1  1 -> Entry Mode set (INCREMENT) - Display Shift
 * 10. 1  0  0  0  1  0  0  0  0  0 -> Escreve um espaco
 *
 */

/*  0000 0000 01 LIMPA
    0000 0000 1— RETORNA HOME
    0000 0 0 0 1 I/D S ENTRY MODE SET
    000 0 0 0 1 DCB SETS ENTIRE DISPLAY ON/OFF
*/

/*
 *  Instruction RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description fOSC is 270 kHz)
                1  0                                   Write data Writes data into DDRAM or

                1  1                                   Read data Reads data from DDRAM or

    I/D = 1: Increment
    I/D = 0: Decrement
    S = 1: Accompanies display shift
    S/C = 1: Display shift
    S/C = 0: Cursor move
    R/L = 1: Shift to the right
    R/L = 0: Shift to the left
    DL = 1: 8 bits, DL = 0: 4 bits
    N = 1: 2 lines, N = 0: 1 line
    F = 1: 5 × 10 dots, F = 0: 5 × 8 dots
    BF = 1: Internally operating
    BF = 0: Instructions acceptable

*/

#define RS 2
#define RW 3
#define E 4
#define DB0 6
#define DB1 7
#define DB2 8
#define DB3 9
#define DB4 10
#define DB5 11
#define DB6 12
#define DB7 13

void setup() {

    for (int i = 2; i <= 4; i++) {
        pinMode(i, OUTPUT);
    }

    for (int i = 6; i <= 13; i++) {
        pinMode(i, OUTPUT);
    }

    digitalWrite(E, 0);
    returnHome();
    delay(100);
    limpa();
    delay(100);
}

void loop() {

    functionSet();
    displayOnOff();
    entryModeSet(HIGH, LOW);
    //A
    escreve(1, 0, 0, 1, 0, 0, 0, 0, 0, 1); //Writes A
    //piscaE();
    //U
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 1); //Writes U and so on...
    //G
    escreve(1, 0, 0, 1, 0, 0, 0, 1, 1, 1);
    //U
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 1);
    //S
    escreve(1, 0, 0, 1, 0, 1, 0, 0, 1, 1);
    //T
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 0);
    //O
    escreve(1, 0, 0, 1, 0, 0, 1, 1, 1, 1);
    piscaE();

    entryModeSet(HIGH, HIGH);

    //escreveEspaco();

    while(1) {} //infinite loop to "stop" void loop()

}

void escreve(int rs, int rw, int db7, int db6, int db5, int db4, int db3, int db2, int db1, int db0) { // Function to WRITE something on the display

    piscaE();
    digitalWrite(RS, rs);
    digitalWrite(RW, rw);
    digitalWrite(DB7, db7);
    digitalWrite(DB6, db6);
    digitalWrite(DB5, db5);
    digitalWrite(DB4, db4);
    digitalWrite(DB3, db3);
    digitalWrite(DB2, db2);
    digitalWrite(DB1, db1);
    digitalWrite(DB0, db0);
    //piscaE();
    delay(10);

}

void escreve(int db7, int db6, int db5, int db4, int db3, int db2, int db1, int db0) {
    digitalWrite(RS, HIGH);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, db7);
    digitalWrite(DB6, db6);
    digitalWrite(DB5, db5);
    digitalWrite(DB4, db4);
    digitalWrite(DB3, db3);
    digitalWrite(DB2, db2);
    digitalWrite(DB1, db1);
    digitalWrite(DB0, db0);
}

void piscaE() { //Function to blink ENABLE pin

    // NOT shure how enable pin works
    digitalWrite(E, 1);
    delay(11);
    digitalWrite(E, 0);
}

void limpa() { //Function to clear display
    piscaE();
    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, LOW);
    digitalWrite(DB0, HIGH);
    returnHome();
}

void entryModeSet(int id, int s) {

    //0 0 0 0 0 0 0 1 I/D S   -   ENTRY MODE SET

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, HIGH);
    digitalWrite(DB1, id);
    digitalWrite(DB0, s);
}

void functionSet() {
    // 0  0  0  0  1  1  0  0  *  * -> Function set

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, HIGH);
    digitalWrite(DB4, HIGH);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);

}

void displayOnOff() {
    //0  0  0  0  0  0  1  1  1  0 -> Display ON/OFF control

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, HIGH);
    digitalWrite(DB2, HIGH);
    digitalWrite(DB1, HIGH);
    digitalWrite(DB0, LOW);
}

void escreveEspaco() { //Function to write a space
    //1  0  0  0  1  0  0  0  0  0 -> Writes a space
    piscaE();
    digitalWrite(RS, HIGH);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, HIGH);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, LOW);
    digitalWrite(DB0, LOW);
    piscaE();
}

void escreveEspaco(int quant) { //Function to write a specific number of spaces
    //1  0  0  0  1  0  0  0  0  0 -> Writes a space

    for (int i = 1; i <= quant; i++) {
        piscaE();
        digitalWrite(RS, HIGH);
        digitalWrite(RW, LOW);
        digitalWrite(DB7, LOW);
        digitalWrite(DB6, LOW);
        digitalWrite(DB5, HIGH);
        digitalWrite(DB4, LOW);
        digitalWrite(DB3, LOW);
        digitalWrite(DB2, LOW);
        digitalWrite(DB1, LOW);
        digitalWrite(DB0, LOW);
        //piscaE();
    }
    piscaE();
}

void returnHome() { //Function to return cursor to adress 0 according to datasheet
    piscaE();
    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, HIGH);
    digitalWrite(DB0, LOW);
    piscaE();
}

why would you habe to upload LiquidCrystal.h example code? ... LED blink code should also work, if the arduino code gets corrupted

you are not thinking clearly ... you use a function escreve() and you call it like escreve(1, 0, 0, 1, 0, 0, 0, 0, 0, 1);, which is the proper way to reuse code .... but then you go on to define pointless functions such as returnHome() and escreveEspaco(), which do the same thing as escreve()

I'm not used to work with bytes or pointers and that's why I said this code is totally messed up because of "lots of tweaking and hacking stuff" like writing a function to write something and another function to write a SPACE instead of creating a variable to then split it or so.

start by reducing the code ... for instance, escreveEspaco() is same as escreve(1, 0, 0, 0, 1, 0, 0, 0, 0, 0); ... work with bytes is no different than work with integers... a byte is just a number ... it is like saying not used to working with numbers that are less than 256


text:
cant read json data esp 32 “parseObject() failed”

hello  I am just trying to make Youtube Subscribe Counter with led matrix 32*8 and esp 32 and I had this problem when I trying to get
subscribers to count
so what is the problem and how I can fix it? `

  ```    //########################  YouTube Subscriber Count Display on LED MATRIX  #############################
        // Receives and displays YouTube channel statistics
        //################# LIBRARIES ################
        String version = "v1.0";       // Version of this program

    #include <WiFi.h>
    #include <WiFiClientSecure.h>
    #include <ArduinoJson.h>     // https://github.com/bblanchon/ArduinoJson
    #include <SPI.h>
    #include <Adafruit_GFX.h>
    #include <Max72xxPanel.h>    // https://github.com/markruys/arduino-Max72xxPanel
    #include <time.h>
    //################ VARIABLES ################
    // Use your own API key by signing up for a free Youtube developer account at http://www.youtube.com
    // LED Matrix Pin -> ESP32 Pin
    // Vcc            -> 3v
    // Gnd            -> Gnd
    // DIN            -> MOSI pin use results of print statement 23 maybe
    // CS             -> SS pin   use results of print statement 5 maybe
    // CLK            -> SCK pin  use results of print statement 18 maybe

    const char* channelId = "UCqTSLaEj9c4hiZkU0FfbaJA"; // See your Channel details click on your channel icon at top-right, then Settings, then Advanced
    const char* apiKey    = "A--------------Aw"; // See https://developers.google.com/youtube/v3/getting-started for an API key, you must enable it to make it work!
    const char* host      = "https://www.googleapis.com";
    unsigned long lastConnectionTime = 0;                 // Last time you connected to the server, in milliseconds
    const unsigned long  postingInterval = 10L*60L*1000L; // Delay between updates, in milliseconds, you should limit your YouTube requests per-day maximum

    //################ PROGRAM VARIABLES and OBJECTS ################
    int pinCS = 5; // Attach CS to this pin, DIN to MOSI and CLK to SCK (cf http://arduino.cc/en/Reference/SPI )
    int numberOfHorizontalDisplays = 4;
    int numberOfVerticalDisplays   = 1;
    int wait   = 35; // In milliseconds
    int spacer = 1;
    int width  = 5 + spacer; // The font width is 5 pixels
    int port   = 443;
    String time_str;

    Max72xxPanel matrix = Max72xxPanel(pinCS, numberOfHorizontalDisplays, numberOfVerticalDisplays);

    struct channelStatistics{
      long viewCount;
      long commentCount;
      long subscriberCount;
      bool hiddenSubscriberCount;
      long videoCount;
    };

    // Change to your WiFi credentials
    const char* ssid     = "SSid";
    const char* password = "PASS";

    channelStatistics channelStats;

    void setup() {
      Serial.begin(115200); // initialize serial communications
      Serial.println("Mosi="+String(MOSI));
      Serial.println("SS="+String(SS));
      Serial.println("SCK="+String(SCK));
      StartWiFi(ssid,password);
      StartTime();

      //----------------------------------------------------------------------
      configTime(0 * 3600, 0, "pool.ntp.org", "time.nist.gov");
      matrix.setIntensity(0); // Use a value between 0 and 15 for brightness
    // Adjust the LED matrix to your own needs
    //  matrix.setPosition(0, 0, 0); // The first display is at <0, 0>
    //  matrix.setPosition(1, 1, 0); // The second display is at <1, 0>
    //  matrix.setPosition(2, 2, 0); // The third display is at <2, 0>
    //  matrix.setPosition(3, 3, 0); // And the last display is at <3, 0>
    //  ...
      matrix.setRotation(0, 1);    // The first display is position is rotated
      matrix.setRotation(1, 1);    // The first display is position is rotated
      matrix.setRotation(2, 1);    // The first display is position is rotated
      matrix.setRotation(3, 1);    // The first display is position is rotated
      lastConnectionTime = millis();
      obtain_subscriber_stats();
    }

    void loop() {
      display_message("Subs: " + String(channelStats.subscriberCount));
      time_t now = time(nullptr);
      String time = String(ctime(&now));
      time.trim();
      display_message(" on " + time);
      if (millis() - lastConnectionTime > postingInterval) { // 15-minutes
        obtain_subscriber_stats();
        lastConnectionTime = millis();
      }
    }

    //################ PROGRAM FUNCTIONS ################

    void display_message(String message){ // Scroll the image left
      matrix.fillScreen(LOW);
      for ( int i = 0 ; i < width * message.length() + matrix.width() - 1 - spacer; i++ ) {
        int letter = i / width;
        int x = (matrix.width() - 1) - i % width;
        int y = (matrix.height() - 8) / 2; // center the text vertically
        while ( x + width - spacer >= 0 && letter >= 0 ) {
          if (letter < message.length()) matrix.drawChar(x, y, message[letter], HIGH, LOW, 1); // HIGH means foreground on, LOW means background off, LOW< HIGH inverts the display
          letter--;
          x -= width;
        }
        matrix.write(); // Send bitmap to display
        delay(wait);
      }
    }

    void obtain_subscriber_stats() {
      String command = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + String(channelId);
      String response = GetRequestFromYoutube(command);
      StaticJsonBuffer <200> jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(response); // Parse JSON
      if (!root.success()) {
        Serial.println(F("jsonBuffer.parseObject() failed"));
      }
      else
      {

        JsonObject& current                = root["items"][0]["statistics"];
        long subscriberCount               = current["subscriberCount"];
        long viewCount                     = current["viewCount"];
        long commentCount                  = current["commentCount"];
        long hiddenSubscriberCount         = current["hiddenSubscriberCount"];
        long videoCount                    = current["videoCount"];
        channelStats.viewCount             = viewCount;
        channelStats.subscriberCount       = subscriberCount;
        channelStats.commentCount          = commentCount;
        channelStats.hiddenSubscriberCount = hiddenSubscriberCount;
        channelStats.videoCount            = videoCount;

      }
      Serial.println("      View Count = " + String(channelStats.viewCount));
      Serial.println("Subscriber Count = " + String(channelStats.subscriberCount));
        Serial.println(GetRequestFromYoutube(command));
        Serial.println(response);
      //  Serial.println(jsonBuffer.parseObject(response));

    }

    String GetRequestFromYoutube(String request) {
      String headers, body = "";
      bool Headers    = false;
      bool currentLineIsBlank = true;
      int  MessageLength = 1000;
      // Connect with youtube api over ssl
      WiFiClientSecure client;
      if (client.connect(host, port)) {
        Serial.println(".... connected to server");
        char c;
        int ch_count=0;
        request += "&key=" + String(apiKey);
        request = "GET " + request;
        Serial.println(request);
        client.println(request);
        int now   = millis();
        while (millis()-now < 1500) {
          while (client.available()) {
            char c = client.read();
            if(!Headers){
              if (currentLineIsBlank && c == '\n') {
                Headers = true;
              }
              else{
                headers = headers + c;
              }
            } else {
              if (ch_count < MessageLength)  {
                body = body+c;
                ch_count++;
              }
            }
            if (c == '\n') {
              currentLineIsBlank = true;
            } else if (c != '\r') {
              currentLineIsBlank = false;
            }
          }
        }
      }
      return body;
    }

    ////////////// WiFi, Time and Date Functions /////////////////
    int StartWiFi(const char* ssid, const char* password) {
      int connAttempts = 0;
      Serial.print(F("\r\nConnecting to: ")); Serial.println(String(ssid));
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED ) {
        delay(500); Serial.print(".");
        if (connAttempts > 20) {
          Serial.println("\nFailed to connect to a Wi-Fi network");
          return -5;
        }
        connAttempts++;
      }
      Serial.print(F("WiFi connected at: "));
      Serial.println(WiFi.localIP());
      return 1;
    }

    void StartTime(){
      configTime(0, 0, "0.uk.pool.ntp.org", "time.nist.gov");
      setenv("TZ", "GMT0BST,M3.5.0/01,M10.5.0/02",1); // Change for your location
      UpdateLocalTime();
    }

    void UpdateLocalTime(){
      struct tm timeinfo;
      while (!getLocalTime(&timeinfo)){
        Serial.println("Failed to obtain time");
      }
      //See http://www.cplusplus.com/reference/ctime/strftime/
      Serial.println(&timeinfo, "%a %b %d %Y   %H:%M:%S"); // Displays: Saturday, June 24 2017 14:05:49
      char output[50];
      strftime(output, 50, "%a %d-%b-%y  (%H:%M:%S)", &timeinfo);
      time_str = output;
    }
    ```

why are you not providing all information? ... I am very certain that the error message is longer than parseObject() failed

this is the full problem if you read the code you will find this if statment
      if (!root.success()) {
        Serial.println(F("jsonBuffer.parseObject() failed"));
      }```
it just printing this message in the serial monitor

print the content and take a look at the byre json. It's probably either too long too fit into 200 bytes or the formating is broken.

The documentation for ArduinoJson 5 lists the reasons why parseObject() may return false:

The input is not a valid JSON
The StaticJsonBuffer is too small
The StaticJsonBuffer is too big (stack overflow)
The DynamicJsonBuffer fails to allocate memory
You called parseObject() instead of parseArray()
The nesting limit is too low

A glance at your code suggests that the problem is number 2: the StaticJsonBuffer is too small.
Indeed, I don't know what the input looks like, but 200 bytes is probably too small to store the result.
You can use the ArduinoJson Assistant to compute the required capacity for the JsonBuffer. Don't forget to switch to a DynamicJsonBuffer if it becomes bigger than 4 KB.
Lastly, I really recommend that you switch to ArduinoJson 6 because it offers more features, better performance, better memory usage, and better error reporting, all with the same code size and portability.


text:
ESP32 cam module SPI and NRF
I'm trying to use nrf2401 as transmitter on ESP32-cam module.
I'm programming with Arduino IDE, but I'm not sure how to set the pins.
I know that the board has 2 SPI interfaces. The first one is for the SD card built-in module.
The second one should be free.
Those are the pins for the second SPI:
MOSI - 13,
MISO - 12,
CLK - 14,
CS 15
Here is my code - https://pastebin.com/qEC3JA1d
Where should I define my pins for the SPI?

There are examples in the RF24 docs


text:
Downloading code from Arduino mega
A while ago I made a code for a drag timing system and uploaded it to my Arduino mega after that I broke my computer and got a new one and I don't have that code anymore. Does anyone know how to recover it from my Arduino?

this has been asked before

You can easily recover the binary (look up avrdude and the command your IDE uses to upload to the board), but you won't get your source code back from that.


text:
Measuring li-ion that arduino is running from
I am using a 5v Arduino pro mini (with regulator and power led removed).
I have been reading how to accurately measure Li-ion batteries when powering from the same battery you are trying to measure from. Using the 1.1V internal analog reference to measure a draining VCC source by using a voltage divider on it, and math to show that converted reading.
Reading the Arduino forums I came across this answer.
  long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

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

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

However, I cant see a analogRead anywhere in this sketch. (Is this a strictly internal reference?)
At the bottom of the thread someone is saying that you can do this without a voltage divider on the analog pin.
Can someone confirm or explain this? I don't want to fry my Arduino...

Using the 1.1V internal analog reference to measure a draining VCC
source by using a voltage divider on it

You could indeed use a voltage divider, and measure a scaled-down Vcc
against the internal 1.1 V reference. This is, however, not what
the code you posted is doing. It is instead measuring the internal
reference against Vcc, as stated in the comment within the code. The
REFS0 bit selects Vcc as the reference for the ADC. The bits MUX1...MUX3
select the internal reference as the input channel.

result = ADCL;
result |= ADCH<<8;

This idiom dates back from a time when the compiler did not know how to
read 16-bit I/O registers: you had to explicitly read one byte at a time
and then put these together into a 16-bit word. This time is long gone,
and you can now just access the 16-bit register as ADC directly. I
would even get rid of the result variable and just:
return 1126400L / ADC;  // Vcc in mV

Edit: As suggested by the busybee, here is the explanation of the
factor 1126400: The ADC meaures the ratio of its input voltage to its
reference voltage, and returns this ratio scaled by a factor 1024. In
this case,
ADC = 1024 × (Vbg ÷ Vcc)
where Vbg is the voltage of the 1.1 V bandgap reference. Thus,
Vcc = 1024 × Vbg ÷ ADC
If we want Vcc in millivolts, we plus the Vbg voltage in millivolts in
the above equation and get
Vcc (in mV) = 1024 × 1100 ÷ ADC = 1126400 ÷ ADC

You might add that 1126400 is 1024 * 1100, which is scaling the result, and why.

@thebusybee: Thanks for the suggestion. Added.

Outstanding answer, as usual. (voted)

Thank you for the very detailed explanation!

wouldn't it be 1.1v x 1023 x 1000? the 1023 being the 10bit total value for the ADC?

@LindsayCox: No, it's 1024, although 1023 is a very widespread error, presumably because it's the highest reading you can get. According to the datasheet, “the maximum value represents the voltage on the AREF pin minus 1 LSB.” (emphasis mine) and “ADC = Vin ⋅ 1024 ÷ Vref”. The datasheet is the only authoritative source. Note that, given the uncertainty in Vbg, it doesn't really matter.

If anyone else is confused by this:
Will it hurt your Arduino?

No, this is a internal voltage reference between VCC & the 1.1v internal analog reference.

Is a voltage divider necessary?

Not unless you have something external of the Arduino to measure!

Is the internal reference actually 1.1v?

No, it seems like each pro mini I have the the 1.1v reference is slightly different. My pro minis do not have a break out for the AREF pin, so you need to figure out what the value is for each individual Arduino.

I used this,
1.15 x 1023 x 1000 = [value in quotation from second to last line in the Function]

return "1125300L" / ADC;

I just incremented the 1.1v reference by 0.01 a couple of times until the output matched the voltage reading on my digital multi-meter. I would think with a known voltage you could do this math backwards to find what AREF actually is. I am sure that would be easier.
A big thanks to JRobert & @ EdgarBonnet for your answers!

Instead of calling analogRead(), this sketch performs the equivalent actions by directly manipulating the hardware registers to begin a conversion, wait until the conversion is complete, and collect the converted value.
Just reading the final value is accomplished by the statements:
result = ADCL;
result |= ADCH<<8;

All of the statements following delay(2) up to and including the above 2, taken together, do what analogRead() does.

Re “All of the statements following delay(2)”: Note that analogRead() does set ADMUX.

Yup - I missed that. Thanks, @EdgarBonet.


text:
WS2812B Power Supply
I have a WS2812b addressable RGB led ribbon that is 5m (150 RGB leds). I purchased a 5v 10amp power supply to power it; however, whenever I try to use it to power the LED strip the leds start flashing colors like crazy. Is there a reason I would be seeing this behavior or is this a sign of a bad power supply?
The setup is very simple, the data line is coming from an Arduino Uno, the voltage and ground are from the power supply. The program is just one of the sample ones with FastLED library and works "fine" when just powered by the arudino's 5V pin.
Thank you

Are the ground of the power supply and of the Uno connected?

No, the Arduino is powered by a separate source and no grounds are shared. Would that cause the issue?

That seems to have fixed it. Thank you!

The strip and the Arduino need to share the same ground connection. They are communicating through voltage and voltage is always a difference between two points. The power supply sets the supply voltage as the difference between + and ground. The chips in the strip will then try to measure the voltage on the data line relative to their ground. When the grounds are not connected, the Arduinos output pin is floating somewhere else, depending on external factors. By connecting the grounds, both devices (Arduino and strip) use the same ground value to measure voltages. Only this enables communication between the devices.


text:
How to combine this two sensor code
I have a problem. I don’t know how to combine this two codes & the diagram. My project is about automatic water storage door that using water sensor & rain sensor. The rain sensor will function when rain while the water sensor will control the open/close door. The door will open when it rain but it will remain close when the volume in the water storage is full.the volume of water in tank was controlled by flood sensor(water sensor). Here is the code for two sensor.
rain sensor
const int senmin = 0;
const int senmax = 1024;
int led = 13;
int sensory = A0;
int i;
void setup() {
Serial.begin (9600);
pinMode(led, OUTPUT);
}
void loop() {
int sensor = analogRead(sensory);
int range = map(sensor, senmin, senmax, 0, 3);
switch (range)
{
case 0:
Serial.println("raining");
digitalWrite(led, HIGH);
  break;

case 1:
  Serial.println("not raining");
  digitalWrite(led,LOW);

}
delay(500);
}
water sensor
const int waterSens = A0; //define water sensor
const int led = 9;//define led to pin 9
int waterVal; //define the water sensor value
void setup() {
pinMode(led, OUTPUT); //set led as an output
pinMode(waterSens, INPUT);//set water sensor as an input
Serial.begin(9600);  //start the serial port at 9600 bauds
}
void loop() {
waterVal = analogRead(waterSens); //read the water sensor
Serial.println(waterVal); //print the value of the water sensor to the serial monitor
if (waterVal <= 0){
digitalWrite(led, HIGH);//if the water sensor senses water turn the led on
}
else{
digitalWrite(led, LOW);//if it doesn't sense anything turn the led off
}
}


text:
Analog Microphone values not changing
I just bought a microphone for my Ardoino Nano 33 BLE. The mic can use both Analog and Digital input. Here is the mic and how it's connected.
Here is the code where I read the input
int sensorPin = A5; // select the input pin for the potentiometer
int sensorValue = 0;
void setup ()
{
 Serial.begin (9600);
}
void loop ()
{
 sensorValue = analogRead (sensorPin);
 delay (500);
 Serial.println (sensorValue, DEC);
}

I've followed an example by the manufacturer and the reads are going random between 0 and 5 sometimes a little higher. It states in the example that it should go up to 1023.
Is something wrong, can I have connected something wrong that would make this? Also when I give 5v nothing happens on the Mic but if I connect 3.3v the mic turns on 2 red led lights and gives me a value around 80 but doesnt respond to any sounds.

"There is also this 10K potentiometer that is used to set a reference voltage for the op-amp, also this potentiometer is used to generate the reference voltage for the analog out function of the module." - https://circuitdigest.com/microcontroller-projects/interfacing-sound-sensor-with-arduino

/* edited to specifically provide a potential solution as commented by @jstola */
You have posted a picture of a ubiquitous sound detection sensor - typically a Keyes KY-037.
It is based on an LM393 dual comparator.

The board has a digital output [marked DO] and an analog output marked AO. It also has + and G (Ground) connections.

I dug mine out and attached it to a Nano 33 BLT.

Notice that I have + connected to 3.3v, G connected to ground and AO connected to A5.
A little trick is to connect just power and ground and turn the potentiometer until L2 (that's the LED nearest the pot) turns off. If you make some noise, you will see L2 flash briefly. This sets the digital output threshold and works well for testing the analog out.
Then I ran this simple program (very similar to yours)
void setup() {
  pinMode(A5,INPUT); // not absolutely needed in this case
  Serial.begin(9600);
}
void loop() {
  Serial.println(analogRead(A5));
}

Opened the Arduino IDE serial plotter (shift+ctr+L) and watched the waveform change when I snapped my fingers - see the spikes?.

So what is the solution to your problem that is does not work?
A couple of possibilities.

You have a different board.

Does your board look just like the one I posted or does it look different? If it is a different board then what you posted, that is another matter.
Assuming it is the same board (or at least the same generic board), it is possible that:

You don't have the connections correct. Double check that.

You don't have the pot set near the mid point - follow the direction for that and observe that the LED can be turned off. That is a multi-turn pot and if you hear a little 'click', you went too far in that direction - move it the other way and see if you can get that LED to just turn off.

Failing any of those, your board could be toast

Welcome! This is generic in nature because you did not provide any links to the hardware items so everything is a pure SWAG.
I cannot properly answer your question without knowing what board you have, there are several that look similar in red and other colors. Maybe the following will help you determine what you have. Look at the specifications closely.
Your statement "The mic can use both Analog and Digital input." The mic is analog by nature but can be converted to a digital signal with an op-amp  or comparator circuit as many of these modules have done.
It appears to me that your board will give you a logic 1 or zero, not an analog output. The pot on those generally sets the reference voltage for the comparator (may be an op amp) function, If it is a dual op amp the other half is an amp for the microphone. If there is an analog output the microphone signal needs to be amplified as the microphone output is only a few millivolts and the A/D needs volts.


text:
Alternate full speed usb library for ATTINY85?
I'm currently working on a project using the ATTINY85 for USB communication. After some research, it turns out that the V-USB library only supports usb 1.1, which only supports a 125hz polling rate. I would like to be able to have a polling rate of 1000hz, or close to it, which requires usb 2.0 or faster. I was hoping that someone could help point me to a library which supports usb 2.0, or suggest an alternative. Any help would be greatly appreciated, thanks in advance!

you need a dedicated USB controller for that

Since an ATtiny85 has no built-in USB hardware module, you use a software solution like V-USB. Unfortunately bit-banging software cannot be as fast as hardware, so you are out of luck here. (Reading the documentation of V-USB is enlightened and explains the difficulties and limits of such a solution.)
You cannot have USB 2.0 with an ATtiny85 alone.
Possible solutions:

an external USB module
another microcontroller


text:
Compilation error with MMA8451 accelerometer and attiny85 using ATTinyCore
I am trying to use the Adafruit MMA8451 accelerometer with an attiny85. The Adafruit library uses Wire which doesn't work on the attiny so I used the ATTinyCore board files which have been modified to use a working version of Wire (github link: https://github.com/SpenceKonde/ATTinyCore).
I'm just trying to get the MMA8451 example to compile but here is the following error output:

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp: In static member function 'static void SPIClass::begin()':

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:259:5: error: 'USI_SCK_PORT' was not declared in this scope

     USI_SCK_PORT |= _BV(USCK_DD_PIN);   //set the USCK pin as output

     ^~~~~~~~~~~~

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:259:5: note: suggested alternative: 'USI_CLOCK_PORT'

     USI_SCK_PORT |= _BV(USCK_DD_PIN);   //set the USCK pin as output

     ^~~~~~~~~~~~

     USI_CLOCK_PORT

In file included from c:\users\sglaw\appdata\local\arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr\io.h:99:0,

                 from C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.h:27,

                 from C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:20:

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:259:25: error: 'USCK_DD_PIN' was not declared in this scope

     USI_SCK_PORT |= _BV(USCK_DD_PIN);   //set the USCK pin as output

                         ^

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:259:25: note: suggested alternative: 'USI_PIN'

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:260:5: error: 'USI_DDR_PORT' was not declared in this scope

     USI_DDR_PORT |= _BV(DO_DD_PIN);     //set the DO pin as output

     ^~~~~~~~~~~~

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:260:5: note: suggested alternative: 'USI_PORT'

     USI_DDR_PORT |= _BV(DO_DD_PIN);     //set the DO pin as output

     ^~~~~~~~~~~~

     USI_PORT

In file included from c:\users\sglaw\appdata\local\arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr\io.h:99:0,

                 from C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.h:27,

                 from C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:20:

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:260:25: error: 'DO_DD_PIN' was not declared in this scope

     USI_DDR_PORT |= _BV(DO_DD_PIN);     //set the DO pin as output

                         ^

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:260:25: note: suggested alternative: 'NOT_A_PIN'

C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI\SPI.cpp:261:26: error: 'DI_DD_PIN' was not declared in this scope

     USI_DDR_PORT &= ~_BV(DI_DD_PIN);    //set the DI pin as input

                          ^

Using library Wire at version 2.0.0 in folder: C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\Wire
Using library Adafruit_MMA8451_Library at version 1.2.1 in folder: C:\Users\sglaw\Documents\Arduino\libraries\Adafruit_MMA8451_Library
Using library Adafruit_BusIO at version 1.14.1 in folder: C:\Users\sglaw\Documents\Arduino\libraries\Adafruit_BusIO
Using library Adafruit_Unified_Sensor at version 1.1.7 in folder: C:\Users\sglaw\Documents\Arduino\libraries\Adafruit_Unified_Sensor
Using library SPI at version 2.0.0 in folder: C:\Users\sglaw\Documents\Arduino\hardware\ATTinyCore-2.0.0-dev\avr\libraries\SPI
exit status 1
Error compiling for board ATtiny85/45/25 (No Bootloader).

Any help much appreciated

I'm pretty sure I know what this is, but I can't replicate your problem exactly.

I guess this is a problem with the 2.0.0 version of core. I installed version 1.5.2 through the boards manager and the example of the library compiles without errors

I'll try the 1.5.2 version

@chrisl Did you also not get their exact error?

@timemage In fact I got no error. Only the warning, that like 85% of memory is used globally. Compiled without problems. OP: Maybe you can report this at the cores github repository. They are asking for feedback on the 2.0.0 version.

@chrisl no errors with 1.5.2 (apart from same global variables warning), thanks for the help! I'll try report it on the github for 2.0.0


text:
Problem with Time Interrupts in ESP8266 with water proof depth sensor
I am trying to use an edited version of waterproof depth sensor code from the Arduino blog. It works well on my Arduino Uno board; however, it doesn't work with my ESP8266 board. Is there a way to adjust it? I understand that the problem is with Arduino clock module and time interrupts. On the other hand, I can't know where to find their counterparts in the ESP libraries.
Code is here:
#include <SPI.h>
const int clock = 4;
float initial = 0;
void resetsensor()
{
  SPI.setDataMode(SPI_MODE0);
  SPI.transfer(0x15);
  SPI.transfer(0x55);
  SPI.transfer(0x40);
}
float read_pressure(){
  TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
  analogWrite (clock, 128) ;
  resetsensor();
  unsigned int result1 = 0;
  unsigned int inbyte1 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0x50);
  SPI.setDataMode(SPI_MODE1);
  result1 = SPI.transfer(0x00);
  result1 = result1 << 8;
  inbyte1 = SPI.transfer(0x00);
  result1 = result1 | inbyte1;
  resetsensor();
  unsigned int result2 = 0;
  byte inbyte2 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0x60);
  SPI.setDataMode(SPI_MODE1);
  result2 = SPI.transfer(0x00);
  result2 = result2 <<8;
  inbyte2 = SPI.transfer(0x00);
  result2 = result2 | inbyte2;
  resetsensor();
  unsigned int result3 = 0;
  byte inbyte3 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0x90);
  SPI.setDataMode(SPI_MODE1);
  result3 = SPI.transfer(0x00);
  result3 = result3 <<8;
  inbyte3 = SPI.transfer(0x00);
  result3 = result3 | inbyte3;
  resetsensor();
  unsigned int result4 = 0;
  byte inbyte4 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0xA0);
  SPI.setDataMode(SPI_MODE1);
  result4 = SPI.transfer(0x00);
  result4 = result4 <<8;
  inbyte4 = SPI.transfer(0x00);
  result4 = result4 | inbyte4;
  long c1 = (result1 >> 1) & 0x7FFF;
  long c2 = ((result3 & 0x003F) << 6) | (result4 & 0x003F);
  long c3 = (result4 >> 6) & 0x03FF;
  long c4 = (result3 >> 6) & 0x03FF;
  long c5 = ((result1 & 0x0001) << 10) | ((result2 >> 6) & 0x03FF);
  long c6 = result2 & 0x003F;
  resetsensor();
  unsigned int presMSB = 0; //first byte of value
  unsigned int presLSB = 0; //last byte of value
  unsigned int D1 = 0;
  SPI.transfer(0x0F); //send first byte of command to get pressure value
  SPI.transfer(0x40); //send second byte of command to get pressure value
  delay(35); //wait for conversion end
  SPI.setDataMode(SPI_MODE1); //change mode in order to listen
  presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
  presMSB = presMSB << 8; //shift first byte
  presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
  D1 = presMSB | presLSB; //combine first and second byte of value
  resetsensor(); //resets the sensor
  unsigned int tempMSB = 0; //first byte of value
  unsigned int tempLSB = 0; //last byte of value
  unsigned int D2 = 0;
  SPI.transfer(0x0F); //send first byte of command to get temperature value
  SPI.transfer(0x20); //send second byte of command to get temperature value
  delay(35); //wait for conversion end
  SPI.setDataMode(SPI_MODE1); //change mode in order to listen
  tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
  tempMSB = tempMSB << 8; //shift first byte
  tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
  D2 = tempMSB | tempLSB; //combine first and second byte of value
  const long UT1 = (c5 << 3) + 20224;
  const long dT = D2 - UT1;
  const long TEMP = 200 + ((dT * (c6 + 50)) >> 10);
  const long OFF  = (c2 * 4) + (((c4 - 512) * dT) >> 12);
  const long SENS = c1 + ((c3 * dT) >> 10) + 24576;
  const long X = (SENS * (D1 - 7168) >> 14) - OFF;
  long PCOMP = ((X * 10) >> 5) + 2500;
  float TEMPREAL = TEMP/10;
  float PCOMPHG = PCOMP * 750.06 / 10000; // mbar*10 -> mmHg === ((mbar/10)/1000)*750/06
  long T2 = 0;
  float P2 = 0;
  if (TEMP < 200)
    {
      T2 = (11 * (c6 + 24) * (200 - TEMP) * (200 - TEMP) ) >> 20;
      P2 = (3 * T2 * (PCOMP - 3500) ) >> 14;
    }
  else if (TEMP > 450)
    {
      T2 = (3 * (c6 + 24) * (450 - TEMP) * (450 - TEMP) ) >> 20;
      P2 = (T2 * (PCOMP - 10000) ) >> 13;
    }
  if ((TEMP < 200) || (TEMP > 450))
  {
    const float TEMP2 = TEMP - T2;
    const float PCOMP2 = PCOMP - P2;
    float TEMPREAL2 = TEMP2/10;
    float PCOMPHG2 = PCOMP2 * 750.06 / 10000; // mbar*10 -> mmHg === ((mbar/10)/1000)*750/06
    return PCOMPHG2;
  }
}
void initialialize()
{
  Serial.print("Setting initial");
  for (int i = 0; i < 10; i++)
  {
    initial += read_pressure();
    Serial.print(".");
    delay(1000);
  }
  initial /= 10;
  Serial.println();
  Serial.print("initialial Pressure: ");
  Serial.println(initial);
}
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV32);
  pinMode(clock, OUTPUT);
  delay(100);
  initialialize();
  delay(5000);
}
void loop()
{
  float reading = (read_pressure() - initial) * 1.3595474315191;
  Serial.print("Water is: ");
  Serial.print(reading);
  Serial.println("cm");
  delay(500);
}

I get errors with both the clock variable and TCCR1B.


text:
Lilygo T-Wristband code not working (DRV2605 Motor version)
I am new to this and I have purchased the Lilygo T-Wristband to prototype a watch that will vibrate upon receiving a 1-bit bluetooth signal from an android app. The goal is to allow the user to set the intensity of vibration (hence i am using the Real Time Playback, RTP, mode) that varies from 0-255. My device seems to not be working whenever i have the Wire1 code and I really am stuck at this point trying to make the motor work. I have attached the code below
#include <pcf8563.h>
#include <TFT_eSPI.h> // Graphics and font library for ST7735 driver chip
#include <SPI.h>
#include <Time.h>
#include <Wire.h>
#include <WiFi.h>
#include "sensor.h"
#include "esp_adc_cal.h"
#include "avas.h.c"
#include "charge.h"
#include "BluetoothSerial.h"
#include <Adafruit_DRV2605.h>
// init Class:
BluetoothSerial ESP_BT;
Adafruit_DRV2605 drv;

#define TP_PIN_PIN          33
#define I2C_SDA_PIN         21
#define I2C_SCL_PIN         22
#define RTC_INT_PIN         34
#define BATT_ADC_PIN        35
#define VBUS_PIN            36
#define TP_PWR_PIN          25
#define LED_PIN             4
#define CHARGE_PIN          32
#define DRV_SDA             15
#define DRV_SCL             13

TFT_eSPI tft = TFT_eSPI();  // Invoke library, pins defined in User_Setup.h
PCF8563_Class rtc;

char buff[256];
bool rtcIrq = false;
bool initial = 1;
bool otaStart = false;
RTC_DATA_ATTR int boots = 0;

uint8_t func_select = 0;
uint8_t omm = 99;
uint8_t xcolon = 0;
uint32_t targetTime = 0;       // for next 1 second timeout
uint32_t colour = 0;
int vref = 1100;

bool pressed = false;
uint32_t pressedTime = 0;
bool charge_indication = false;
uint8_t hh, mm, ss ;

void setupWire() {
  tft.init();
    tft.setRotation(1);
    tft.setSwapBytes(true);
    tft.pushImage(0, 0,  160, 80, avas);
    delay(2000);
  Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
  Wire.setClock(400000);
}
void setupPins() {
  pinMode(TP_PIN_PIN, INPUT);
  pinMode(TP_PWR_PIN, PULLUP);
  //! Must be set to pull-up output mode in order to wake up in deep sleep mode
  digitalWrite(TP_PWR_PIN, HIGH);
  pinMode(LED_PIN, OUTPUT);
  pinMode(CHARGE_PIN, INPUT_PULLUP);
  attachInterrupt(CHARGE_PIN, [] {
      charge_indication = true;
  }, CHANGE);
  if (digitalRead(CHARGE_PIN) == LOW) {
      charge_indication = true;
  }

}
void setupTFT() { //set-up fonts
  tft.init();
  tft.setRotation(1);
  tft.setSwapBytes(true);
  tft.fillScreen(TFT_WHITE);
  tft.setTextColor(TFT_YELLOW, TFT_WHITE); // Note: the new fonts do not draw the background color
}
void setupVolt() { //set-up battery monitoring
    esp_adc_cal_characteristics_t adc_chars;
    esp_adc_cal_value_t val_type = esp_adc_cal_characterize((adc_unit_t)ADC_UNIT_1, (adc_atten_t)ADC1_CHANNEL_6, (adc_bits_width_t)ADC_WIDTH_BIT_12, 1100, &adc_chars);
    //Check type of calibration value used to characterize ADC
    if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) {
//        Serial.printf("eFuse Vref:%u mV", adc_chars.vref);
        vref = adc_chars.vref;
    } else if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) {
//        Serial.printf("Two Point --> coeff_a:%umV coeff_b:%umV\n", adc_chars.coeff_a, adc_chars.coeff_b);
    } else {
//        Serial.println("Default Vref: 1100mV");
    }
}
void setupRTC() { //set-up RTC for time
    rtc.begin(Wire);
    //Check if the RTC clock matches, if not, use compile time
    rtc.check();
    RTC_Date datetime = rtc.getDateTime();
    hh = datetime.hour;
    mm = datetime.minute;
    ss = datetime.second;
}
void setupDRV(){

   Wire1.begin(DRV_SDA, DRV_SCL);
    Wire1.beginTransmission(DRV2605_ADDR);
    if (Wire1.endTransmission() != 0) {
        tft.setTextColor(TFT_RED, TFT_WHITE);
        tft.fillScreen(TFT_WHITE);
        tft.setCursor(0, 0);
        tft.println("Failed to connect DRV2605");
        delay(5000);
        esp_restart();
    }
    drv.begin(&Wire1);
    drv.setMode(DRV2605_MODE_REALTIME);

}
void setup(void) {
  // WiFi.mode(WIFI_OFF);

  Serial.begin(9600);
  setCpuFrequencyMhz(80);         // scaling it back saves so much of the precious battery life
  btStop();
  ESP_BT.begin("AVAS");
  setupDRV();
  setupWire();
  setupTFT();
  setupRTC();
  setupVolt();
  while (ESP_BT.available() == false)
        {
          tft.setTextColor(TFT_BLUE, TFT_WHITE);
          tft.fillScreen(TFT_WHITE);
          tft.setCursor(0, 0);
          tft.println("Bluetooth not connected");
          delay(3000);
        }

  while (ESP_BT.available() == true){
          tft.setTextColor(TFT_RED, TFT_WHITE);
          tft.fillScreen(TFT_WHITE);
          tft.setCursor(0, 0);
          tft.println("Bluetooth connected");
          delay(5000);
          break;
  }

  if(boots == 0) //Run this only the first time
  {
    targetTime = millis() + 1000 ;  //adds 1 min to compiler time
    boots ++;
  }
  setupPins();
}
String Volt() {
    uint16_t v = analogRead(BATT_ADC_PIN);
    float battery_voltage = ((float)v / 4095.0) * 2.0 * 3.3 * (vref / 1000.0);
    return String(battery_voltage) + "V";
}
void RTC() {

    if (targetTime < millis()) {
        RTC_Date datetime = rtc.getDateTime();
        hh = 11;
        mm = datetime.minute;
        ss = datetime.second;
        // Serial.printf("hh:%d mm:%d ss:%d\n", hh, mm, ss);
        targetTime = millis() + 1000;
        if (ss == 0 || initial) {
            initial = 0;
            tft.setTextColor(TFT_GREEN, TFT_WHITE);
            tft.setCursor (8, 60);
            tft.print(__DATE__); // This uses the standard ADAFruit small font
        }
        tft.setTextColor(TFT_BLUE, TFT_WHITE);
        tft.drawCentreString(Volt(), 120, 60, 1); // Next size up font 2
        // Update digital time
        uint8_t xpos = 6;
        uint8_t ypos = 0;
        if (omm != mm) { // Only redraw every minute to minimise flicker
            // Uncomment ONE of the next 2 lines, using the ghost image demonstrates text overlay as time is drawn over it
            tft.setTextColor(0x39C4, TFT_WHITE);  // Leave a 7 segment ghost image, comment out next line!
            //tft.setTextColor(TFT_BLACK, TFT_BLACK); // Set font colour to black to wipe image
            // Font 7 is to show a pseudo 7 segment display.
            // Font 7 only contains characters [space] 0 1 2 3 4 5 6 7 8 9 0 : .
            tft.drawString("88:88", xpos, ypos, 7); // Overwrite the text to clear it
            tft.setTextColor(0xFBE0, TFT_WHITE); // Orange
            omm = mm;

            if (hh < 10) xpos += tft.drawChar('0', xpos, ypos, 7);
            xpos += tft.drawNumber(hh, xpos, ypos, 7);
            xcolon = xpos;
            xpos += tft.drawChar(':', xpos, ypos, 7);
            if (mm < 10) xpos += tft.drawChar('0', xpos, ypos, 7);
            tft.drawNumber(mm, xpos, ypos, 7);
        }

        if (ss % 2) { // Flash the colon
            tft.setTextColor(0x39C4, TFT_WHITE);
            xpos += tft.drawChar(':', xcolon, ypos, 7);
            tft.setTextColor(0xFBE0, TFT_WHITE);
        } else {
            tft.drawChar(':', xcolon, ypos, 7);
        }
    }
}

void loop() {
  if (charge_indication) {
      charge_indication = false;
      if (digitalRead(CHARGE_PIN) == LOW) {
          tft.pushImage(140, 55, 16, 16, charge);
      } else {
          tft.fillRect(140, 55, 16, 16, TFT_WHITE);
      }
  }
  if (digitalRead(TP_PIN_PIN) == HIGH) {
      if (!pressed) {
          initial = 1;
          targetTime = millis() + 1000;
          tft.fillScreen(TFT_WHITE);
          omm = 99;
          func_select = func_select + 1 > 2 ? 0 : func_select + 1;
          pressed = true;
          pressedTime = millis();
      } else {
          if (millis() - pressedTime > 3000) {
              esp_restart();
          }
      }
  } else {
      pressed = false;
  }
        RTC();
   if (ESP_BT.available())
        {
          byte pwm = ESP_BT.read(); //Read what we receive
          // drv.setRealtimeValue(pwm);
          // drv.go();
          tft.setTextColor(TFT_RED, TFT_WHITE);
          tft.fillScreen(TFT_WHITE);
           tft.setCursor(0, 0);
          tft.println(pwm);
        }
  }

start with simple code that runs the motor for one second, stops the motor for one second and repeats


text:
Unable to flash arduino pro micro from Terminal
I am trying to upload an hex file to my arduino pro micro using Avrdude . The thing is that I cannot upload any code using the Avrdude terminal commands , but when I use arduino IDE to upload any code it perfectly uploads the code to Arduino.
The command I am using on the terminal:
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -patmega32u4 -cavr109 -PCOM15 -b57600 -D -U flash:w:C:\Users\santi\Documents\keyboard\corne\crkbd_rev1_layout_split_3x6_3_mine.hex:i

I already have avrdude on the environment variables on my windows 10 machine.
Output:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM15
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

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

avrdude: butterfly_recv(): programmer is not responding

I keep waiting but it does not upload the code.
I added a push button for RST and GND pins to enter bootloader mode, and I am pressing the reset button. I even tried resetting twice quickly, but I get the same result.
I tried using the Arduino and the code gets uploaded.
I uploaded the following code:
int RXLED = 17;
void setup(){
  pinMode(RXLED, OUTPUT);
}

void loop() {
  digitalWrite(RXLED, LOW);
  delay(1500);
  digitalWrite(RXLED, HIGH);
  delay(1500);
}

The command ran in the IDE is:
"C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

Arduino IDE output:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM16
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: reading input file "C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex"
avrdude: writing flash (3852 bytes):

Writing | ################################################## | 100% 0.29s

avrdude: 3852 bytes of flash written

avrdude done.  Thank you.

I tried using the same Avrdude command in the terminal.
"C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

Output:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM16
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
avrdude: ser_open(): can't open device "\\.\COM16": El sistema no puede encontrar el archivo especificado.

I don´t know why it uses a different port.
I tried changing the port in that command but I get the same result as before
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM15
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

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

I could just use the arduino IDE to flash my device but the problem is that I only have the hex file. I am trying to flash my device with a hex file from QMK Configurator. I am trying to build a custom keyboard.

When you tried the same command as the IDE, did you close the IDE? There is a possibility that it has the port open, which will block other programs from accessing it.

You have to reset the Arduino using a very special procedure in order
for it to accept being programmed. This involves opening the port at
1200 bps, toggling some control lines, and closing the port again.
You may try using this ard-reset-arduino Python script with the
option --caterina.
By the way, this script belongs a project called “Arduino-Makefile”. You
may want to take a look if you want to program your Arduino from the
command line. Alternatively, you can use arduino-cli.

"I am trying to flash my device with a hex file from QMK Configurator." The arduino-cli does the 1200baud touch as part of the upload process, but it might not apply or may need clarification on how to apply. I'm not sure how you'd make use of it unless it has the ability to be supplied arbitrary hex files to upload, or has a stand-alone command for issuing a 1200 baud touch, or unless you can sneak your hex file over top of one the compile command had created.  "I even tried resetting twice quickly" This should have given them 8 seconds of bootloader time, though the tool would help.


text:
What is the difference between ":i" and ":a" in avrdude command?
What is the difference between :i and :a after my hex file path in avrdude command.
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM8 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:i

and
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

:-( The art of reading manuals is being lost more and more.

These are Avrdude file format specifiers.
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

The final :a in this case is a format specifier meaning "auto detect; valid for input only, and only if the input is not provided at stdin."
An :i in the same position means "Intel Hex"
A complete list can be found here: https://www.nongnu.org/avrdude/user-manual/avrdude_3.html#Option-Descriptions

It is worth noting that :a is the default, and can thus be omitted. Also, if this version of avrdude is not too old, it can understand the ELF file: no need to convert it to hex.


text:
Communication between 2 arduino's one at 6th floor and the other at the basement
Communication between 2 Arduino's one at 6th floor and the other at the basement.
I tried with nodemcu , but the signal is not reaching the basement. From 6th floor.

Which is the best way to connect?.
I have a couple of nRF24L01 with antennas, does nRF24L01 works in this case?
How about hc-12. I have seen tests with line of sight's only.  But in this case, I have an elevation of about 80 feet and also some horizontal distance.
Basically, I wanted to implement wireless water level measurement for our overhead tank inside our apartment.
Regards
ravi

2.4 GHz radio is too short range.  Try 433 MHz modules instead.

lora will work if nothing else does. you can get ESP8266 boards with antenna jacks. using a shotgun antenna on the roof will almost assuredly connect to the basement once aimed.


text:
Wiring ESP8266 and PN532
I'm trying the Android Hce example in this PN532 library. I can't find how to set SDA and SCL address in the code, so I tried connecting them in CLK and SD0 pins. The serial monitor gives me "Didn't find PN53x board". Can someone help me?
    #if 0
      #include <SPI.h>
      #include <PN532_SPI.h>
      #include "PN532.h"

      PN532_SPI pn532spi(SPI, 10);
      PN532 nfc(pn532spi);
    #elif 1
      #include <PN532_HSU.h>
      #include <PN532.h>

      PN532_HSU pn532hsu(Serial1);
      PN532 nfc(pn532hsu);
    #else
      #include <Wire.h>
      #include <PN532_I2C.h>
      #include <PN532.h>
    #endif

    void setup()
    {
        Serial.begin(115200);
        Serial.println("-------Peer to Peer HCE--------");

        nfc.begin();

        uint32_t versiondata = nfc.getFirmwareVersion();
        if (! versiondata) {
          Serial.print("Didn't find PN53x board");
          while (1); // halt
        }

        // Got ok data, print it out!
        Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
        Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
        Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

        // Set the max number of retry attempts to read from a card
        // This prevents us from waiting forever for a card, which is
        // the default behaviour of the PN532.
        //nfc.setPassiveActivationRetries(0xFF);

        // configure board to read RFID tags
        nfc.SAMConfig();
    }

    void loop()
    {
      bool success;

      uint8_t responseLength = 32;

      Serial.println("Waiting for an ISO14443A card");

      // set shield to inListPassiveTarget
      success = nfc.inListPassiveTarget();

      if(success) {

         Serial.println("Found something!");

        uint8_t selectApdu[] = { 0x00, /* CLA */
                                  0xA4, /* INS */
                                  0x04, /* P1  */
                                  0x00, /* P2  */
                                  0x07, /* Length of AID  */
                                  0xF0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* AID defined on Android App */
                                  0x00  /* Le  */ };

        uint8_t response[32];

        success = nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength);

        if(success) {

          Serial.print("responseLength: "); Serial.println(responseLength);

          nfc.PrintHexChar(response, responseLength);

          do {
            uint8_t apdu[] = "Hello from Arduino";
            uint8_t back[32];
            uint8_t length = 32;

            success = nfc.inDataExchange(apdu, sizeof(apdu), back, &length);

            if(success) {

              Serial.print("responseLength: "); Serial.println(length);

              nfc.PrintHexChar(back, length);
            }
            else {

              Serial.println("Broken connection?");
            }
          }
          while(success);
        }
        else {

          Serial.println("Failed sending SELECT AID");
        }
      }
      else {

        Serial.println("Didn't find anything!");
      }

      delay(1000);
    }

    void printResponse(uint8_t *response, uint8_t responseLength) {

       String respBuffer;

        for (int i = 0; i < responseLength; i++) {

          if (response[i] < 0x10)
            respBuffer = respBuffer + "0"; //Adds leading zeros if hex value is smaller than 0x10

          respBuffer = respBuffer + String(response[i], HEX) + " ";
        }

        Serial.print("response: "); Serial.println(respBuffer);
    }

    void setupNFC() {

      nfc.begin();

      uint32_t versiondata = nfc.getFirmwareVersion();
      if (! versiondata) {
        Serial.print("Didn't find PN53x board");
        while (1); // halt
      }

      // Got ok data, print it out!
      Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
      Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
      Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

      // configure board to read RFID tags
      nfc.SAMConfig();
    }

For I2C the default pins to use are whatever are defined in your board configuration - probably pins 4 and 5 (to mirror A4 and A5 on the Uno). However your code is set up to use serial, not I2C.

I was doubting so, can you please tell me the exact wiring for serial? (Or for anything to make this code work). I'd like to even know how to get these information, usually I find the pinout in the define section (how should be done)

For serial connect it to the UART1 TX and RX pins. Where those are depends on what module you have.

I have connected SCK to CLK (on ESP8266), MSO and MOSI connected to D6 and D7. How should I set up this in code? I tried to changing SPI, but it doesn't work

What you wire to where, and what code you use, depends on what PN532 module you have and what ESP8266 module you have.

I have Elechouse PN532 Module V3 and a NodeMCU

This one?

Solved. Set #if 1 and #elif 0.
Connected:
SCK to D5
MISO to D6
MOSI to D7
SS to D0 (and set it on pn532spi)


text:
How to burn a bootloader to non-bootloaded(clean crystal) ATMEGA328P-PU with USBASP programmer via Avrdudess?
I'm trying to burn bootloader to my clean crystals, atmega328p-pu.For this I use the 16MHZ crystal with two ceramic capacitors and USBASP programmer, on Windows 10 Pro. As program for burning I tried: Arduino IDE, AVRDUDESS,AVRDUDEPROG. But when I would to detect my chip(or in IDE try to burn the Chip)., I get this error:
`
avrdude.exe: set SCK frequency to 1500000 Hz
avrdude.exe: warning: cannot set sck period. please check for usbasp firmware update.
avrdude.exe: error: program enable: target doesn't answer. 1
avrdude.exe: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.
avrdude.exe done.  Thank you.
`
From this error I understand that the target(My chips) Wouldn't to start. I checked my connection for 1000 times and I tested mt wires too, they works correctly. And supply 5V comes o chip and it become warm(it means that supply comes and it should start). I have got 5 chips And I tested all of them. I searched internet but nothing.
Please,help me, and say how can I burn them.
Best Regards,
E.M.

My understanding of that error message is that your USBASP is unable to set the right clock speed. Maybe it's got inferior (out-dated) firmware on it...

Not only. In khazarma or in avrdudeprog it don't work too

It without the bootloader. And

Have you tried with another programmer? Like I said: the error looks to pertain to the programmer, not the software or the chip.

So can I use the Arduino As ISP? If yes should I change the SPI_CLOCK to (16000000/6) as I use the 16 MHZ crystal? And which baudrate should I use:19200,115200,1000000? in ArduinoISP sketch?

don't change the Arduino as ISP sketch. select Uno in Tools menu to burn the bootloader. Uno has a 16 MHz oscillator

I'm intrigued to know what a "clean crystals atmega328p-pu" is...

it worked!!!. I took of the capacitors that was connected to crystal 16MHZ, that connected to the common GND of Arduino. So and I changed in sketch and defined the Old Wiring that I used it and it worked!!! And one more question. Why the capacitors are changed this results?

clean crystals atmega328p-pu is non-bootloaded chips


text:
FastLED not performing as expected
I'm fairly new to working and programming with arduinos. The project I am working on is a digital clock which uses a string of WS2812 leds to light up the correct numbers. Each digit consists of 7 leds and there are two 'colon' leds between the second and third digits. I am using the FastLED library to try to program the code. I am able to make the leds light up such that all four digits are the same number (four consecutive 5's). However, the second I try to have it display multiple different numbers, everything goes south quickly. Here are some pictures of my current results:

55:55. I can create this with any number 0-9.

Should be 12:34.
Here is the code that I'm working with so far:
#include <RTClib.h>

RTC_DS3231 rtc;
DateTime now;

#define NUM_LEDS 30
#define LED_PIN 6

CRGB leds[NUM_LEDS];

void setup() {
  // put your setup code here, to run once:

  Serial.begin(57600);

  FastLED.addLeds<WS2812, LED_PIN>(leds, NUM_LEDS);

  FastLED.clear();
}

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

  const int ZERO[]={0,1,2,4,5,6};
  const int ONE[]={2,6};
  const int TWO[]={0,1,3,5,6};
  const int THREE[]={1,2,3,5,6};
  const int FOUR[]={2,3,4,6};
  const int FIVE[]={1,2,3,4,5};
  const int SIX[]={0,1,2,3,4,5};
  const int SEVEN[]={2,5,6};
  const int EIGHT[]={0,1,2,3,4,5,6};
  const int NINE[]={2,3,4,5,6};

  for(int i=0; i<sizeof(ONE);i++){
        leds[ONE[i]]=CRGB::Red;
        FastLED.show();
      }

  for(int i=0; i<sizeof(TWO);i++){
        leds[TWO[i]+7]=CRGB::Red;
        FastLED.show();
     }

  for(int i=0; i<sizeof(THREE);i++){
        leds[THREE[i]+16]=CRGB::Red;
        FastLED.show();
      }

  for(int i=0; i<sizeof(FOUR);i++){
        leds[FOUR[i]+23]=CRGB::Red;
        FastLED.show();
      }

Can anyone explain what's going wrong? Any help would be greatly appreciated. Let me know if you need clarification!

what happens if you turn off all LEDs first? ... try putting FastLED.show(); after the last for loop

I did try that and nothing changed. I also have FastLED.clear(); in the set up so it at least gets cleared once when the program is uploaded.

Start by writing a sketch that switches just one segment of one digit on, all others off. Then each second, change to the next segment. You might find the problem, be it in your usage of FastLED or the hardware. (Hardware, because it looks like a multiplexing problem.)

Your problem is your usage of sizeof(). It doesn't do what you think it does.
sizeof() gives you the amount of memory a variable takes up. It does not give you the number of elements in an array.
For example:
const int ONE[]={2,6};

sizeof(ONE) will not give you 2. It will give you 4. An int is two bytes in size (16 bits). An array of 2 ints is, therefore, 2x2 = 4 bytes.
So when you're iterating over a 2 byte array but counting 0-3 you're overflowing your array and reading from the next bits of memory - which happen to be the first two entries of the TWO array in this case.
To get the number of entries in an array you must divide the sizeof() by the size of the variable type the array is made up of.  The most common way of doing that is:
sizeof(ONE) / sizeof(ONE[0])

It's common to set up some macros at the time of array creation so you can easily refer to it later:
const int ONE[]={2,6};
#define ONE_SIZE (sizeof(ONE) / sizeof(ONE[0]))

You should also consider using an array of byte (or better, the standard uint8_t) where the size of one element will be 1 not 2, since you don't need to store any number > 255. It's still good to do the division of the sizeof() even with a 1 byte size in case you should ever need to change the variable type in the future. It's also a good habit to get into.

This explains SO much! It works now. Thank you!


text:
How can I program a ATmega328 au tqfp32 ( SMD ) chip?
I have some experience with the Arduino UNO , Nano , mega etc .. But today I want to upgrade my skills and knowledge to next level . So I am about to design my own PCB for ATmega328 au ( SMD ) but this time I want to use a tqfp32 programmer to get the job done .. I have searched the internet and I have found that people use Universal programmers ( ISP ) such as Top2013 universal programmer or TL86ii but I have no idea how to use them and I don't even know what  software that the youtubers are using ... They are actually uploading some *.hex files it seems I am not sure but they aren't using Arduino IDE . According to my knowledge they are using a tqfp32 to dip28 programming module ( I have attached a pic ) . And then the Module is mounted on top of the ISP . Then they have uploaded code using some unknown software. And few people are using USBasp , can any explain me the scenario and what they have done ..  https://youtu.be/GFyr9tVEHzQ
The link is a reference video .

Please add more info to your question on how this will be used in relation to Arduino. Thanks.

The link to the video in your question is of a "promotional" nature (TQFP32 to DIP 28 converter Zif socket). If you want to know more about their product, click the "SHOW MORE" link. This network is for Arduino questions, not questions about the TQFP32.

To upload compiled code (.hex) to a bare atmega which doesn't have a bootloader installed you can use ISP. As this stands for in-system-programming you don't have to flash the chip before assembly, but you can flash it in-system, so when already soldered onto your pcb. There actually is no need for those adapters like shown in your first picture, which often are a bit expensive. Also, both pictures stand in contrast to the idea of ISP, they seem to show firmware upload via serial connection, which as far as I know only works with a bootloader already installed...
ISP is based on SPI (serial peripheral interface) and you need to break out the corresponding pins to fit this connector. This obviously has the advantage of being able to update a firmware afterwards without the need of a bootloader.
Atmel provides a tool for flashing firmware via ISP which is called avrdude (tutorial) or you can use the atmel studio. To compile your code, you can use avr-gcc.

I use Atmel AVR ISP MKii, which is a dedicated Programmer - it connects via USB to the PC, and to the Power/Gnd/Reset/SCK/MOSI/MISO pins of the SMD device (i.e. the pins that connect to an ICSP header if one were installed).  Then in the IDE you can select Upload Using Programmer, and it will load the .hex file that is created as part of the IDE compilation process into the chip.  This blows away any bootloader that might exist.
The Arduino as ISP does the same, running a sketch on an Uno for example that then interfaces with the PC and the target device to program it via the ICSP connection.
If the pins are not brought to a header, but are accessible via edge connecters, than a Programmer adapter can be used to connect the Programmer to the desired pins.  Imagine this board had a SMD package vs a DIP - then the 6 wires are connected to the desired pins, in this case via flying wires, and programming can be done.  A FTDI module is connected to other pins (5V, Gnd, DTR, Tx, Rx) just to provide power to the board. The AVR ISP MKii only monitors the power level in use (generally 3.3V or 5V) and adjusts its output levels accordingly.

The TQFP socket you show would generally be used to pre-program chips in a manufacturing type environment before they are installed on boards, or by a distributor like Digikey if you were ordering a large quantity of parts.
Making the ICSP pins accessible on board somehow is often not hard, and can be beneficial for making changes.
Here is an example of the same chip in a TQFP package, and you can see the dedicated ICSP and FTDI headers to allow onboard bootloading and then Serial downloads of code being developed.

I find the dedicated hardware very convenient as I bootload and/or program a lot of boards and SMD chips on boards.
I also have this adapter for Atmega328P chips that are installed on a board.  There are 6 little spring-loaded pins that press down onto the chip's ICSP pins from above to allow programming when an ICSP header is not provided, or the signals are not brought out to accessible pins. Unfortunately, hobbyking.com does not stock them anymore, this has gotten me out of a jam on occasion.

Do you have the name of that last item with the spring-loaded pins?

I got it from hobbyking.com. I don't see it listed there now, and I haven't found it anywhere else online. Which is too bad, it's a nice tool to have.

This is the closest I could find http://www.diagnosys.com/DTI/41-0191.PDF Dated 2014 CLIP 41-0191 I don't see a way to buy one tho.


text:
Nodemcu POST Response "-1"
Nodemcu device is returning HTTP response -1 for a POST request on django rest api.
I tried the below http request to Postman, and it works perfectly fine.
http://localhost:8000/api/datalogs/?plant=http://localhost:8000/api/plants/1/&light=23&temperature=24&humidity=75&soil=Dry&moisture=787&remarks=/
This is my arduino post request:
if(WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    http.begin(host_url);

    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httpCode = http.POST(postData);

    payload = http.getString();
    http.end();
}

The expected result is 200, but I get -1. Can someone please explain?

the values of host_url and postData are not shown ... your code is sending unknown data .. therefore there is nothing to explain

you use the name "localhost" in the request from other device?

can you be more specific about the code on nodemcu side like what is the host_url and also postdata. At the same time update the code form Django side like what function is catching the http response from nodemcu.

Yes, thanks. I might be messing it with localhost, whereas my device has a different ip than my computer.. I should give it a try first Juraj

The host_url is http://localhost:8000 and the postData is "plant="+String(host)+"plants/1/&light="+String(lux)+"&temperature="+String(temperature)+"&humidity="+String(humidity)+"&soil="+mRes+"&moisture="+mVal+"&remarks=/";
I think the issue might be localhost jsotola

So, I tried using ip address, also configured from django settings, works perfectly from my mobile device, Insomnia REST API client. But Nodemcu returns 301 Moved Permanently.

if it returns 301 then only https is allowed so the url should use https://

So, I found the solution. It was a very simple mistake. The NodeMCU IP is not the same as the Computer IP that the server was running on.
I changed the localhost string with the IP of my pc, and it worked perfectly fine.


text:
Camera VC0706 send image save to pc
i'm working on project now,
i need to save picture from camera VC0706 serial camera in specific folder on my PC, i found a tutorial (indonesian tutorial), thath give me code to use the camera, but they not tell me how to save the picture,
basically i need this image show on android phone, but i don't have money to buy a paid web server that can store image, so i want to use local webserver (PhpMyadmin using Xammpp) and call the image from htdoc folder, so i can show the image on android phoe
here is the code
 #include <Adafruit_VC0706.h>
#include <SoftwareSerial.h>

// Software serial & camera instance
SoftwareSerial cameraconnection = SoftwareSerial(2,3); // RX, TX
Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

void setup() {

  Serial.begin(115200);
  Serial.println("Program Test Camera");

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Terbaca");
  } else {
    Serial.println("Camera Tidak Terbaca !!!");
    return;
  }

  // Set ukuran gambar
  cam.setImageSize(VC0706_640x480);   // Vga
  //cam.setImageSize(VC0706_320x240); // Qvga
  //cam.setImageSize(VC0706_160x120); // QQVGA
  // Tunggu 3 detik untuk capture
  Serial.println("Picture in 3 seconds ...");
  delay(3000);

  if (! cam.takePicture())
    Serial.println("Failed to capture!");
  else
    Serial.println("Capture Gambar OK ");
}

void loop() {
}

why don't you start with the example code that is included with the library?

@jsotola library of what?

The examples of the Adafruit_VC0706 library. It shows, how to save an image to a SD card. For sending it over wifi, you first need a wifi module. You can buy an ESP8266 module for that, though it might be a better idea to directly use an ESP instead of the Mega