message:
Why no brackets after Interrupt routine inside attachInterrupt

I'm just curious as to why there are no brackets at the end of the ISR when attaching and assigning the interrupt command?

```
 attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
 ...
 void blink() {
    state = !state;
 }
```

In, attachInterrupt, I would have expected "blink" to be written as "blink()", with the brackets, not just the name of the function, sort of like how you would normally call the function blink() from your loop or setup functions (or elsewhere). So, what's going on here, and are there other scenarios where you might use a function without the brackets after it?

body:
It is right, that you are putting brackets after the function name if you are **calling it**. But with `attachInterrupt()` you just want to give it the information, which function to call in case of an interrupt. With the brackets the compiler would think you want the function to be executed and the result/return value being given as parameter to `attachInterrupt()`. But the execution here should only happen in case of an interrupt. The `attachInterrupt()` function/the corresponding ISR need to know, what to call in case of an interrupt. Just the information/address of the function.

Maybe you have already heard of pointers. That are variables that hold the address of a different variable. They are pointing somewhere else in the memory. `blink` (without the brackets) is basically a function pointer. Leaving the brackets away tells the compiler, that you want the address of the function, not executing it. You are providing the function parameter by reference this way, providing the address, not the value.

If you like/need you can use that principle yourself by defining your own function pointer variable. For example this

    void (*myCallbackFunction)(int);

which is a function, that takes an int as parameter and returns nothing (void). You can then set the function pointer and call it as a normal function

    void blinkXTimes(int times){
        for(int i=0;i<times;i++){
            digitalWrite(pin, HIGH);
            delay(500);
            digitalWrite(pin, LOW);
            delay(500);
        }
    }

    void setup(){
        pinMode(pin, OUTPUT);
        myCallbackFunction = blinkXTimes;

    void loop(){
        myCallbackFunction(3);
        delay(5000);
    }

We are calling `myCallbackFunction()`, but it is a function pointer, that points to `blinkXTimes()`, so that will be executed.

> So, what's going on here, and are there other scenarios where you might use a function without the brackets after it?

The above principle is super useful for writing libraries with user callback functions. Another example (besides `attachInterrupt()`) is the `Wire` library. There the receive and request interrupts need to interact with the library user to deliver to or request data from him. For this the `Wire` library lets you set your own callback functions. Refer to the examples of that library.

Another application would be building a Finite State Machine with a function pointer (basically calling different functions on each loop iteration depending on the state, which is represented by the function pointer).

That are the two big application I know of. The first one is more common. Though function pointers are just a tool. They can be used for many things.


sender: user

message:
Arduino Multiplexer Input voltage per pin not decoupled

I am very new to electronics (software engineer background).

I want to send an analog signal (5V) to one/many input wires. The input wires are connected to a 16 channel mutiplexer.
My arduino then reads all of the 16 channels.

Right now the issue is: If I connect only one pin to the 5V output of the arduino many other of the multiplexer input pins also read high voltage values even tho only one pin is actually connected.

I am pretty sure this issue is a duplicate - please point me to the right direction.

I have read about decoupling (if that is the case - please explain it for newbies without background).

sender: assistant

body:
As I understand it you have a multiplexer with one of the inputs connected to 5 volts and the rest are open. What you are reading is leakage in the IC and associated wiring. There are many reasons they tell us not to leave inputs open, you just found one. This is especially problematic with CMOS devices because of there extremely high impedance. The first thing the TI publication
SCBA004D–July 1994–Revised September 2016 tells you is power consumption is
becoming a major issue in today’s market. However, when designing systems using CMOS and BiCMOS devices, one must understand the characteristics of these families and the way inputs and outputs behave in systems. It is very important for the designer to follow all rules and restrictions that the manufacturer requires, as well as to design within the data-sheet specifications. Because data sheets do not cover the input behavior of a device in detail, this application report explains the input characteristics of CMOS and BiCMOS families in general. It also explains ways to deal with issues when designing with families in which floating inputs are a concern. Understanding the behavior of these inputs results in more robust
designs and better reliability.


message:
Arduino Nano not recognized by Mabook Pro M1

I am new to Arduino and I have ran into an issue. When I first tried to plug the arduino nano (after market, from ebay) into my computer (Macbook pro M1), nothing happened. Then I downloaded the cp210xVCP Driver. After that, when I plugged in the nano, the /dev/cu.usbserial- 1110 appeared. But when I try to get board info noting happens. It's like the computer recognize there is something, but does not know what. I believe Arduino is not fully compatible for M1 macbooks, but is there something I can do to fix this?

[![ fi][1]][1]

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

body:
Majenko and Python Schlange have the right of it I think. This is a common and well documented phenomenon. Check out [the comments](https://forum.arduino.cc/t/unable-to-find-board-information-on-new-arduino-nano/525184) on the Arduino forum by the arduino team which explain PIDS and VIDS on USB equipment and why the clones appear differently. It shouldn’t (all going according to plan) make a difference other than the board information not being present as you’ve noted. That’s why Majenko is suggesting you go ahead and upload a sketch. The [Blink][1] example sketch is frequently used for this as a first board test when you receive something new.

See also https://arduino.stackexchange.com/questions/80794/usb-ft232-driver-on-m1-mini/80795#80795 for more information about checking USB ports on the Mac.

  [1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink


message:
Problem with first two samples of serial data received by RPi

I'm trying to receive a string from an Arduino to a Raspberry Pi via a Bluetooth socket connection (RFCOMM).  I'm using an HC-06 Bluetooth module, an Arduino UNO R3, and an RPi 4 Model B.  For the most part, everything is working well --except the first two data samples.  This is what my output generally looks like when I view it from the RPi terminal:

    0.
    06,21,0.01,64
    0.06,21,0.01,64
    0.06,21,0.01,64
    0.06,21,0.01,64
    0.06,21,0.01,64
    0.06,21,0.01,64

Is there any way I can get the first two lines to show the data properly?  This data is a singular string and I chose my buffer to be 32 bits, so I don't think buffer size is the issue.  I had to add time.delay(4) in my Py script or else every sample of the data would look messed up.  I've tried adjusting the time delay relentlessly, but I can't seem to get the first two samples to display correctly.  Below is a bit of my Python code:

    while 1:
    try:
            received_data = bluetoothSocket.recv(24)
            formatted_data = received_data.decode("utf-8")
            print("Received Data: ", formatted_data)
            time.sleep(4)

    except KeyboardInterrupt:
            print("keyboard interrupt detected")
            break
    bluetoothSocket.close()

body:
You might want to try sending the data in a packet delimited by unique characters, e.g. `{` and `}`, similar to the [JSON format][1].

The [NMEA GPS][2] standard uses `$` and '\n' to delimit messages.

Here is an Arduino non-blocking C++ algorithm which builds upon [Majenko's `readline()` example][3] to read a packet. It returns true when incoming data has been accumulated into a valid packet. It should be fairly straightforward to convert it to Python.

```cpp
void setup()
{
 Serial.begin(115200);
 Serial.println(F("\n\nSerial Packet Test\n"));
 pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
 const static unsigned int INTERVAL = 200;
 static unsigned long previous_timestamp = millis();
 unsigned long current_timestamp = millis();
 static bool led_state = false;

 if (current_timestamp - previous_timestamp >= INTERVAL)
 {
  led_state = !led_state;
  digitalWrite(LED_BUILTIN, led_state);
  previous_timestamp += INTERVAL;
 }

 static char packet[100];

 if (ReadPacket(Serial, packet, sizeof(packet)))
 {
  Serial.print(F("Received packet >"));
  Serial.print(packet);
  Serial.println(F("<"));
 }
}

bool ReadPacket(Stream& stream, char *const packet, const unsigned int SIZE)
{
 const char FIRST = '{';
 const char LAST = '}';
 static bool read_until_last = false;
 static unsigned int i = 0;
 char ch;

 if (stream.available())
 {
  ch = stream.read();

  if (ch == FIRST)
  {
   Serial.println(F("Received FIRST."));
   i = 0;
   packet[0] = ch;
   read_until_last = true;
   return false;
  }
  if (read_until_last)
  {
   i++;
   if (i > SIZE - 2)
   {
    Serial.println(F("Buffer overrun. Resetting to look for next packet."));
    i = 0;
    read_until_last = false;
    return false;
   }
   if (ch == LAST)
   {
    Serial.println(F("Received LAST."));
    packet[i++] = ch;
    packet[i] = 0;
    read_until_last = false;
    return true;
   }
   else
   {
    Serial.print(F("Received char >"));
    Serial.print(ch);
    Serial.println("<");
    packet[i] = ch;
    return false;
   }
  }
 }
 return false;
}
```

  [1]: https://en.wikipedia.org/wiki/JSON
  [2]: https://www.gpsworld.com/what-exactly-is-gps-nmea-data/
  [3]: https://majenko.co.uk/blog/reading-serial-arduino


body: I don't know what the `time.sleep(4)` statement fixes, but you could try moving the  to the top of the loop instead of the bottom, so it precedes the first read. At the bottom of the loop, it's first execution comes *after* the first read.


message:
Can I pass data from an Arduino Nano to a Websocket Server via USB?

I have an Arduino Nano, and a local Java WebSocket server (ws://localhost:8888) run by a .jar file on my computer.

I'm wondering if it's possible to send data (text, numbers etc.) from the Arduino Nano to the WebSocket server via USB cable (USB-A to USB Mini, one that normally powers the Nano).

If so, what do I need to do it?

A quick Google for WebSocket Arduino libraries reveals:

[Websockets][1] and [Arduino Websocket Fast][2], but looking at the examples, the former uses Ethernet.h and the latter uses Wifi.h, and I'm unsure if my board is compatible with that without other modules.

  [1]: https://www.arduino.cc/reference/en/libraries/websockets/
  [2]: https://www.arduino.cc/reference/en/libraries/arduino-websocket-fast/

body: No, you can't. The Arduino has a serial connection, not a network connection. If the Java program is of your own devising you would need to rewrite it to use serial instead of (or as well as) WebSockets. Either that or write a separate piece of software for your computer to go between the Arduino's serial connection and the WebSockets interface.


body:
As @Majenko already said the ATmega328 uses a serial connection to communicate. Another chip on the board translates the serial data to USB-Format and the other way around. This enables your computer to interact with the main chip on the Nano (ATmega328).
To solve your problem you might try using something like [this](https://github.com/RandomStudio/serial-to-websocket) simple serial-to-websocket node-server that listenes to data coming in from a serial port and sends it out over WebSocket.


body: I ended up using Python to bridge Serial to WebSocket. I wanted flexibility in sending from WebSocket back to Serial too, so I didn't try a prepackaged solution like https://github.com/RandomStudio/serial-to-websocket


message:
CH340K - Unknown USB Device (Device Descriptor Request failed)

I have a Arduino Nano clone working fine with the CH340 drivers. It has a CH340C on it.

I made a custom PCB. CH340 chips are hard to come by these days, so I opted for the CH340K, From the datasheet, seems like it should work similar to the CH340C and CH340G that are quite common.

My PCB has a footprint for both the CH340K and CH340C/CH340G (Yes, I'm aware I'm missing the load capacitors for the CH340G). CH340C/N/K/E and CH340B have built-in clocks without external crystal oscillator. So no need for a crystal.

After soldering on the CH340K and USB port, I plugged the device in, and I'm getting an error in Windows 10 Device Manager:

> Unknown USB Device (Device Descriptor Request failed)
>
> Windows has stopped this device because it has reported problems.
> (Code 43)
>
> The USB set address request failed.

I've uninstalled and reinstalled the CH340 drivers several times. Tried to force the driver onto the device in device manager, and it didn't let me.

There's no short to ground or vcc.

Any help to get this recognized would be great! thanks!

**CH340K Pinout**

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

**PCB**

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

  [1]: https://i.stack.imgur.com/7YnCt.png
  [2]: https://i.stack.imgur.com/uzARR.jpg

body:
Needed a 100nf capacitor on the v3 pin, per Majenko's suggestion, and per datasheet.

I thought this was only needed if you were going to use the 3.3v output for other purposes. I was wrong!

Same requirement for the CH340C!


message:
Modbus rtu data decimal to float conversion

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

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

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

  [1]: https://i.stack.imgur.com/wkaBo.jpg
  [2]: https://i.stack.imgur.com/064VT.jpg
  [3]: https://i.stack.imgur.com/EdLPt.jpg

Hi,am trying to communicate with power-factor controller [Selec APFC 148-312] using modbus RTU,am following example sketch from modbusmaster library. am able to get the raw data from the instrument but data structure seems to be in decimal format, can someone help me to convert this into float.thank you

    #include <ModbusMaster.h>

    #define MAX485_DE      3
    #define MAX485_RE_NEG  2

    // instantiate ModbusMaster object
    ModbusMaster node;

    void preTransmission()
    {
      digitalWrite(MAX485_RE_NEG, 1);
      digitalWrite(MAX485_DE, 1);
    }

    void postTransmission()
    {
      digitalWrite(MAX485_RE_NEG, 0);
      digitalWrite(MAX485_DE, 0);
    }

    void setup()
    {
      pinMode(MAX485_RE_NEG, OUTPUT);
      pinMode(MAX485_DE, OUTPUT);
      // Init in receive mode

      digitalWrite(MAX485_RE_NEG, 0);
      digitalWrite(MAX485_DE, 0);

      // Modbus communication runs at 9600 baud
      Serial.begin(9600);

      // Modbus slave ID 1
      node.begin(1, Serial);
      // Callbacks allow us to configure the RS485 transceiver correctly
      node.preTransmission(preTransmission);
      node.postTransmission(postTransmission);
    }

    void loop()
    {
      float result;

      result = node.readInputRegisters(0x30000, 10);
      if (result == node.ku8MBSuccess)
      {

        Serial.print("V1N: ");
        Serial.println(node.getResponseBuffer(0x01));

        Serial.print("V2N: ");
        Serial.println(node.getResponseBuffer(0x02));

        Serial.print("V3N: ");
        Serial.println(node.getResponseBuffer(0x03));

        Serial.print("Vavg: ");
        Serial.println(node.getResponseBuffer(0x04));

        Serial.print("V12: ");
        Serial.println(node.getResponseBuffer(0x05));

        Serial.print("V23: ");
        Serial.println(node.getResponseBuffer(0x06));

        Serial.print("V31: ");
        Serial.println(node.getResponseBuffer(0x07));

        Serial.print("L-L avg: ");
        Serial.println(node.getResponseBuffer(0x08));
      }
      delay(1000);
    }

body:
I'm not sure this can really be considered topical, but someone wanting to read floating point numbers over MODBUS with an Arduino might get something out of it.  Also I have no way to test this really.  But here goes:

Your MODBUS map shows V2N at 30002, and you notice 30003 is not mentioned in the map.  Your voltage from phase two to neutral appears to be encoded into two consecutive 16-bit registers, which is a somewhat normal scheme for conveying 32bit floats via MODBUS, from what I can tell.  So, your values of `17280` and `9830` are two halves of a 32-bit floating point number.  In hex, 0x4380 and 0x2666.  These seem to be taken together as 0x43802666 as the bit pattern for 32-bit float.

A function like this would allow you to extract your 32-bit float data from your separate 16-bit MODBUS register reads:

```c++
float modbus_16bit_register_pair_to_float(uint16_t a, uint16_t b) {
    uint32_t combined = ((uint32_t)a << 16) | b;
    float f;
    memcpy(&f, &combined, sizeof f);
    return f;
}
```

There are lots of ways you could do this.  This code assumes that the `float` type's endian matches the `uint32_t` type's endian, and that `float` is 32-bit, which is common but not strictly standard.

Running this on `17280` and `9830` gives 256.3 (rounded), which doesn't perfectly match other output, but I suspect that's just because the reading is varying.


message:
How to gradually increase and decrease the speed of a motor using IR remote

I am making an IR controlled helicopter and I have the very basic part of the code done, but I don't know how to make the motor gradually increase speed. I want the motor to gradually increase speed when you hold the button on the IR remote and hold its speed when you stop pushing the button. And the same for when the helicopter goes down.
Here is the code:

       #include <IRremote.h>
       #include <Servo.h>
       #define enA 9
       #define enB 11
       #define in1 6
       #define in2 7
       #define in3 4
       #define in4 5

       Servo ball1;

       int IR_RECEIVE_PIN = 2;
       IRrecv IrReceiver(IR_RECEIVE_PIN);
       decode_results results;

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

         ball1.attach(10);

         pinMode(in1, OUTPUT);
         pinMode(in2, OUTPUT);
         pinMode(in3, OUTPUT);
         pinMode(in4, OUTPUT);
       }
       void loop() {
         if (IrReceiver.decode(&results)) {
           switch (results.value) {

             case 0xFFA857:
               Serial.println("case: UP");
               digitalWrite(enA, 255);
               digitalWrite(in1, HIGH);
               digitalWrite(in2, LOW);
               break;

             case 0xFFE01F:
               Serial.println("case: DOWN");
               digitalWrite(enA, 120);
               digitalWrite(in1, LOW);
               digitalWrite(in2, LOW);
               break;

             case 0xFF18E7:
               Serial.println("case: FORWARD");
               ball1.write(90);
               break;

             case 0xFF10EF:
               Serial.println("case: LEFT");
               digitalWrite(in3, LOW);
               digitalWrite(in4, LOW);
               break;

             case 0xFF5AA5:
               Serial.println("case: RIGHT");
               digitalWrite(in3, HIGH);
               digitalWrite(in4, LOW);
               break;

             case 0xFF48B5:
               Serial.println("case: BACKWARD");
               ball1.write( ? ); // I need help on the direction of the linear servo
               break;
           }

           Serial.println(results.value, HEX);
           IrReceiver.resume();
         }
       }

It is the same code I used to control a RGB LED (But modified). Would it be possible to upload this code to an IC? I already programmed my UNO as an ISP, but there seems to be a problem. Also, I am using a linear servo for the pitch of the helicopter, can someone please show me how to change the direction of a linear servo? I have one that is similar to the Pico linear servo.

body:
You could separate reading the controls and taking actions and there are several ways of doing that, one example shown below where the switch() can be used to read all commands and according to the value call one or more atomic functions. For instance, one function to change speed and another one to change direction, and perhaps calling several functions in a row for more complex tasks like take off and land (I have no idea how those helicopter projects works).

On each case you do the validation, min and max allowed values, dependencies on other factors and alike.

    void loop() {

      if (IrReceiver.decode(&results)) {

        switch (results.value) {

          case 0xFFA857: // up
            verticalSpeed = verticalSpeed + verticalSpeedStep;
            if (verticalSpeed > maxVerticalSpeed) verticalSpeed = maxVerticalSpeed;
            setVericalMotor();
            break;

          case 0xFFE01F: //down
            verticalSpeed = verticalSpeed - verticalSpeedStep;
            if (verticalSpeed < 0) verticalSpeed = 0;
            setVericalMotor();
            break;

        }
      }
    }

    void setVericalMotor() {
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(enA, verticalSpeed);
    }

As for your question regarding the servo, they usually run from 0 to 180 degrees, so tey anything in that range as the "reverse" for 90 degrees for Forward (normally that should be 0 or 180).


message:
ESP 32 unable to connect to https website and return the data using GET

I have created a ThingHTTP below:

    https://api.thingspeak.com/apps/thinghttp/send_request?api_key=BVLJ7A6KNK9VVAYK
In my browser I could see the reply. But I am unable to make this work in my ESP32. I understand that this is a https so I would have to declare the root cert details. I have tried to modify based on this tutorial:

    https://github.com/witnessmenow/arduino-sample-api-request/blob/master/ESP8266/HTTP_GET/HTTP_GET.ino

My code as follows:

    #include <WiFi.h>
    #include <WiFiClientSecure.h>

    //------- Replace the following! ------
    char ssid[] = "SSID";       // your network SSID (name)
    char password[] = "pass";  // your network key

    // For Non-HTTPS requests
    // WiFiClient client;

    // For HTTPS requests
    WiFiClientSecure client;

    // Just the base of the URL you want to connect to
    #define TEST_HOST "https://api.thingspeak.com/apps/thinghttp/send_request?api_key=BVLJ7A6KNK9VVAYK"

    const char *server_cert = "-----BEGIN CERTIFICATE-----\n"
                                      "MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\n"
                                      "RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\n"
                                      "VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\n"
                                      "DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\n"
                                      "ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\n"
                                      "VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\n"
                                      "mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\n"
                                      "IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\n"
                                      "mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\n"
                                      "XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\n"
                                      "dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\n"
                                      "jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\n"
                                      "BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\n"
                                      "DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n"
                                      "9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\n"
                                      "jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\n"
                                      "Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\n"
                                      "ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\n"
                                      "R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n"
                                      "-----END CERTIFICATE-----\n";

    void setup() {

      Serial.begin(115200);

      // Connect to the WiFI
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      Serial.println("");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

      //--------

      // Checking the cert is the best way on an ESP32
      // This will verify the server is trusted.
      client.setCACert(server_cert);

      // If you don't want to verify the server
      // Unlike the fingerprint method of the ESP8266 which expires frequently
      // the cert lasts years, so I don't see much reason to ever
      // use this on the ESP32
      // client.setInsecure();

      makeHTTPRequest();
    }

    void makeHTTPRequest() {
      delay(5000);
      // Opening connection to server (Use 80 as port if HTTP)
      if (!client.connect(TEST_HOST, 443))
      {
        Serial.println(F("Connection failed"));
        return;
      }

      // give the esp a breather
      yield();
      client.connect(TEST_HOST, 443);
      // Send HTTP request
      client.print(F("GET "));
      // This is the second half of a request (everything that comes after the base URL)
      client.print(""); // , == ,
      client.println(F(" HTTP/1.1"));

      //Headers
      client.print(F("Host: "));
      client.println(TEST_HOST);

      client.println(F("Cache-Control: no-cache"));

      if (client.println() == 0)
      {
        Serial.println(F("Failed to send request"));
        return;
      }
      //delay(100);
      // Check HTTP status
      char status[32] = {0};
      client.readBytesUntil('\r', status, sizeof(status));
      if (strcmp(status, "HTTP/1.1 200 OK") != 0)
      {
        Serial.print(F("Unexpected response: "));
        Serial.println(status);
        return;
      }

      // Skip HTTP headers
      char endOfHeaders[] = "\r\n\r\n";
      if (!client.find(endOfHeaders))
      {
        Serial.println(F("Invalid response"));
        return;
      }

      // This is probably not needed for most, but I had issues
      // with the Tindie api where sometimes there were random
      // characters coming back before the body of the response.
      // This will cause no hard to leave it in
      // peek() will look at the character, but not take it off the queue
      while (client.available() && client.peek() != '{')
      {
        char c = 0;
        client.readBytes(&c, 1);
        Serial.print(c);
        Serial.println("BAD");
      }

      // While the client is still availble read each
      // byte and print to the serial monitor
      while (client.available()) {
        char c = 0;
        client.readBytes(&c, 1);
        Serial.print(c);
      }
    }

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

    }

the program was able to compile, and was able to run until it shows it connect to the network. But then it returned "Connection failed!" I believe it stuck at this line :

    if (!client.connect(TEST_HOST, 443))

I am not sure what is the problem here. Comments appreciated.

body:
Things wrong with your GET request (which are nothing to do with Arduino - just learn the basics of the protocol you are trying to use *before* you use it):

* You are trying to open a socket to a URL not to a server. That can never work. Connect to the server instead (hint: the server, or "FQDN", is the bit between the `https://` and the next `/`).
* You aren't providing any path in your `GET` request, only a comment that says what you should provide.  Hint: the path is everything that comes after (and including) the `/` following the FQDN.
* Your `Host:` header should contain just the FQDN, not the whole URL. By now you should know what the FQDN is.
* You should also include `Connection: close` in your headers to inform the server you won't be keeping the socket open.

Correct those problems and you might begin to see something useful happening.


message:
I am in need of a usable communication library on 1-4 pins of ATTiny84 instead of I2C

I messed up when designing my PCB and just assumed that I could use software slave I2C with ATTiny84.

The reason I did so is - I needed to use all of the analog inputs.

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

The pins I have on my connector are:

PB0 (pin 2), PB1 (pin 3), PB2 (pin 5) and PA0 (pin 13)

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

Is there an alternative to I2C or a different communication protocol I could use to connect multiple of these slave boards to a master (ATMEGA328 etc.)?

Thanks a lot, I can provide any further information.

body:
That is a lot of pins, so this really boils down to your application and what you want to optimize for.

You could do a bit-banged software I2C slave on these pins. "Bit-bang" means you just write a program to flip the bits on the pins rather than handing the bytes off to the hardware which would do the same thing (although sometimes faster or without using up CPU cycles). This would require either finding some existing code to implement the protocol, or sitting down with the documentation for the protocol and writing it yourself. Depending on your goals, the second option might be a great learning experience and take away some of the magic from this stuff. It is all just 1s and 0s and once you really internalize that, you realize that you can do almost anything with these little chips regardless of hardware or library support.


message:
consecutive analogRead()

Has anyone noticed that if calling `analogRead()` in a consecutive way that the value drops by a bit as opposed to just doing a single read?

And is this to be expected?

I am using a Seeeduino XIAO.

body:
You need a short delay between analog reads due to the time it takes to complete a reliable ADC reading. In depth technical explanations can be found [here][1], note that it refers to AVR architecture.

  [1]: https://www.quora.com/Why-is-a-little-delay-needed-after-analogRead-in-Arduino


message:
Replace CH340 With FTDI

I have built a arduino midi octapad with a Clone of arduino nano that contain a ch340 chip but hairless midi says FTDI driver doesn't installed i installed that driver but it still show that error so can i replace the ch340 chip with a FTDI chip to resolve this Problem... ?

body:
When you search for "FTDI" in one of the hairless-midiserial repos on github (I looked at [this][1] and [this one][2]), you find what looks like your error message (though you didn't actually put it in your question:

    ./src/PortLatency_win32.cpp:        emit debugMessage("FTDI drivers don't seem to be installed. Not attempting any FTDI latency tricks.");

Also the repos have a class in PortLatency.h with the description:

    A simple class to manage latency reduction of FTDI-based serial ports.

This gives us some information:

- The message above is not an error message, but a debug message. It might work despite not having an FTDI
- The class description suggests, that the program wants to use some tricks to reduce the latency in the communication. These tricks seem to be FTDI specific. When the above debug message appears, these tricks are not used. Thus your performance may be significantly worse than with an FTDI chip. Also one of the repos has an [open issue][3] about problems with the CH340, which states, that it just doesn't work correctly. It was updated in May and still has no solution. I would not bet on getting help there. (Also the ground repo, that the other was forked off, wasn't updated since 5 years.)
- You cannot fix that debug message by installing the FTDI drivers, because you don't use an FTDI chip.

As we are on Arduino SE here, we cannot really help you with that program running on your PC.

Of course you can use an extra FTDI chip/board and connect it to the RX and TX lines of the Arduino (not using the CH340 USB serial chip on the Arduino itself). But I support Majenkos comment about just migrating to an Arduino with native USB connection (means the USB communication is done by the Arduinos microcontroller directly, not by an extra chip) (for example the Micro, but there are a lot more Arduinos with native USB). That enables you to manipulate the type of USB connection, thus you can let the Arduino directly appear and work as an USB midi device. Then you don't need the hairless-midiserial program anymore.

  [1]: https://github.com/rhargreaves/hairless-midiserial
  [2]: https://github.com/projectgus/hairless-midiserial
  [3]: https://github.com/projectgus/hairless-midiserial/issues/68


message:
RaspberryPi Pico SPI and nrf24l01

I am programming a RaspberryPi Pico with the Arduino IDE. Works pretty well, but now I try to control an nrf24l01 module.

My code compiles but I do not know on which pins the SPI bus has to be hocked up. I tried to connect to different pins according the pinout
https://datasheets.raspberrypi.org/pico/Pico-R3-A4-Pinout.pdf
(for example 2 sck, 3 miso, 4 mosi), but nothing worked so far.

Does anybody know what the default pins are or how to control them? I also would like to control other SPI hardware, for example a display.

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const uint64_t address = 0x1;
byte sendData[1];

#define CSN_PIN  5
#define CE_PIN   6
RF24 radio(CE_PIN, CSN_PIN);

byte counter = 0;

void setup()
{
  Serial.begin(115200);
  Serial.println(“radio starting");

  if (!radio.begin())
  {
    Serial.println("radio hardware is not responding!!");
    while (1) {}
  }
  radio.openWritingPipe(address);
}

void loop()
{
  Serial.print("Counter: ");
  Serial.println(counter);

  sendData[0] = counter;

  radio.write( sendData, sizeof(sendData));

  counter++;
}
```

body:
1. For Arduino-pico core

   ** MISO - pin GP16

   ** MOSI - pin GP19

   ** CS   - pin GP17

   ** SCK  - pin GP18

2. Arduino-mbed core

   ** MISO - pin GP4

   ** MOSI - pin GP3

   ** CS   - pin GP5

   ** SCK  - pin GP2


message:
How do I make another action repeat inside a loop?

*So, I've just started programming Arduino (and also in general), so I'm doing basic things, like switching on and off LED's.*

I've made them light in a sequence and then turning them off (in the same sequence), and now I wanted to use 2 buttons, one to make them do the same thing as before (light and turning LED's off in sequence) repeatedly, and the other to turn them off.

The problem is that curently they only light up once, and not repeatedly, I think I would've needed another loop, but i found out that you can't use 2 of them.

Can anyone help me? here's the code

    int LED1 = 2;
    int LED2 = 3;
    int LED3 = 4;
    int LED4 = 5;
    int LED5 = 6;
    int buttonON = 7;
    int buttonOFF = 8;

    void setup()
    {
      pinMode(LED1, OUTPUT);
      pinMode(LED2, OUTPUT);
      pinMode(LED3, OUTPUT);
      pinMode(LED4, OUTPUT);
      pinMode(LED5, OUTPUT);
      pinMode(buttonON, INPUT_PULLUP);
      pinMode(buttonOFF, INPUT_PULLUP);
    }

    void loop ()
    {
      if (digitalRead(buttonON)== LOW)
      {
        delay(300), digitalWrite(LED1, HIGH);
        delay(50), digitalWrite(LED2, HIGH);
        delay(50), digitalWrite(LED3, HIGH);
        delay(50), digitalWrite(LED4, HIGH);
        delay(50), digitalWrite(LED5, HIGH);
        delay(300), digitalWrite(LED1, LOW);
        delay(100), digitalWrite(LED2, LOW);
        delay(100), digitalWrite(LED3, LOW);
        delay(100), digitalWrite(LED4, LOW);
        delay(100), digitalWrite(LED5, LOW);
      }
     if (digitalRead(buttonOFF)== LOW)
     {
      digitalWrite(LED1, LOW);
      digitalWrite(LED2, LOW);
      digitalWrite(LED3, LOW);
      digitalWrite(LED4, LOW);
      digitalWrite(LED5, LOW);
     }
    }

P.S. if anyone has other general tips I would really apreciate them

body:
You simply need to save the state of the LEDs in a new variable ...

    void loop ()
    {
      if (digitalRead(buttonON)== LOW)
          ledEffectON = true;

      if (digitalRead(buttonOFF)== LOW)
          ledEffectON = false;

      if(ledEffectON)
      {
        delay(300), digitalWrite(LED1, HIGH);
        delay(50), digitalWrite(LED2, HIGH);
        delay(50), digitalWrite(LED3, HIGH);
        delay(50), digitalWrite(LED4, HIGH);
        delay(50), digitalWrite(LED5, HIGH);
        delay(300), digitalWrite(LED1, LOW);
        delay(100), digitalWrite(LED2, LOW);
        delay(100), digitalWrite(LED3, LOW);
        delay(100), digitalWrite(LED4, LOW);
        delay(100), digitalWrite(LED5, LOW);
      }
    }


body:
By using `delay()` it blocks the rest of the code. The programme needs to keep track of two buttons and update the lightshow at appropriate times, therefore a non-blocking style of coding is needed similar to the [Blink Without Delay example][1] where the `delay()` is replaced with a timer using `millis()` that is checked periodically. This allows other things to be checked periodically as well, e.g. the buttons.

Also the button contacts tend to bounce several times for several milliseconds when they change state sending a train of on/off pulses to the MCU, so they need to be debounced. You can find many debouncing algorithms online, but here's a [simple debouncer][2] that I put on GitHub.

```cpp
void loop ()
{
  static bool doLightshow = false;

  static Debouncer buttonOn(buttonON);
  static Debouncer buttonOff(buttonOFF);

  buttonOn.Update();
  buttonOff.Update();

  if (buttonOn.Fall())
  {
    Serial.println("buttonOn falling edge.");
    doLightshow = true;
  }
  else if (buttonOff.Fall())
  {
    Serial.println("buttonOff falling edge.");
    doLightshow = false;
  }

  if (doLightshow)
  {
    // Do lightshow.
    . . .
  }
  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, LOW);
    digitalWrite(LED4, LOW);
    digitalWrite(LED5, LOW);
  }
}
```

Due to the way you've neatly written your code, you can probably pick out a pattern in the lightshow.

| State | Delay time | LED pin | LED state |
| :---: | :---:      | :---:   | :---:     |
| 0     |   300      | LED1    | HIGH      |
| 1     |    50      | LED2    | HIGH      |
| 2     |    50      | LED3    | HIGH      |
| 3     |    50      | LED4    | HIGH      |
| 4     |    50      | LED5    | HIGH      |
| 5     |   300      | LED1    | LOW       |
| 6     |   100      | LED2    | LOW       |
| 7     |   100      | LED3    | LOW       |
| 8     |   100      | LED4    | LOW       |
| 9     |   100      | LED5    | LOW       |

This lends itself well to creating a Finite State Machine that can be stored in an array of structures:

```cpp
typedef struct LightshowData
{
  unsigned int delayTime;
  byte ledPin;
  bool ledState;
};

const byte numStates = 10;

const LightshowData lightshowData[numStates] =
{
  { 300, LED1, HIGH },
  {  50, LED2, HIGH },
  {  50, LED3, HIGH },
  {  50, LED4, HIGH },
  {  50, LED5, HIGH },
  { 300, LED1, LOW },
  { 100, LED2, LOW },
  { 100, LED3, LOW },
  { 100, LED4, LOW },
  { 100, LED5, LOW }
};
```

The state machine can now cycle through the array in a non-blocking manner:

```cpp
    // Do lightshow.
    static byte state = 0;
    unsigned long currentTimestamp = millis();
    static unsigned long previousTimestamp = currentTimestamp;

    if (currentTimestamp - previousTimestamp >= lightshowData[state].delayTime)
    {
      previousTimestamp += lightshowData[state].delayTime;
      digitalWrite(lightshowData[state].ledPin, lightshowData[state].ledState);
      state = ++state % numStates;
      Serial.print("state = ");
      Serial.println(state);
    }
```

You may want to reset `state` to 0 after a negative edge on `buttonOff`, otherwise the lightshow will continue where it left off after being stopped and restarted.

Here's the Wokwi simulation of the lightshow with 250 Ω protection resistors for the LEDs.

[Wokwi simulates button bounce by default][3] to more accurately model the real world, so it's advisable to have some form of button debouncing.

  [1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay/
  [2]: https://github.com/TimMathias/Arduino-Debouncer
  [3]: https://docs.wokwi.com/parts/wokwi-pushbutton#bouncing


body:
You have written your question beautifully.
In your case, according to your logic, the button has to be kept pressed, so that the LEDs are lit in the order you desire. The single loop() function is part of the Arduino sketch but it is never a limitation.

One way to solve your problem is to make the LED drive logic independent of the button press state.

 - Once you detect the button press, store the event in one variable.
 - Let us call it `ButtonStatus`.
 - So, soon after the keypress is detected, update the `ButtonStatus` variable to TRUE.
 - Your LED drive logic can check this variable value to decide whether to drive the LEDs or not
 - Soon after you detect another press of the second button, you can update the variable value to FALSE.
Here is the Arduino simulation output for your code and the code suggested by @cat

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

below is after adapting the solution from cat
[![enter image description here][2]][2]

The simulation links are here:
[Original problem][3]
[solution 1][4]
```
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int buttonON = 7;
int buttonOFF = 8;
int ledEffectON;
void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(buttonON, INPUT_PULLUP);
  pinMode(buttonOFF, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(buttonON)== LOW)
      ledEffectON = true;

  if (digitalRead(buttonOFF)== LOW)
      ledEffectON = false;

  if(ledEffectON)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
}
```
Link to docs on [Pushbuttons][5]. Wokwi Arduino simulator simulates debounce by default - just like real-world switched. Debounce is a very important technique that you should consider adding to the code. To disable the "bounce" option, use the below trick!

    { "bounce": "0" }

  [1]: https://i.stack.imgur.com/DOZms.gif
  [2]: https://i.stack.imgur.com/XvLyY.gif
  [3]: https://wokwi.com/arduino/projects/304627808095699521
  [4]: https://wokwi.com/arduino/projects/304626706673566272
  [5]: https://docs.wokwi.com/parts/wokwi-pushbutton


message:
Can bool variable be NULL

I want to know if bool variable can be null, or it must have to be true or false:

Base on Arduino description:
A bool holds one of two values, true or false. (Each bool variable occupies one byte of memory.)

body:
A bool is literally that - a boolean value. So either 1 or 0 - true or false.

In C only pointers can be NULL. Every other primitive type is a value, and NULL is not a value.


body:
A `bool` value must be either `0` or `1`, or `false` and `true` respectively. It is [*undefined behavior*](https://stackoverflow.com/questions/54120862/does-the-c-standard-allow-for-an-uninitialized-bool-to-crash-a-program) for it to be any other value. When assigning a value to a `bool`, the compiler will automatically force it to be 0 if it is already 0, or 1 if it is not.

However, as it is a full byte, it is possible to store another value. As mentioned before, however, this is undefined behavior. This means that if it ever happens, or will absolutely happen, the program can do *anything*: for example, crash the program, output random data, or act like it's truthy, falsy, or both! In fact, that *can* (again, no guarantees) happen if you store the value 2:

```cpp
#include <cstdio>

int main() {
    union b_c {
        unsigned char c;
        bool b;
    };
    b_c c;
    c.c = 2;

    if(c.b) puts("true!");
    if(!c.b) puts("false!");
}
```

(this is designed to run on a computer, but the same thing could happen on an Arduino). [Check out what happens](https://cpp.godbolt.org/z/eM14v7srM) when you run it: it outputs both `true!` and `false!`! This obviously doesn't make sense, but because we violate the rules by making a `bool` `2`, we loose all guarantees.

---

So, how is this relevant to your question? There's no valid value a `bool` can store other than `true` and `false`. In C++, `null` is defined as "an integer literal with value zero". So, if you were to assign `null` to a `bool`, it would be stored as false. If you want a separate null value, you're better off using another type that takes up a single byte (e.g. `unsigned char` or `uint8_t`, same thing) and storing e.g. `0` for `false`, `1` for `true`, and `2` for null.


message:
how to write a program in Arduino that pairs a single Rx to multiple Tx modules? i want to learn implementing this protocol

I have two Attiny85 communicating over 433mhz radio (Rx & Tx on either ends) using virtual wire library, how will the programming be to pair them by the press of a button on either module ?
i have so far been able to pair them both through the program (exclude any external devices by giving a node ID to listen to in my Rx) or think of adding DIP switches (but i run out of pins & combinations sooner). I am expecting  something similar to a commercial product where i can connect/pair multiple Tx modules to a single Rx base station in a press of a button on the Tx side. so i am seeking some technical expertise on the idea to understand such programming technique/methods.

Regardless of using 433mhz or a NRF24L01 module or anything else, i want to know how this feature of pairing module together is made.

*------*
Edit 22 July 2021:
This is added here in response from Crisl's comment

you have correctly understood my question, yes i want to learn how such a pairing protocol is implemented, i am not too concerned about the device for the communication gateway.

this question is regarding the protocol, and not about a specific circuit

*------*
I am a mechanical engineer by profession, with a hobby towards programming & electronics, so kindly spare some patience/detail in explaining this concept/technique.

body:
If it is sufficient to distinguish between the two (or several) transmitters and you don't need to exclude intrusions, accidental or otherwise, a "protocol" can be as simple as:

XMTRID BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]

, where each of the above represents a single byte. Does the library include message integrity checking, such as a checksum? If not, and the physical conditions warrant, you might add that to your protocol as well, and include an expectation by the transmitter that it receives an acknowledgement or rejection of correct reception (ACK or NAK) within a short time and will re-transmits the same message if it hasn't received an ACK. Then you'll want a message ID byte that increments for each new message (but not for retramsmission), so the receiver can reject a retransmission (if, say, its attempt to acknowledge had been lost).

Then your protocol could look something like this:

XMTRID MSGID CHKSUM BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]

. and it just keeps getting better from there as you add features for robustness, security, and whatever else you might need it to accomplish. But I'm guessing this is already sufficient.

Update:
To clarify:

    XMTRID    - ID of sending 433MHz radio (any value you like, as long as each device has its own).
    MSGID     - An incrementing number (rollover allowed), a new one for each *new* message
                (enables the receiver to distinguish new messages from resent ones).
    CHKSUM    - A sum of bytes in the message to let the receiver check the message integrity.
    BYTECOUNT - The number of message bytes to follow.
    BYTE[0] ... BYTE[BYTECOUNT-1] - The actual message data.


message:
Using Arduino LMIC library with EnableInterrupt

I am using the [EnableInterrupt][1] library, infact the only library that I can find that allows me to use six interrupts to wake the Arduino. However when I use it with the [LMIC][2] library (Matthijs Kooijman ) the "Forward uplink data message" is not sent during initial registration, only if
#include <EnableInterrupt.h> is commented out does it work. I am using a RFM95 with the following LMIC pin assignments:

const lmic_pinmap lmic_pins = {
    .nss = 10,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 9,
    .dio = {3, 8, LMIC_UNUSED_PIN},
};

This must be something to do with the library sharing ISRs.  Could somebody point to which parts of the LMIC library so as not to have this conflict?

I have tried swapping 8 for A5 and it again only works when the line is commented. Any help would be greatly appreciated.

  [1]: https://github.com/GreyGnome/EnableInterrupt/
  [2]: https://github.com/mcci-catena/arduino-lmic

body:
This is the best I can get to work with 6 available pin change interrupts - just enough!

    #define EI_ARDUINO_INTERRUPTED_PIN
    #define EI_NOTPORTB  // DISABLE FOR LMIC
    #define EI_NOTPORTD  // DISABLE FOR LMIC


message:
How to control Shift registers output individually bitwise

so i am working on a project which needs a lots of bit manipulation and shifting out the bits to control the pins of shift registers individually.

So i am using 2 shift registers daisy chained with 16 LEDS. Now, what i want is that, i want to control the LEDs individually just by shifting out the bits

here is what i tried

first Attempt

    int latchPin = 4; // Latch pin of 74HC595 is connected to Digital pin 5
    int clockPin = 5; // Clock pin of 74HC595 is connected to Digital pin 6
    int dataPin = 3; // Data pin of 74HC595 is connected to Digital pin 4

    byte leds=0b1000000000000001; // byte has 16 bits

    void setup()
    {

      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
    }

    void loop()
    {

      updateShiftRegister();

    }

    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);

       shiftOut(dataPin, clockPin, LSBFIRST, leds);
       digitalWrite(latchPin, HIGH);
    }

Does not work! the 2nd shift register seems to be copying the first shift register which i don't want

In second attempt, i tried the masking method with HEX data type.
Here is it.

    int latchPin = 4; // Latch pin of 74HC595 is connected to Digital pin 5
    int clockPin = 5; // Clock pin of 74HC595 is connected to Digital pin 6
    int dataPin = 3; // Data pin of 74HC595 is connected to Digital pin 4

    byte leds=0xFFFF & 0x8001; // used hex masking method

    // 0xFFFF = 1111111111111111
    // 0x8001 = 1000000000000001
    // After & it should be 1000000000000001

    void setup()
    {

      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
    }

    void loop()
    {

      updateShiftRegister();

    }

    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);

       shiftOut(dataPin, clockPin, LSBFIRST, leds);
       digitalWrite(latchPin, HIGH);
    }

This too makes same effect like the attempt 1 above.

Now here is what i want and need...

    byte leds = 0b1000000000000001

    /* As you can see the index 0 and index 15 of the byte led
      is set 1 or high which should produce +ve to the 15th pin of first register and 8th pin of second register.

but whenever i try this, it seems that one of the register is copying another one.

So, is there any way to shift out bits to control the shift register outputs individually?

if yes then please give a clear example code with a clear explanation.

if no then, please suggest me some alternative ways which can be used in the same way i want , of course with example code and explanation.

Schematic: [arduino.cc/en/Tutorial/Foundations/ShiftOut][1]

Thank You so much for your precious time.

Looking forward to your replies .

:)

  [1]: http://arduino.cc/en/Tutorial/Foundations/ShiftOut

body:
The function `shiftOut()` only works for 8-bit values, as its documentation says.

Additionally, a `byte` can only store 8 bits. It doesn't matter how many bits you try to assign. (The compiler should have given you a warning, but the IDE likes to hide this.)

You need to write your own output function to shift out 16 bits, AFAIK.


body:
You have two problems with your code:

- `byte` is equal to `unsigned char` and can only hold exactly one byte, aka 8 bits (not 16 bits like your comment says). But you are trying to assign a 16bit number to it. The upper 8 bits are cut out in that process. They are lost. If you want to hold a 16bit number, you need to use a data type, that is at least 16 bits in its size, for example `uint16_t` (or you can use `unsigned int`, though in such situations it is often better to use a type, which has the same size on all platforms).

        uint16_t leds = 0b1000000000000001;

- The `shiftOut()` function has this declaration in wiring_shift.c:

        void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)

    You can see, that `val` (which is the data, that should be shifted out) is of type `uint8_t`, the same as `byte`, which also can only hold 8 bits. The upper 8 bits of a 16bit value would be cut off and the function also just transmits 8 bits, nothing more (When you look at its implemention in the mentioned file, you will see a for loop with 8 as limit).

    Instead you should call that function for every byte, that you want to transmit in a single transmission; 2 times in your case  because you have 2 shift registers.

So the resulting program would look something like this:

    int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
    int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
    int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

    uint16_t leds=0b1000000000000001; // uint16_t has 16 bits

    void setup()
    {

      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
    }

    void loop()
    {

      updateShiftRegister();

    }

    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);

       // Shiftout lower byte by masking the other byte with bitwise AND (&)
       shiftOut(dataPin, clockPin, LSBFIRST, leds & 0xFF);
       // Shiftout higher byte by shifting the bit pattern 8 bits to the right
       // resulting in the high byte getting to the position of the low byte
       // and then masking away anything else than the new position of the high
       // byte data
       shiftOut(dataPin, clockPin, LSBFIRST, (leds >> 8) & 0xFF);
       digitalWrite(latchPin, HIGH);
    }

Note, that the masking with the bitwise AND operator is not really necessary here, but I like to do such things explicitly to make it more clear.

---

> So I need to store almost 50 bits in the variable to control the columns so can 'uint' method be useful in this case ?

In that case I would use a byte array to hold the data. With 50 bits you are at 6.25 or 7 bytes (since you cannot have sub bytes). The declaration would be something like this:

    byte leds[] = {0b00011001, ... }; // list the byte data here

And then you can shift that out with a for loop:

    void updateShiftRegister()
    {
       digitalWrite(latchPin, LOW);
       for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
           shiftOut(dataPin, clockPin, LSBFIRST, leds[i]);
       }
       digitalWrite(latchPin, HIGH);
    }

Note that `sizeof(leds)` will return the size of the `leds` array in bytes. I also divided through the size of a single element of the array to get the number of elements in the array instead of bytes. In this case this is the same, but since datatypes might change while the code progresses it is better to be save than sorry.

> i tried the masking method with HEX data type.

The data, that comes out is the same. The Arduino only knows of binary data. It doesn't know of different representions (like binary, HEX or decimal). The compiler will already convert that to the target value. So for the Arduino both ways are equivalent.


message:
Arduino and fingerprint scanner - can I get the fingerprint scanner data?

I am currently planning a thesis that involve scanning fingerprints and storing the data in a database. The problem is that I do not know if it is possible for me/us to get the fingerprint data or variables scanned by the fingerprint scanner.

I tried searching on google, of course, but I don't see any information on how to display the data in a form such as binary.  I'm not sure if I can extract the data from the Arduino then store it in a website/database (---which to be fair, since fingerprints can be confidential, I understand if some articles don't provide a sample.)

Is it possible to get and extract the fingerprint scan data? For example, converting the scanned data in to a binary representation (011010101 etc.)

body:
Echoing my comment on SO with more information:

Commercial fingerprint sensors like [this one][1] do local store and compare and do not expose the actual image or binary signature. What they transmit to the microcontroller are ID's and match success.

If you need the binary data of the image itself you may be able to write your own image processing algorithm, perhaps using machine learning, and use a simple video camera connected to a microcontroller that in turn will send the captured image to your web server for processing.

Arduino can be programmed to capture still images and transfer a bitmap file to a server, such devices (microcontroller and cameras) are widely available.

  [1]: https://www.aliexpress.com/item/32847055230.html


body:
There is a discussion thread on [Quora][1] discussing finger print scanners that provide raw output. The Quora author recommends a  [Futronic][2] device which comes with an API for raw image collection. They also discussed [NeuroTechnology][3] which apparently also has a downloadable image database. Looking at the neurotechnology website they also have some interesting SDK options. These of course all give you an image not the binary output you described.

It strikes me that a binary encoded output would likely be the result of a recognition algorithm, or a resultant / generated security key. Not sure that is what you intended by your question?

There are a [mass][4] of academic papers on open finger print scanning algorithms.

I did a bit of google searching for people capturing raw data from Arduino compatible devices. Didn’t find anyone saying it was easy. Please post back here if you make progress.

Hope this helps get you started.

  [1]: https://www.quora.com/Are-there-any-fingerprint-scanners-that-provide-raw-images-as-output
  [2]: https://www.futronic-tech.com/pro-detail.php?pro_id=1535
  [3]: https://www.neurotechnology.com/verifinger.html
  [4]: https://scholar.google.com.au/scholar?hl=en&as_sdt=0,5&q=open fingerprint scanning algorithm&btnG=


body:
I'm a software engineer that works with biometric sensors. The answer is, it will vary **greatly** depending on the scanner you've chosen. Some hardware solutions have built-in subject enrollment and database matching; some simply collect an image and return it in an appropriate format- sometimes an image file (e.g. PNG), or a template file (a binary representation of a subject and/or their fingerprint(s)).

For you, I **highly** recommend avoiding the pain of interfacing with an Arduino at such a low level, and use a Raspberry Pi or other full computer to write a collection program with your vendor's SDK. Linux is supported by all the major players I've worked with, and that will drastically ease integration with whatever database or website you have in mind. Many vendors have built-in enrollment, storage, and matching examples as part of their SDKs that will help you get up and going in short order

**EDIT**: As this is an Arduino SE, I realize **I should give a microcontroller-friendly answer as well**. There are indeed [scanners like this][1]. It does templating and matching on board if I understand correctly, and the provided library does indeed allow you to transfer those templates over serial. Granted, you still have to get that data from your Arduino to a computer of some sort, so I still think a Pi is the shorter putt ;)

  [1]: https://www.adafruit.com/product/4690


message:
As a novice, how do I program my Atmega328p?

I bought a board which the above MCU is the atmega328p. Since I haven't used atmel MCU before, now it's a bit confusing. Are the ATMEGA and STM32 programmers not universal? What programming methods can this chip support? Is there serial programming or SWD programming? Need help. Many thanks!

body:
> **Are the ATMEGA and STM32 programmers not universal?**

They are not the same. As far as I know their programming arrangements are completely distinct.

> **What programming methods can this chip support?**

- Traditional AVR In-Circuit-Serial-Programming ([ICSP](https://en.wikipedia.org/wiki/In-system_programming)) using a 2x3 header pin connector and one of a variety of programmers such as the STK500 which has low-cost clones like the [Pololu AVR programmer](https://www.pololu.com/product/1300) (less than $10). These programmers typically connect to a PC's USB port and can be used either with the software development tools from Atmel (now Microchip) or using the Arduino integrated development environment (IDE) which uses a program named avrdude to communicate with the ATMega328P (or other AVR family MCUs). ICSP is sometimes called In System Programming (ISP). It uses the MCU's [SPI](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface) interface and you have to be careful what other circuitry is attached to those pins when you program the device.

- Serial-port programming by communicating with a pre-loaded "bootloader" program installed in the ATMega328P. This is the normal way to use the Arduino IDE but it depends on having that bootloader installed. Most bare ATMega328Ps are sold without this bootloader installed. All "Arduino" boards will have a bootloader installed in their MCU and many will have a serial-to-USB interface on-board so that the board can be plugged in to a PC directly. Otherwise you would need a USB-to-Serial interface like the [Adafruit FTDI friend](https://learn.adafruit.com/ftdi-friend) or many others.

There is also a [high-voltage programming](https://microchipsupport.force.com/s/article/How-to-perform-High-Voltage-Programming-on-AVR-devices) method but that isn't something a novice would need to use. I believe it is most often needed when you have configured the MCU in such a way that the above methods cannot be used. For example after having disabled the reset pin so it can be used as an IO pin that can be pulled to GND without resetting the MCU.

You can use an Arduino to emulate a programmer and use that to program boards that lack a USB serial interface. This is called [Arduino as ISP](https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoISP)

Microchip's newer generation of AVR MCUs use a different programming method than ICSP called [UPDI](http://www.technoblogy.com/show?2OJT).


body:
> What programming methods can this chip support? Is there serial programming or SWD programming?

The Arduino IDE (a free download) supports programming in C++. The IDE pre-processes your code (which they call a "sketch") slightly but it is still C++.

You can drop into assembler if you absolutely must, but the C++ compiler does a good job of producing efficient code, almost always.

With the assistance of a serial interface (many Arduinos, like the Uno, have one built-in connected to a USB interface) you can quickly and easily upload your code. The wherewithal to do that is built into the IDE.


message:
How to read wireless doorbell's indicator LED circuit

I have a cheap wireless doorbell. My plan is to include an ESP8266 and power the doorbell from the microcontroller 3.3V output as the doorbell also runs on 3V

I specifically chose a model with a LED, as I thought it should be easy to use the LED as a trigger on the ESP8266 and consume as a digital input.

I've soldered two wires from the LED positive and negative solder points. What I find strange is that I measure 3V between the PCB ground and the positive LED wire when the doorbell is not triggered. If I measure between the negative LED wire and positive LED wire, I see a voltage spike corresponding to each LED flash (it flashes 5 times). I plan to debounce this in software.

I did not expect to measure a voltage when the doorbell is not triggered between the positive LED wire and the PCB ground, and this will definitely not work as I intended.

*Disclaimer: I'm not an electronic engineer, and my test equipment consists of a multimeter.*

I've included a photo of the PCB. It is labelled "QH-823A-19" but searching for this on the Internet has provided no usable information.

What have I tried?
1. I've tried to trace the tracks running to the LED solder points, but the tracks run under some components which makes this hard
2. I've tried to measure different points on the board for a positive 3V spike when the LED flashes, no success

Any advice on how to achieve this? Am I going about this the wrong way?

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

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

body:
Your LED is connected between V+ and the GPIO of the microcontroller. This is a common arrangement because historically microcontrollers have been able to sink more current than they can source. It's also easier to make a "low side" constant current source, which this custom chip may have, to reduce the number of external components needed.

To read the state you need to take the voltage at the cathode of the LED referenced to the ground of the doorbell circuit. This will give you a voltage at or near the board supply voltage when the LED is off, and a lower voltage (near zero but probably not zero) when the LED is on.

If the voltages are within the threshold voltages VIH and VIL of the ESP8266 then you can just directly read that level as a logic level. If not then you may need to "condition" the voltage to give proper logic levels.

For example you could use a comparator (an op-amp running in "saturated" mode) to compare that voltage to a single threshold voltage that is roughly half way between the HIGH and LOW voltages. That would then swing the output between the supply and ground voltage levels giving you a much cleaner signal.

Or you may use an analog input (the ESP8266 only has one, and that is quite a crude one with only 1.1V maximum allowed on it, so a voltage divider will be needed) to measure the voltage and do the comparison in software.

Another option would be to remove the LED completely and replace it with an optocoupler, thus making the LED itself an electronically operated button to the ESP8266. This will also keep the ESP8266 ganvalically isolated from  the doorbell.


body:
# Schmitt Trigger using a Comparator

If you follow @Majenko's advice of using a comparator, you could add some hysteresis to it with a few resistors to create an inverting [Schmitt trigger][1]. This will increase the noise immunity and thus reduce the noise going to the ESP8266. The following simulation has a noisy input transformed into square pulses. It also performs a small level shift from an input of 3 V to an output of 3.3 V.

<a href="https://www.falstad.com/circuit/circuitjs.html?ctz=CQAgjCAMB0l3BWcMBMcUHYMGZIA4UA2ATmIxEMJCQUmoFMBaMMAKAEMRs0Q08QALN174Q-bNGxRk8OL2h5IGFhjyEEWQgISVwsUsSGRDGFAJTF+YWZFYB3QcL6OUvU1FYAnF29co8-JiudNbw9rwBvGZcPCjRtg7+gdFJvh6JkXECEVYC2bbeqWB5OWJ0IbJepUGl2NhUFWEA5rX1tYT85awA8j7OAooinR4ASqWDqQPSdAJ0ElLlUNAI4dwhxH7RYBseAG7ghOub2dvB4IIhekjly6xjYIfgO2D+T2cQoTfX07cADlEnHZZLhtRYJAEgqgoHSQ9K8GF1KGRREef7QqEpBGg6bhdEQ1LA2wAe3A2WEITixDmS3gEEuADUAJYAO1YJOIMWks0s1CWdPO9KJAFcAC5s0mcmYWOjXaAfXggDl0JnMgA6AGdduqNYLRawgA">

*Figure 1 – Schmitt trigger circuit.*

[![Schmitt trigger simulation waveforms][2]][2]

*Figure 2 – Schmitt trigger simulation.*

# Hysteresis versus Low-Pass Filtering

There is a subtle difference between hysteresis and low-pass filtering.

The following experimental circuit, Figure 3, demonstrates this difference with an interactive simulation where you can click on the switches to add/remove noise and add/remove filtering.

The low-pass filter has a cut-off frequency of 40 Hz.

I've set the high-going threshold, Vt+, to 2.31 V and the low-going threshold, Vt-, to 1.54 V. I calculated these figures from the [74HC14 datasheet][3] using the thresholds for 3 V at 25°C and scaling them for 3.3 V.

<a href="https://www.falstad.com/circuit/circuitjs.html?ctz=CQAgjCAMB0l3AmcMGIOxoMyQBwIGwCchaIArJOSACybkCmAtGGAFAAe5mOyS+CEMJDI1w1EAFkAwgFUAOgGcAxgEsATkoCuKgC5qAnqwBGIfJiSYypBNxA4RkDiEaEeQvshHiw4gCIB7fzUjegAbUMVVDW09QxM0fBBLHmYhO0THACUkpEJE8xoeSkpqSjpiqGgyVjB+HPB8MqRUHiQAE3oAMwBDTVCdRlD6NvAoMZhITFY1etqmkDyxoUcAd3rMTES5pM2oVjWChFL13dX6loXEi4RWTudakAQj8+eCsCrKyBu17Y2rnB4fz2awQAJ2+Rw4iBWXuV2ejGorWelCQx3eInR4yqrGyoJ4izxhXGNDK0HKWOqAHkaATcKY6RcII4AOYNMq7X74Ip7MA4Oi0Zp06i07kwDFVcQIMkQTBkvacagYsCEengJ6iMBITI3JRJSGPMHcKGnJLQHDEC2Wq1oJikd6EWoENBwagINCg1CkCaQNgHfUXAWPOmOT1B1oMumLcQANVCKgAdgBrG6ho1hvXiKMgaOdFT9ehqYasUPCq5CxZZ6P+TQ6aYG-H-cPc5aOGaE66Gk0txwKyCSzAqqwo10apBoagACSkPgANIpowM5ABHdHUaNzhQLuQAB2XUswYGjdfbdLTF0o3dYADdLuBCEhtsqkBeSSjiWL9umO03Hk4WIIyG8agANIbwkAAOX8FQFHoVgFAzdMzzBF8elCGCnBcOEREYNAVSeHgwOzBNWAAZS-OltnPUZUJgsZvlvC4CWRT8mO8RpHmYtYRVvJ89lDRZeIrRIYzjJM2E4HwRCOZpNUeRVRxASDoPoRQFBWXQlAACycA8pMRJI0FaMgIEIgAxPMdALVT1J0LTWH8cA6HwcQLyeB0kk+OAmUeRyPOjYiHJVZyljckpoAtXC3LIPBuDAcpYC8uiFj80TEzYByECClySVcKhvX4BwfMylKE2Teyg1MbLNUy0lFURLASCeah8HwIQXISn0ktQPzc3zQs2nKsARGC1yatNeL4G8iAqxrVggA">

*Figure 3 – Circuit showing difference between hysteresis and low-pass filtering.*

Hysteresis provides greater noise immunity and reshapes a slowly changing signal into a square wave ready for a digital input. But it can't filter out noise spikes that breach its threshold levels. These spikes would cause the Schmitt trigger to output square pulses. See the orange section of Figure 4.

Low-pass filtering filters out high frequency spikes which could breach the upper and lower thresholds of a Schmitt trigger. See the green section of Figure 4. Note that it also introduces a phase shift. If the noise were created by switch-bounce, then the low-pass filter would be performing debouncing. The blue section represents the ideal world where there is no noise, no need of filtering, and the output is in phase with the input.

[![Simulation of hysteresis versus filtering.][5]][5]

*Figure 4 – Simulation of hysteresis versus low-pass filtering.*

  [1]: https://en.wikipedia.org/wiki/Schmitt_trigger
  [2]: https://i.stack.imgur.com/iLE95.png
  [3]: https://www.onsemi.com/pdf/datasheet/mc74hc14a-d.pdf
  [4]: https://i.stack.imgur.com/vxEDh.png
  [5]: https://i.stack.imgur.com/BVBsd.png


message:
ESP32 and SQLite - ALTER TABLE problem

I'm using an ESP32 and SQLite3 from https://github.com/siara-cc/esp32_arduino_sqlite3_lib
Everything is OK except the ALTER TABLE command.
When I try

        ALTER TABLE TAB_JOUEUR RENAME TO TAB_NEW_JOUEUR

I get a "SQL logic error". I just see that the default source code will not compile with the ALTER TABLE option if SQLITE_OMIT_ALTERTABLE is defined.
So at the begining of the .c source, I added:

     #if defined(SQLITE_OMIT_ALTERTABLE)
       #undef SQLITE_OMIT_ALTERTABLE
    #endif

But result is the same.... Any idea?

body:
Well. After searching a lot here's the way todo a "RENAME" for a table. It's a bit tricky...
Renaming table in ESP SQLite is very interesting because SQLite has very limited features for editing table. So you can't add field, remove and so on. The only way is to create a new tmp table, copy the content of the orginal one into this tmp table, drop the original one and rename the tmp with the name of the new one.
DROP TABLE is OK with the ESP version of SQLite, but as said in the question, ALTER RENAME don't work.

So here is the way to do:

**1-What tables do we have?**

When we init the ESP, we call

      sqlite3_initialize();

and then we give SQLite the file it will use for saving data with a call to sqlite3_open() giving the name of a previously created file.

All our own tables will be saved into this file but also definitions of our tables. For that, SQLite create system table. So in the database we have our own tables but also the SQLlite system tables

**2 - The data base schema table**

One of the most important table is the database schema one. Its name depend on the version of SQLite. With the version we use on ESP8266 or ESP32, its name is *sqlite_master* .
This table has 4 fields:

 - type. Value can be  'table', 'index', 'view', or 'trigger'
 - name. Value is the name of the data. If type='table', name is the name of
   the table defined in this record
 - tbl_name. Name of the table. So if type='name', tbl_name = name
 - rootpage. An int which is the index in the Btree used by SQLite to
   access the data
 - sql. The code to create the table

**3-Check the schema**

To check the content of this specific table, just make a  CREATE TABLE then SELECT * FROM sqlite_master

Here is what I've done and the result:

The CREATE TABLE CALL:

*create TABLE    IF NOT EXISTS     TAB_JOUEUR ('tjoueur_id' INTEGER,"tjoueur_prenom" TEXT   , "tjoueur_nom" TEXT,   "tjoueur_ville" TEXT ,  PRIMARY KEY("tjoueur_id" AUTOINCREMENT))*

The result of the SELECT * FROM sqlite_master

 - type = table
 - name = TAB_JOUEUR
 - tbl_name = TAB_JOUEUR
 - rootpage = 2
 - sql    = CREATE TABLE TAB_JOUEUR ('tjoueur_id'
   INTEGER,"tjoueur_prenom" TEXT   , "tjoueur_nom" TEXT,"tjoueur_ville" TEXT ,  PRIMARY    KEY("tjoueur_id" AUTOINCREMENT))

and then

 - type = table
 - name = sqlite_sequence
 - tbl_name = sqlite_sequence
 - rootpage = 3
 - sql = CREATE TABLE sqlite_sequence(name,seq)

As you can see the sql field relative to the table "TAB_JOUEUR" as the CREATE call but it's not a pure copy of the original CREATE call. The original one as "create" in lower case, had extra spaces and has a "IF NOT EXISTS" which we don't have in the sql field of sqlite_master. But the part between the () is **exactly** the same (single quote for tjoueur_id, double for tjoueur_nom, extra spaces...)

**4 - The trick**

In order to rename a table, you just have to make a SELECT on sqlite_master in order to get the record of the table you want to rename. Then, change the content of the sql field to replace the "old name" by the "new one", and perform an update, using the rootpage as id.
So like that:

    void alter_table(String old_name, String new_name){

 int rc ;
 String data_rootpage;
 String data_sql;
 int pos_start;
 char *err_msg = 0;

 String query_sql = "SELECT rootpage,sql FROM sqlite_master WHERE type='table' AND name = '"+old_name+"'";

 const char* sql = query_sql.c_str();
 rc = sqlite3_prepare_v2(db_handle, sql, -1, &stmt, NULL);
 rc = sqlite3_step(stmt);
 data_rootpage = (const char *)sqlite3_column_text(stmt, 0);
 data_sql = (const char *)sqlite3_column_text(stmt, 1);

 // Find first ( in the string
 pos_start = data_sql.indexOf ('(');
 String tmp = "CREATE TABLE "+new_name+" "+data_sql.substring(pos_start);

 query_sql = "UPDATE sqlite_master SET sql='"+tmp+"', name='"+new_name+"', tbl_name='"+new_name+"' WHERE rootpage = "+data_rootpage;
 sql = query_sql.c_str();
 rc = sqlite3_exec(db_handle, sql, 0, 0, &err_msg);

    sqlite3_close(db_handle);
 sqlite3_initialize();
 sql_connect("/littlefs/transcom.db", &db_handle);}

It's basic and don't have test (you must add some!). I start by searching for the record concerning the "old_name" table. In the sql field I search for the "(" and then I replace the first part of the sql field data with the new name of the table.
Then I update. Notice I don't escape the quote because I've previously make a CREATE call without any ' or " (easier!)

After that, I perform a sqlite3_close() then re-open with sqlite3_initialize(); If you don't do that, SQLite don't take change in account (maybe there is a cache for data).

**5 - Great but... not enought!**

If you try this, you'll get an error on the update call. That's because for you, "user", sqlite_master is a read only table. So you can't update it. In order to prevent writing on some table (like the sqlite_master one), when SQLite create it, it sets a "read only" flag. The trick is to edit the source code in order to give to this flag, the value of "read and write".
In the sqlite3.c of the LIB, it's a line 17420. You'll see:

      #define TF_Readonly        0x0001    /* Read-only system table */

Just change it by

       #define TF_Readonly        0x0000    /* Read-only system table */

So when SQLite will create a system table, it will set a read+write flag and so, you would be able to update the sqlite_master table. You need to compile again de lib (on Arduino IDE, just select a wrong board, try to compile, get an error, select ESP32 and compile again and the IDE will perform a full compilation of the lib)

If you have trigger, and some other specific feature, maybe it would be nice to check the result of the select * from sqlite_master in order to see if some records need also to be updated. But for basic table, this will do the job.

Hope this will help.

***Edit***

If you add an index (or more than one) to your table, you'll have also to update 'index" records from sqlite_master. They are like that:

 - type = index
 - name = index_ttest_nom
 - tbl_name = TAB_TEST
 - rootpage = 6
 - sql = CREATE UNIQUE INDEX index_ttest_nom ON TAB_TEST (ttest_nom)

So just update the tbl_name value giving the new name of the table, and update the sql field the same way.


message:
MPU6050 does not give output

I need help getting my MPU 6050 to actually give me data. As of right now, my program is only reading 0s from the gyroscope and when I move it, the values all go to -1 and the program just stops until I close and reopen the serial monitor. I know this question has been asked multiple times before, but I've already looked at each of those questions and tried all of the fixes listed there, but not a single one has worked. The I2C scanner does find the sensor at 0x68, but that's only thing that works. These are all brand new boards that I got a couple days ago.

I've tried every library and every example sketch I could find. I've switched to 2 new boards. I've even tried looking at the [datasheet][1] for the MPU 6050 and reading/writing the registers directly and still I'm getting no results. The serial monitor either stays blank, shows only 0s or -1s, or just gives me garbage values that change randomly. Please help me.

I've wired the sensor like this (I'm currently on an Arduino Uno):

VCC ==> 5V\
GND ==> GND\
SCL ==> A5\
SDA ==> A4\
AD0 ==> digital 13 (set to LOW)

And the code I'm using is this:

  [1]: https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf

```
#include <Wire.h>

const int addressPin = 13;

int gyroX, gyroY, gyroZ;

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

  //designating pins as I/O
  pinMode(addressPin, OUTPUT);

  //setting IMU address to 0x68 (LOW)
  digitalWrite(addressPin, LOW);

  initializeSensor();
}

void loop() {
  readGyro();

  Serial.print(gyroX);
  Serial.print("    ");
  Serial.print(gyroY);
  Serial.print("    ");
  Serial.println(gyroZ);
}

void initializeSensor() {
  //performing full device reset, disables temperature sensor, disables SLEEP mode
  Wire.beginTransmission(0x68);

  Wire.write(0x6B);
  Wire.write(0b10001000);

  Wire.endTransmission();

  //writing to gyro config register
  Wire.beginTransmission(0x68);

  Wire.write(0x1B);
  Wire.write(0b00001000);

  Wire.endTransmission();
}

void readGyro() {
  //requesting data from gyro data registers
  Wire.beginTransmission(0x68);

  Wire.write(0x43);

  Wire.endTransmission();

  Wire.requestFrom(0x68, 6);

  gyroX = Wire.read()<<8|Wire.read();
  gyroY = Wire.read()<<8|Wire.read();
  gyroZ = Wire.read()<<8|Wire.read();
}
```

P.S. I few weeks ago I posted a question about I2C devices and in it, I said I had managed to successfully read data from the sensor, but I found out later those were garbage numbers. :(

body:
From the [MPU-6000/MPU-6050 Register Map and Descriptions][1]:

- Section 4.28, Register 107 – Power Management 1 PWR_MGMT_1, pages 40 to 41:

   > Note:<br>
   > When using SPI interface, user should use DEVICE_RESET (register 107) as well as SIGNAL_PATH_RESET (register 104) to ensure the reset is performed properly. The sequence used should be:
   > 1. Set DEVICE_RESET = 1 (register PWR_MGMT_1)
   > 2. Wait 100ms
   > 3. Set GYRO_RESET = ACCEL_RESET = TEMP_RESET = 1 (register SIGNAL_PATH_RESET)
   > 4. Wait 100ms

- Section 4.26, Register 104 – Signal Path Reset SIGNAL_PATH_RESET, page 37:
   > Note: This register does not clear the sensor registers. The reset initializes the serial interface as well.

 - Section 3, Register Map, page 8:
   > The reset value is 0x00 for all registers other than the registers below.
   > - Register 107: 0x40.
   > - Register 117: 0x68.

This means that the PWR_MGMT_1 register defaults to sleep mode after a reset so it needs to be rewritten to disable sleep mode after commanding a reset.

```cpp
void initializeSensor()
{
  //
  // Perfrom full reset as per MPU-6000/MPU-6050 Register Map and Descriptions, Section 4.28, pages 40 to 41.
  //

  // performing full device reset, disables temperature sensor, disables SLEEP mode
  Wire.beginTransmission(0x68);  // Device address.
  Wire.write(0x6B);              // PWR_MGMT_1 register.
  Wire.write(0b10001000);        // DEVICE_RESET, TEMP_DIS.
  Wire.endTransmission();
  delay(100);                    // Wait for reset to complete.

  Wire.beginTransmission(0x68);  // Device address.
  Wire.write(0x68);              // SIGNAL_PATH_RESET register.
  Wire.write(0b00000111);        // GYRO_RESET, ACCEL_RESET, TEMP_RESET.
  Wire.endTransmission();
  delay(100);                    // Wait for reset to complete.

  // Disable SLEEP mode because the reset re-enables it. Section 3, PWR_MGMT_1 register, page 8.
  Wire.beginTransmission(IMUAddress);   // Device address.
  Wire.write(0x6B);                     // PWR_MGMT_1 register.
  Wire.write(0b00001000);               // SLEEP = 0, TEMP_DIS = 1.
  Wire.endTransmission();
}
```

In the following code I've:
1. Modified `readGyro()` to implement 3 states (Request, Wait, and Read) and return `true` when 6 bytes have been read from the MPU-6050.

2. Added [Blink Without Delay][2] to `loop()` to see whether the MCU freezes which requires changing the ADO pin from pin 13 (the built-in led) to another pin, i.e. pin 12.

3. Added several `Serial.print()` statements for debugging to see where things go wrong.

4. Tweaked the code in response to comments.

```cpp
#include <Wire.h>

const byte IMUAddress = 0x68;   // Added for readability and maintainability.
const byte addressPin = 12;     // Changed from 13 to 12 because 13 is built-in LED.

int gyroX, gyroY, gyroZ;

void setup()
{
  Wire.begin();
  Serial.begin(115200);
  Serial.println(F("\n\nMPU-6050 Test\n"));

  // Designating pins as I/O.
  pinMode(addressPin, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);  // Added LED for heartbeat signal.

  // Setting IMU address to 0x68 (LOW).
  digitalWrite(addressPin, IMUAddress & 1);  // Added bit mask of bit 0.

  initializeSensor();
}

void loop()
{
  //
  // TASK 1: Blink without delay to indicate that MCU hasn't frozen.
  //
  const unsigned int INTERVAL = 250;
  unsigned long current_timestamp = millis();
  static unsigned long previous_timestamp = current_timestamp;
  static bool led_state = false;
  if (current_timestamp - previous_timestamp >= INTERVAL)
  {
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    previous_timestamp += INTERVAL;
  }

  //
  // TASK 2: Read gyro.
  //
  if (readGyro())
  {
    Serial.print(gyroX);
    Serial.print(F("    "));
    Serial.print(gyroY);
    Serial.print(F("    "));
    Serial.println(gyroZ);
  }
}

void initializeSensor()
{
  //
  // Perform full reset as per MPU-6000/MPU-6050 Register Map and Descriptions, Section 4.28, pages 40 to 41.
  //

  Serial.print(F("Performing full reset of MPU-6050..."));

  Wire.beginTransmission(IMUAddress);   // Device address.
  Wire.write(0x6B);                     // PWR_MGMT_1 register.
  Wire.write(0b10001000);               // DEVICE_RESET, TEMP_DIS.
  Wire.endTransmission();
  delay(100);                           // Wait for reset to complete.

  Wire.beginTransmission(IMUAddress);   // Device address.
  Wire.write(0x68);                     // SIGNAL_PATH_RESET register.
  Wire.write(0b00000111);               // GYRO_RESET, ACCEL_RESET, TEMP_RESET.
  Wire.endTransmission();
  delay(100);                           // Wait for reset to complete.

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

  // Disable SLEEP mode because the reset re-enables it. Section 3, PWR_MGMT_1 register, page 8.
  Serial.print(F("Disabling sleep mode of MPU-6050..."));
  Wire.beginTransmission(IMUAddress);   // Device address.
  Wire.write(0x6B);                     // PWR_MGMT_1 register.
  Wire.write(0b00001000);               // SLEEP = 0, TEMP_DIS = 1.
  Wire.endTransmission();
  Serial.println(F(" Done."));

  //
  // Writing to gyro config register.
  //
  Serial.print(F("Configuring gyro of MPU-6050..."));
  Wire.beginTransmission(IMUAddress);   // Device address.
  Wire.write(0x1B);                     // GYRO_CONFIG register.
  Wire.write(0b00001000);               // +/-500 deg/s.
  Wire.endTransmission();
  Serial.println(F(" Done."));
}

typedef enum State
{
  Request,
  Wait,
  Read
};

bool readGyro()
{
  static State state = State::Request;

  switch (state)
  {
    case State::Request:
      // Request data from gyro data registers.
      Serial.print(F("Requesting data from gyro..."));
      Wire.beginTransmission(IMUAddress);   // Device address.
      Wire.write(0x43);                     // GYRO_XOUT_H register.
      Wire.endTransmission(false);          // Restart connection, i.e. keep alive.
      Wire.requestFrom(IMUAddress, 6);      // GYRO_XOUT_H, GYRO_XOUT_L, GYRO_YOUT_H, GYRO_YOUT_L, GYRO_ZOUT_H, GYRO_ZOUT_L.
      Serial.println(F(" Done."));
      state = State::Wait;
      Serial.print(F("Waiting for data from gyro..."));
      break;

    case State::Wait:
      // Wait for data to arrive into buffer.
      if(Wire.available() < 6)
      {
        //Serial.print(F("."));
        Serial.print(F(" "));
        Serial.print(Wire.available());  // Added to show bytes received.
      }
      else
      {
        Serial.print(F(" "));
        Serial.print(Wire.available());  // Added to show bytes received.
        Serial.println(F(" Done."));
        state = State::Read;
      }
      break;

    case State::Read:
      // Read data from gyro registers.
      Serial.print(F("Reading gyro data..."));
      gyroX = Wire.read() << 8 | Wire.read();
      gyroY = Wire.read() << 8 | Wire.read();
      gyroZ = Wire.read() << 8 | Wire.read();
      Serial.println(F(" Done."));
      state = State::Request;
      return true;  // Indicate data was received.
      break;
  }

  return false;  // Indicate no data received yet.
}
```

**Update based upon RowanP's answer**

While concentrating on the software issues I missed a crucial piece of information from the other datasheet ([MPU-6000/MPU-6050 Product Specification][3]), i.e. the electrical characteristics in Sections 6.3 and 6.4 on pages 14 and 15 showing a Vdd range of 2.375 V to 3.46 V:

[![Electrical Characteristics of MPU-6050][4]][4]
[![Vdd power supply of MPU-6050][5]][5]

**6.4 Electrical Specifications, Continued**
[![Digital inputs and outputs of MPU-6050][6]][6]

This will require [level shifters][7]  on the signals between the 3.3 V MPU-6050 and the 5 V Arduino.

  [1]: https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf
  [2]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay/
  [3]: https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Datasheet1.pdf
  [4]: https://i.stack.imgur.com/DQsKX.png
  [5]: https://i.stack.imgur.com/T0Y6x.png
  [6]: https://i.stack.imgur.com/j79QD.png
  [7]: https://www.falstad.com/circuit/circuitjs.html?ctz=CQAgjCAMB0l3BWcMBMcUHYMGZIA4UA2ATmIxAUgoqoQFMBaMMAKADMQ8AWPcDQzjxCYUIbKLDQkMSChYAnEBgSiRSlXwFUw8SApDEuXTQaPCMo7bpYB3TuPOjlqi1FvqXownl5q5dvEJjNUNg1z07UMdkfGi5ACUPE2dwFF4qKi4qbGhsKHyYBBZEqLB U2MwNIKQLOoMqCl3FLKBbl5WtztvXmxsNqE rXd2sX6Y3vG9AHNBSYHe7wKWAGcJ6J1YofyINgBDABsVulWQHrGBc7VtEH2jk4APM7BiYUJLrleiV8rRAGUAMIAGVYTx0Dm yEInlqqRAgKBcieGBeBnIxDwSE2sJQxgAQgBLBgAEwJ8joAGMAC4EgD2ADtDgAdFYHOgANzoBxZKwAFgS2FS6PIWLTYUF8lkMfVYNJhLC8gjWGKPpLINKuNBSBjmAhvDxCBhIHkZHAIFQvGJ4cC5EA


body:
A while ago while figuring out I2C difficulties of my own I did some research and listed out all the failure modes and test techniques I could think of regarding I2C. See https://arduino.stackexchange.com/questions/79775/i2c-protocol-doesnt-work-properly/81001#81001. I routinely go through the list now to tick off the things I need to check to get a new I2C connection working, usually it's something simple (fingers crossed). Do you have access to an oscilloscpe?

(Edit) This old post seems to describe a similar problem (only getting zeros) https://arduino.stackexchange.com/questions/37629/mpu6050-doesnt-work. The consensus there was that the **3.3V MPU6050 had been connected to a 5V UNO, frying the MPU6050 chip**. That sounds very like your situation.


body:
I used 5 V from my Arduino to power the MPU6050, and it was fine. Check out: https://www.instructables.com/How-to-Make-a-Robot-Car-Drive-Straight-and-Turn-Ex/, which has very similar code.

Also, I typically avoid pin 13, since it performs some special additional function, unlike pin 2 to 12.


message:
SIM800L and UNO can't request web page

I know this module is super old but the network I am on still uses GPRS so should work.

This is the module:
[![enter image description here][1]][1]
I am using the Adafruit example scipt FONAtest. I can connect to GPRS

``` ---> AT+CIPSHUT
 <--- SHUT OK
 ---> AT+CGATT=1
 <--- OK
 ---> AT+SAPBR=3,1,"CONTYPE","GPRS"
 <--- OK
 ---> AT+SAPBR=3,1,"APN","live.vodafone.com"
 <--- OK
 ---> AT+CSTT="live.vodafone.com","",""
 <--- OK
 ---> AT+SAPBR=3,1,"USER",""
 <--- OK
 ---> AT+SAPBR=3,1,"PWD",""
 <--- OK
 ---> AT+SAPBR=1,1
 <--- OK
 ---> AT+CIICR
 <--- OK
FONA>
```

There is credit on the SIM so it has data for sure, I can also send SMS.

There are several different approaches people seem to take (altering AT commands) to persuade this device to work, pretty sure I have tried all of them :) I always get a timeout when trying to read or GET a webpage.

I have tried several combinations via terminal and I seem to connect ok but get no further. It has worked once, but that was in a different part of town.

How do I check that the GPRS is actually connected? Any troubleshooting tips?

There is a dedicated 2A 5V connected to the unit, it isn't dropping out AFAIK. Do you have a rock-solid AT sequence that always works?

Also, there seem to be SAPBR commands that don't work at all, not sure why?

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

body:
It highly depends on the URL you are trying to fetch.
Those modules DO NOT understand secure HTTP/S. They only understand plain unsecure HTTP.
Most web pages nowdays don't offer unsecure HTTP access and always redirect the request to a HTTP/S server. So in my opinion the usefulness of those devices is very limited when it comes to internet access.

If you have full control over the web server you should disable the enforcement of a secure connection.

Beyond that. The sequence you posted is just for activating GPRS.

I also found the FONA sample for fetching a page not very reliable but I was able to request the page multiple time. Perheps you have your module in a place with low signal strenght. Does your module offer an u.fl connector for a better antenna?


body:
Don't know why, I had to manually set the DNS t0 8.8.8.8 using `AT+CDNSCFG?`

It had DNS entries in there but they didn't want to resolve for some reason.


message:
Pro Mini - Using RAW pin for 3.3v input

I design a PCB that one of its components is a 3.3v Pro Mini. Since I want it versatile regarding powering the PCB (3.3v or 5.0v) I want to know if it is a good practice to supply 3.3v to Pro Mini's RAW pin( rather than to the VCC Pin ).

body:
It is not ideal, no.  The RAW pin first goes into a 3.3V voltage regulator whose dropout voltage is up to 200mV (worst case).  That means that you would get around 3.1V out, and it wouldn't be properly regulated.

Oh, it would *work*, but the power won't be stable, which means that any analogue readings that you make that don't directly use the (shakily) regulated "3.3V" (now 3.something else V) in the generation of the analog signal (such as a simple potentiometer) will be inaccurate.

Also output logic voltages will be lower than expected which may have an effect if communicating with something whose upper input threshold is at or near the 3.3V mark (such as many 5V devices).