body:
That is a difference between embedded systems programming and (many but not all) other types of programming. An embedded system is usually a controller of some kind and needs to be responsive to one or more kinds of events. Three typical ways of accomplishing this are

 - to use some kind of operating system to coordinate events and the code that manages each of them;
 - to write interrupt service routines (ISRs) to manage events and dispatch to code that manages them;
 - to poll for events frequently and dispatch to the code to manage them.

On processors as small as the AVRs, data memory and sometimes instruction memory, are scarce resources and an operating system is usually too expensive (in terms of memory needs) for most of them. On the ATtinys, forget it. On Uno, maybe kinda sorta, but memory will be a pretty severe limitation. On Megas, you might manage it.

ISR programming can be complex to write and is definitely more complex to debug(!). It's not out of the question, and it may be justified in a system that must be highly responsive - think automotive ABS braking, traction control, and fly-by-wire systems. On the other hand, systems like these *have to be right*.

Polling is the easiest to write and debug. You call each subsystem (code) in a tight loop (and there's your answer: "yes, let it iterate") that gives each one an opportunity to assess whether or not it needs to act and to do so. This is a case where burning cycles is inconsequential, while making a more responsive system.

In my hobbyists' classes, this is what I teach; it's also what use most. I call it "maybe-do" ([and wrote about it here][1] in answer to another question). In `loop()` I do nothing but call a number of functions in turn, each of which does:

       {
          if I dont need to act now,
             return;
          else {
             do what needs to be done -- quickly!;
             return;
          }
       }

  [1]: https://arduino.stackexchange.com/questions/60759/how-to-rotate-two-or-more-steppers-simultaneously-by-giving-array-of-angles/66380#66380


sender: user

message:
How to get full response json SIM900 + Arduino?

```
  void toSerial(int delay_ms)
  {
    delay(delay_ms);

    while(mySerial.available())
    {
       Serial.write(mySerial.read());
    }
  }

  Serial.begin(9600);
  mySerial.begin(9600);

  mySerial.println("AT+HTTPINIT");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"CID\", 1");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"URL\", \"www.example.test\"");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(500);

  mySerial.println("AT+HTTPACTION=0");
  toSerial(4000);

  mySerial.println("AT+HTTPREAD");
  delay(3000);

  while(mySerial.available())
  {
    Serial.write(mySerial.read());
  }

  Serial.println("");
  mySerial.println("AT+HTTPTERM");
  toSerial(500);

```
**Result:**
```
AT+HTTPREAD

+HTTPREAD:39
{"pinRed":0,"pinGreen":1,"pinYello

```

**I expect messages:**
```
{"pinRed":0,"pinGreen":1,"pinYellow":0}
```

sender: assistant

body: Okay, I've found a solution. To start with, you need to download the server response length and loop according to the response length.


message:
Does the MKR WIFI 1010 support the arduino mouse and keyboard controller?

I am working on a project right now that needs to connect to my computer via bluetooth and access the arduino mouse and keyboard library. In my research, I've found that only the Leonardo, Due, and Micro can emulate cursor movements, but they need to have additional hardware like the HC05. I would like to keep the amount of hardware I use to a minimum, but I understand if there is no way around it. Is there any way to use the MKR WIFI 1010 like a Leonardo, or would I need to get one of the aforementioned boards and then get a bluetooth module hooked up?

PS this is my first dive into bluetooth, so any additional resources to aid me in my journey would be much appreciated.

body:
Yes, the Arduino SAMD boards are supported by the Arduino Keyboard and Mouse library.

Nano 33 IoT is a smaler alternative to MKR 1010.

But the MKR1010 or the Nano33 IoT with original NINA firmware doesn't yet support classic Bluetooth like the HC-05 module. The ArduinoBLE library and the NINA firmware support only BLE which is different.

But there is a simple way to replace the NINA firmware with the ESP32 Arduino basic Bluetooth sketch SerialToSerialBT and then use it from the SAMD. This way the NINA module will be degraded to something like a HC-05.


message:
turning positional servo motor more then 180 degrees

My RC servo motor is capable of turning more then 180 degrees(around 200 degrees) when I physically turn it, but when I use my code it only turns 180.

Is there a way to code it so that it turns to 200 instead of 180?

body:
First some basics to clear definitions:

A Servo Motor does not normally spin a full 360 degree rotation. Instead it is limited to a range of 180, 270 or 90 degrees depending on the make or type. A control signal is sent to the servo to position the shaft at the desired angle.

**Conventional Servo Motor Timing**

In a conventional analog servo motor a PWM signal with a period of 20 ms is used to control the motors. A signal of 20 ms has a frequency of 50 Hz.

The width of the pulse is varied between 1 and 2 ms to control the motor shaft position.

 - A pulse width of 1.5ms will cause the servo shaft to rest in the 90 degree position, the center of its travel.
 - A pulse width of 1ms will cause the servo shaft to rest at the 0 degree position.
 - A pulse width of 2ms will cause the servo shaft to rest in the 180 degree position.

Varying the pulse width between 1ms and 2ms will move the servo shaft through the full 180 degrees of its travel. You can bring it to rest at any angle you desire by adjusting the pulse width accordingly.

So if your servo is a 270 degree servo (like the domanrc DM-S0903MD or DS3218 270 Degree Digital RC Servo) the standard sweep sketch (Arduino Servo library) will let your servo sweep from 0-270 even if in the *.ino its `myservo.write(180);` So to simply test you could use `write(map(desired_angle, 0, 270, 0, 180))`

If you want to control it more precicly you use microseconds.

    servo.attach(5,500,2500)
    servo.writeMicroseconds(1500);

**AND** you have to use an extra power supply for 270 degree servos, the 5V from Arduino want make them move or only in a jittering way of.

If you just have a "defect" 180 degree servo turning to lets say 190 degree for some reason, you might try the microsecond method playing around with the values in attach, also use an extra power supply, but for real over 180 degree action get a 270 degree servo.


body:
Just because a servo can manually be turned more than 180 degrees doesn't mean that it *should* be turned more than 180 degrees.

Most servos will include a certain amount of leeway in their design to help reduce damage from external forces, but the internal design will be geared1 towards operating over a 180 degree range.

While it may be possible to "overdrive" the motor by changing the PWM timing signals (see the [Servo attach() reference page](https://www.arduino.cc/en/Reference/ServoAttach)) doing so may end up damaging the servo itself.

----

1: Pun intended


message:
RGB LED color control with a single value

Apps like Photoshop have a single slider to select color: [![enter image description here][1]][1].

I'd like to achieve the same using variable resistance knob as a slider to control color of RGB LED. Can anyone put me on the right track how to linearly map color values?

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

body:
What you are controlling there is one out of three values from the HSV (aka HSB) colour space.

Colour can be represented in a number of different ways, called "spaces".  You computer monitor displays colour in the RGB colour space - red, green and blue. An RGB LED of course also displays in the RGB colour space.  Your colour printer works in the CMYK colour space.

Different colour spaces represent the colour using different values and combinations of values, and which colour space you use may be imposed by technical limitations (such as in the printer it is dictated by the combination of the colours of the inks).

HSV is a convenient way of visually manipulating colour since it gives you easy to understand "Hue" (the colour), "Saturation" (how much colour) and "Value" (or "Brightness" - how light the colour is) values that are easy for a human to understand.

However physical devices don't generally work with that colour space, so you need to be able to translate between them.

You can think of HSV as the "Human" colour space, and RGB as the "Digital" colour space.

Fortunately it's relatively simple to convert from one to another and there are a number of code snippets online that give examples of how to do it.

I'm going to include one here that I use in my chipKIT TFT display library "Cariad".  Given three 8 bit values (0-255) of "hue" "sat" and "val" it will calculate the red, green and blue values. "hue" would be the one you change with your pot - the others can be static values (or you could add more pots to control those too).

```
    unsigned int H_accent = hue/43;
    unsigned int bottom = ((255 - sat) * val)>>8;
    unsigned int top = val;
    unsigned char rising  = ((top-bottom)  *(hueC   )  )  /  43  +  bottom;
    unsigned char falling = ((top-bottom)  *(43-hueC)  )  /  43  +  bottom;

    int r = 0;
    int g = 0;
    int b = 0;

    switch(H_accent) {
        case 0:
                r = top;
                g = rising;
                b = bottom;
        break;

        case 1:
                r = falling;
                g = top;
                b = bottom;
        break;

        case 2:
                r = bottom;
                g = top;
                b = rising;
        break;

        case 3:
                r = bottom;
                g = falling;
                b = top;
        break;

        case 4:
                r = rising;
                g = bottom;
                b = top;
        break;

        case 5:
                r = top;
                g = bottom;
                b = falling;
        break;
    }
    if (r > 255) r = 255;
    if (g > 255) g = 255;
    if (b > 255) b = 255;
    if (r < 0) r = 0;
    if (g < 0) g = 0;
    if (b < 0) b = 0;
```


message:
How to replace String objects with char arrays while still using string methods

I am running the following code on my ESP8266 (AI-Thinker ESP8266MOD).

I send an HTTP GET request and a pin is set to high for a 1/2 second.

However, after some time (sometimes 1hr, 2hrs, 12hrs, totally random), it stops responding to HTTP requests.
I think it might be because of heap fragmentation due to the String objects I'm using.

**Questions:**

How can I replace the `request` (in `loop()`) and `s` and `text` (in `GenerateResponse()`) objects with  char arrays?
After I replace the String objects with char arrays, how can I use the `indexOf()` method and `+` operator on the char arrays?

Will this approach help with heap fragmentation?

Is it possible to find out if heap fragmentation is the problem?

    #include <ESP8266WiFi.h>

    const char* ssid = "myWifi";
    const char* wifiPassword = "y76ggS";
    const char* passwordToOpenDoor = "/81"; //password should begin with a slash

    const int doorPin = 5;

    WiFiServer server(301); //Pick any port number you like
    WiFiClient client;

    void setup() {
      Serial.begin(115200);
      delay(10);
      Serial.println(WiFi.localIP());

      pinMode(doorPin, OUTPUT);
      digitalWrite(doorPin, 0);

      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, wifiPassword);

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

      server.begin();
      Serial.println("Server started. Diagnostics info:");
      Serial.println(WiFi.localIP());
    }

    void loop() {
      client = server.available();
      if (!client) {
        return;
      }

      while(!client.available()){
        delay(1);
      }

      String request = client.readStringUntil('\r');
      client.flush();

      Serial.println(request);
      if (request.indexOf(passwordToOpenDoor) != -1) { //Is password correct?
        GenerateResponse("Password is correct");
        OpenDoor();
      }
      //Got a GET request and it wasn't the favicon.ico request, must have been a bad password:
      else if (request.indexOf("favicon.ico") == -1) {
        GenerateResponse("Password is incorrect.");
      }
    }

    void OpenDoor() {
      digitalWrite(doorPin, 1);
      delay(500);
      digitalWrite(doorPin, 0);
    }

    void GenerateResponse(String text) {
      Serial.println(text);
      String s = "HTTP/1.1 200 OK\r\n";
      s += "Content-Type: text/html\r\n\r\n";
      s += "<!DOCTYPE HTML>\r\n\r\n";
      s += "

" + text + "
";
      s += "\n";
      client.flush();
      client.print(s);
      delay(1);
    }

body:
You asked: "After I replace the String objects with char arrays, how can I use the indexOf() method and + operator on the char arrays?"

Short answer: You can't. If you want to use C strings (aka arrays of char), you'll have to use C string functions.

The String methods operate on String objects. The common wisdom is to avoid the String class entirely since it relies on heap memory, and Arduinos are far, far too memory-starved to be able to use a class like String which creates temporary objects on the heap.


body:
So here is code to get you started:

    myMessageArray [256] = {'\0'}; // Define global array large enough and zero terminate

the + method is replaced by

    strcpy (myMessageArray, "Text to Add");
    // Initializes the myMessageArray starts at index 0
    strcat (myMessageArray, "More text to Add");
    // Appends to the myMessageArray starts at current index

converting numeric values to chars:

    uint_16_t myNumberValue  = 31253;
    char numBuffer [16] = {'\0'}; // Helper buffer for conversions

    itoa (myNumberValue,numBuffer,10);  // converts an integer to a base 10 (decimal) char
    itoa (myNumberValue,numBuffer,2);  // converts an integer to a base 2 (binary) char
    itoa (myNuberValue,numBuffer,16);  // converts an integer to a base 16 (hex) char

itoa initilizes a char array so we need the helper array:

    strcat (myMessageArray, numBuffer);

to convert float we use

    dtostrf(floatVariable, StringLengthIncDecimalPoint, numVarsAfterDecimal, numBuffer);

to convert chars back to int use

    int16_t myIntVar = atoi(numBuffer);

to convert chars back to floats use

    float myFloatVar = atof(numBuffer, decimalsToShow); // using just atof(numBuffer)
    gives you standard x.XX only 2 decimals

A working IndexOf for char arrays:

    /*******************************************************************************/
    /**
        \brief Finds the index of the given value in the array starting at the given index
        \author codebreaker007
        \param [in] targetArray the array to search through for the char
        \param [in] valueToFind the value to find
        \param [in] startIndex the index to start searching at
        \return the index of the value within the array

        \details This method returns INDEX_NOT_FOUND^(-1) for a null input array.
            A negative startIndex is treated as zero. A startIndex larger than the array
            length will return INDEX_NOT_FOUND(-1)
    */
    /********************************************************************************/
    int8_t indexOf(char* targetArray, char valueToFind, uint16_t startIndex = 0) {
      if (targetArray == NULL) {
        return INDEX_NOT_FOUND;
      }
      if (startIndex <= 0) {
        startIndex = 0;
      }
      for (uint16_t i = startIndex; i < strlen(targetArray); i++) {
        if (valueToFind == targetArray[i]) {
          return i;
        }
      }
      return INDEX_NOT_FOUND;
    }

To compare char arrays you should look into the `strcmp` function and if you want to checkthe first n char tomatchyou use:

    if (strncmp(myMessageArray , "POST", 4 ) == 0) {
    // compares the first 4 chars if it matches = 0, see details in the arduino doku

Hope this comprehensive intro to char arrays helps you for your current and future projects. How to find out - convert to char arrays and if its runnibg stable that was it. Before that conversion you can never rule out String class as culprit.


body:
You already received good answer about some _general_ ideas for
replacing `String` objects with C strings. Here I will try to add some
more tricks more specifically targeted to your actual situation.

I can see two places in your program where the use of `String` shines by
its convenience, and replacing it with C strings will require some
effort. The first is the use of `Stream::readStringUntil(char)` for
getting the first request line. Here
<s>I see no better option</s> (see edit below) than reading
the stream one character at a time, and putting those characters into an
array:

```c++
const size_t input_buffer_length = 256;

// Read a line of text up to the first '\r'.
// Returns a NUL-terminated string, without the final '\r',
// into a statically allocated buffer.
// Warning: this never times out.
const char *readline(Stream &input)
{
  static char buffer[input_buffer_length];
  size_t pos = 0;  // writing position within the buffer
  int c;           // current character
  while ((c = input.read()) != '\r') {
    if (c >= 0 && pos < sizeof buffer - 1) {
      buffer[pos++] = c;
    }
  }
  buffer[pos] = '\0';  // terminate the string
  return buffer;
}
```

You would use it like this:

```c++
const char *request = readline(client);
```

For more robustness, you may want to add a timeout. Note also that this
implementation is no reentrant, as it uses a static buffer. This is not
an issue for your use case.

**Edit**: As noted by hcheung in a comment, you do not need to implement
this `readline()` function, as you can use
[`Stream::readBytesUntil()`][readBytesUntil], which handles the timeout
and is provided by the Arduino core:

```c++
char buffer[input_buffer_length];
client.readBytesUntil('\r', buffer, input_buffer_length);
```

[readBytesUntil]: https://www.arduino.cc/reference/en/language/functions/communication/stream/streamreadbytesuntil

The other place is the usage of `String::operator+=(const char *)` for
generating the response. Here I would advice you _against_ using
`strcat()` or `strncat()`: these will require extra memory to store the
concatenated string which you probably do not need. Instead, you can
simply `print()` the pieces one by one:

```c++
void GenerateResponse(const char *text) {
  Serial.println(text);
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.print("<br><h1><b>");
  client.print(text);
  client.println("</b></h1></html>");
  client.flush();
  delay(1);
}
```

Alternatively, you can make use of the implicit concatenation of string
literals in order to reduce the number of calls to `client.print()`:

```c++
void GenerateResponse(const char *text) {
  Serial.println(text);
  client.print(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html\r\n"
      "\r\n"
      "<!DOCTYPE HTML>\r\n"
      "<html>\r\n"
      "<br><h1><b>"
  );
  client.print(text);
  client.print("</b></h1></html>\r\n");
  client.flush();
  delay(1);
}
```


message:
Read status on SCART output

I'm trying to get the status of my set top box (on/off).
It does have USB but it's always powered on.
It has optical out that is also always on.
It has an IP address that always responds to ping.

So my next idea is to read the signal in the SCART.
If I read the voltage across pin 8 and 14 I get 0-ish when off and 12 when on.
But when it powers on it spikes at 18 volt (at least what my multimeter can see).
 https://youtu.be/D2eVFe33MeM

What do I need to do to read this?
If I add a voltage divider with 1 and 4.7 Kohm I get a safe voltage **if it does not go above 18 volt at any time**.

But what can I do to be sure I don't burn a ESP chip?
Is there any way to make sure it's safe to read even if it spikes at say 25 volts?

body:
I would use something like below. The optical isolator ([PC817][1] or similar) protects your ESP.

 - Use a 1.0-1.5K resistor from the incoming SCART switch signal (SCART pin 8) to the anode of the Opto isolator (pin 1 in case of the PC817). This will limit the current through the PC817 internal LED to about 10mA with a 12V signal but the PC817 can survive up to 50mA, i.e. up to 60V on the SCART plug and even then will not damage your ESP processor.
 - Connect SCART ground (pin 14) to the cathode of the Opto isolator
   (pin 2).
 - Connect a 3.3K - 4.7K resistor to the collector of the phototransistor of the PC817 (pin 4 of the PC817) and connect the other side of this resistor to Vcc of your ESP (+3.3V) as a pullup.
 - Connect pin 3 (emitter) of the PC817 to the Ground of your ESP.

 - Connect a digital input pin of your ESP to pin 4 (phototransistor collector) of your PC817 to create an active-low signal indicating your set top box is active.

This is the schematic you could use:

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

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

<!-- End schematic -->

  [1]: https://www.farnell.com/datasheets/73758.pdf


message:
Bootloader onto an ATmega328p (3.3V/8MHz), the dude won't finish his business

Hi and thank you reading my question !

I need for my projects to design as small as i can. Both the skills, and the hardware counts. So i can't use a DIP package for them, and i have gone for a TQFP package. The point is to programm a TQFP ATmega328P using an external board without soldering it, which plugs into a Arduino UNO. Like that no need to constantly check the connection and everything. The shield is a basically a fat Arduino Pro Mini, with all the options available (3.3V/5V, 8MHz/16MHz, Sparkfun FTDI can be connected, ...) as shown below :

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

As you can see I am the enginneer of Gymetrics, but not an electronic enginner nor a programmer ... I actually did some mistakes designing it with the SS pin pins connected together and not the one of the Arduino UNO to the reset pin of the target, and added a capacitor in the wrong place. I did manage to connect the pin 10 of the Arduino to the reset pin of the target on another shield and take out that capacitor. When you order one you got tens of them at the minimum ...

As the schematic is the same as the Mini, and i don't think it's needed. I know that burn in sockets already exists, but because you to reverse enginneer the pins to make it works, i prefered design my own. Ok sorry for that long introduction, but i prefered you to know the full reflexion. As you imagine, i've been searching on so many forum, tutoriels, and so ever to do it and still it doesn't work.

As it is the first time i burn a bootloader into an ATmega328P, i am not confident in what i am doing. So i tried to burn a bootloader into an Arduino Pro Mini, it works fine. I'm happy on a point : I know how to follow a step by step procedure !

The microcontroller i use (ATmega328P) is the same as the one on the Arduino Pro Mini, so the configuration in the Arduino IDE is the same. However, when the work is done easily with the Arduino Pro Mini, it doesn't work with my board. Here is what the IDE errors shows :

    Arduino : 1.8.12 (Windows 10), Carte : "Arduino Pro or Pro Mini, ATmega328P (3.3V, 8 MHz)"

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files
    (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM7 -b19200 -e -
    Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

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

         System wide configuration file is "C:\Program Files
     (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: erasing chip
    avrdude: reading input file "0x3F"
    avrdude: writing lock (1 bytes):

    Writing | ################################################## | 100% 0.01s

    avrdude: 1 bytes of lock written
    avrdude: verifying lock memory against 0x3F:
    avrdude: load data lock data from input file 0x3F:
    avrdude: input file 0x3F contains 1 bytes
    avrdude: reading on-chip lock data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of lock verified
    avrdude: reading input file "0xFD"
    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0xFD:
    avrdude: load data efuse data from input file 0xFD:
    avrdude: input file 0xFD contains 1 bytes
    avrdude: reading on-chip efuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of efuse verified
    avrdude: reading input file "0xDA"
    avrdude: writing hfuse (1 bytes):

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files         (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM7 -b19200 -    Uflash:w:C:\Program Files     (x86)\Arduino\hardware\arduino\avr/bootloaders/atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex:i -    Ulock:w:0x0F:m
    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xDA:
    avrdude: load data hfuse data from input file 0xDA:
    avrdude: input file 0xDA contains 1 bytes
    avrdude: reading on-chip hfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of hfuse verified
    avrdude: reading input file "0xFF"
    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.03s

    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xFF:
    avrdude: load data lfuse data from input file 0xFF:
    avrdude: input file 0xFF contains 1 bytes
    avrdude: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of lfuse verified

    avrdude done.  Thank you.

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

         System wide configuration file is "C:\Program Files     (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Erreur lors de la gravure de la séquence d'initialisation.
    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

    avrdude done.  Thank you.

Something very weird is that it reads the first and second time the right signature, and it's what i understand reading the error, and then doesn't read the signature anymore. If i try to burn again the bootloader, it can't read the signature anymore. I don't know what i am missing here.

What should i do ? I'm gonna try soldering an ATmega328P directly to see if it's a problem in the socket, but i don't think it is as it is working in the first communications.

Thank you !

**EDIT**

Programming interface :

    UNO               Target

    10                RST
    11                MOSI
    12                MISO
    13                SCK

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

body:
Problem solved, i did put two capacitors way to big on the XTAL's pins, which was making the crystal unable to resonate.

Thanks to @Wirewrap for finding the mistake


message:
What is the baud rate for Wiegand?

I am attempting to develop an Arduino project that can identify the bit format of a card (26-bit being the most common but not the only one).

This a library sets the serial to be 9600 baud.
https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary

This documentation says the data bit width is about 100us and the "inter pulse" or the time between the data bit is 20-100us.
https://docs.tibbo.com/taiko/ser_wiegand_mode

I don't understand how these match up? Also, Wiegand isn't even really serial. It uses two inputs - One input is for the on bits and another input is for the off bits.

body:
Wiegand doesn't have a baud rate as such. It's an edge-based input protocol where it looks for HIGH to LOW transitions on two different input lines.

There are certain timing requirements, in that you can't send data faster than the receiver is capable of receiving and pulses have to be wide enough for the receiver to read, and there is a minimum time for the gap between messages, but other than that there is no defined baud rate.


body:
Just tested my **HID multiCLASS SE RP40 920P** with an oscilloscope.

Time between pulses: ~ 2 ms

[![Wiegand oscilloscope time between pulses][1]][1]

Pulse duration: ~ 40 us

[![Wiegand oscilloscope pulse duration][2]][2]

Measured a few different events, they seemed very consistent.

  [1]: https://i.stack.imgur.com/qy6G4.png
  [2]: https://i.stack.imgur.com/pW5tr.png


message:
Use NeoSWSerial instead of SoftwareSerial with Adafruit Fingerprint Library

I'm using the FPM10A fingerprint sensor together with the Adafruit Fingerprint Library. I also have a GPS and Bluetooth module on the board already (connected to an Arduino UNO) and I'm using the neoSWserial library to communicate with them. I would like to use neoSWserial to communicate with the fingerprint sensor.

I've replaced all the instances of SoftwareSerial with NeoSWSerial in the respective .h and .cpp files but now the program says

    'Did not find fingerprint sensor'

For completeness here's the sketch, .h and .cpp file:

    /***************************************************
      This is an example sketch for our optical Fingerprint sensor

      Designed specifically to work with the Adafruit BMP085 Breakout
      ----> http://www.adafruit.com/products/751

      These displays use TTL Serial to communicate, 2 pins are required to
      interface
      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    #include <Adafruit_Fingerprint.h>

    // On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
    // uncomment this line:
    // #define mySerial Serial1

    // For UNO and others without hardware serial, we must use software serial...
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (WHITE wire)
    // comment these two lines if using hardware serial
    NeoSWSerial mySerial(12, 13);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);
      Serial.println("\n\nAdafruit finger detect test");

      // set the data rate for the sensor serial port
      finger.begin(57600);
      delay(5);
      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
      }

      finger.getTemplateCount();
      Serial.print("Sensor contains "); Serial.print(finger.templateCount); Serial.println(" templates");
      Serial.println("Waiting for valid finger...");
    }

    void loop()                     // run over and over again
    {
      getFingerprintIDez();
      delay(50);            //don't ned to run this at full speed.
    }

    uint8_t getFingerprintID() {
      uint8_t p = finger.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK success!

      p = finger.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {
        Serial.println("Did not find a match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      // found a match!
      Serial.print("Found ID #"); Serial.print(finger.fingerID);
      Serial.print(" with confidence of "); Serial.println(finger.confidence);

      return finger.fingerID;
    }

    // returns -1 if failed, otherwise returns ID #
    int getFingerprintIDez() {
      uint8_t p = finger.getImage();
      if (p != FINGERPRINT_OK)  return -1;

      p = finger.image2Tz();
      if (p != FINGERPRINT_OK)  return -1;

      p = finger.fingerFastSearch();
      if (p != FINGERPRINT_OK)  return -1;

      // found a match!
      Serial.print("Found ID #"); Serial.print(finger.fingerID);
      Serial.print(" with confidence of "); Serial.println(finger.confidence);
      return finger.fingerID;
    }

The header file:

    #ifndef ADAFRUIT_FINGERPRINT_H
    #define ADAFRUIT_FINGERPRINT_H

    /***************************************************
      This is a library for our optical Fingerprint sensor

      Designed specifically to work with the Adafruit Fingerprint sensor
      ----> http://www.adafruit.com/products/751

      These displays use TTL Serial to communicate, 2 pins are required to
      interface
      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    #include "Arduino.h"
    #if defined(__AVR__) || defined(ESP8266)
    #include <NeoSWSerial.h>
    #elif defined(FREEDOM_E300_HIFIVE1)
    #include <NeoSWSerial.h>
    #define NeoSWSerial NeoSWSerial
    #endif

    #define FINGERPRINT_OK 0x00
    #define FINGERPRINT_PACKETRECIEVEERR 0x01
    #define FINGERPRINT_NOFINGER 0x02
    #define FINGERPRINT_IMAGEFAIL 0x03
    #define FINGERPRINT_IMAGEMESS 0x06
    #define FINGERPRINT_FEATUREFAIL 0x07
    #define FINGERPRINT_NOMATCH 0x08
    #define FINGERPRINT_NOTFOUND 0x09
    #define FINGERPRINT_ENROLLMISMATCH 0x0A
    #define FINGERPRINT_BADLOCATION 0x0B
    #define FINGERPRINT_DBRANGEFAIL 0x0C
    #define FINGERPRINT_UPLOADFEATUREFAIL 0x0D
    #define FINGERPRINT_PACKETRESPONSEFAIL 0x0E
    #define FINGERPRINT_UPLOADFAIL 0x0F
    #define FINGERPRINT_DELETEFAIL 0x10
    #define FINGERPRINT_DBCLEARFAIL 0x11
    #define FINGERPRINT_PASSFAIL 0x13
    #define FINGERPRINT_INVALIDIMAGE 0x15
    #define FINGERPRINT_FLASHERR 0x18
    #define FINGERPRINT_INVALIDREG 0x1A
    #define FINGERPRINT_ADDRCODE 0x20
    #define FINGERPRINT_PASSVERIFY 0x21

    #define FINGERPRINT_STARTCODE 0xEF01

    #define FINGERPRINT_COMMANDPACKET 0x1
    #define FINGERPRINT_DATAPACKET 0x2
    #define FINGERPRINT_ACKPACKET 0x7
    #define FINGERPRINT_ENDDATAPACKET 0x8

    #define FINGERPRINT_TIMEOUT 0xFF
    #define FINGERPRINT_BADPACKET 0xFE

    #define FINGERPRINT_GETIMAGE 0x01
    #define FINGERPRINT_IMAGE2TZ 0x02
    #define FINGERPRINT_REGMODEL 0x05
    #define FINGERPRINT_STORE 0x06
    #define FINGERPRINT_LOAD 0x07
    #define FINGERPRINT_UPLOAD 0x08
    #define FINGERPRINT_DELETE 0x0C
    #define FINGERPRINT_EMPTY 0x0D
    #define FINGERPRINT_SETPASSWORD 0x12
    #define FINGERPRINT_VERIFYPASSWORD 0x13
    #define FINGERPRINT_HISPEEDSEARCH 0x1B
    #define FINGERPRINT_TEMPLATECOUNT 0x1D

    //#define FINGERPRINT_DEBUG

    #define DEFAULTTIMEOUT 1000 ///< UART reading timeout in milliseconds

    ///! Helper class to craft UART packets
    struct Adafruit_Fingerprint_Packet {

      /**************************************************************************/
      /*!
          @brief   Create a new UART-borne packet
          @param   type Command, data, ack type packet
          @param   length Size of payload
          @param   data Pointer to bytes of size length we will memcopy into the
         internal buffer
      */
      /**************************************************************************/

      Adafruit_Fingerprint_Packet(uint8_t type, uint16_t length, uint8_t *data) {
        this->start_code = FINGERPRINT_STARTCODE;
        this->type = type;
        this->length = length;
        address[0] = 0xFF;
        address[1] = 0xFF;
        address[2] = 0xFF;
        address[3] = 0xFF;
        if (length < 64)
          memcpy(this->data, data, length);
        else
          memcpy(this->data, data, 64);
      }
      uint16_t start_code; ///< "Wakeup" code for packet detection
      uint8_t address[4];  ///< 32-bit Fingerprint sensor address
      uint8_t type;        ///< Type of packet
      uint16_t length;     ///< Length of packet
      uint8_t data[64];    ///< The raw buffer for packet payload
    };

    ///! Helper class to communicate with and keep state for fingerprint sensors
    class Adafruit_Fingerprint {
    public:
    #if defined(__AVR__) || defined(ESP8266) || defined(FREEDOM_E300_HIFIVE1)
      Adafruit_Fingerprint(NeoSWSerial *ss, uint32_t password = 0x0);
    #endif
      Adafruit_Fingerprint(HardwareSerial *hs, uint32_t password = 0x0);

      void begin(uint32_t baud);

      boolean verifyPassword(void);
      uint8_t getImage(void);
      uint8_t image2Tz(uint8_t slot = 1);
      uint8_t createModel(void);

      uint8_t emptyDatabase(void);
      uint8_t storeModel(uint16_t id);
      uint8_t loadModel(uint16_t id);
      uint8_t getModel(void);
      uint8_t deleteModel(uint16_t id);
      uint8_t fingerFastSearch(void);
      uint8_t getTemplateCount(void);
      uint8_t setPassword(uint32_t password);
      void writeStructuredPacket(const Adafruit_Fingerprint_Packet &p);
      uint8_t getStructuredPacket(Adafruit_Fingerprint_Packet *p,
                                  uint16_t timeout = DEFAULTTIMEOUT);

      /// The matching location that is set by fingerFastSearch()
      uint16_t fingerID;
      /// The confidence of the fingerFastSearch() match, higher numbers are more
      /// confidents
      uint16_t confidence;
      /// The number of stored templates in the sensor, set by getTemplateCount()
      uint16_t templateCount;

    private:
      uint8_t checkPassword(void);
      uint32_t thePassword;
      uint32_t theAddress;
      uint8_t recvPacket[20];

      Stream *mySerial;
    #if defined(__AVR__) || defined(ESP8266) || defined(FREEDOM_E300_HIFIVE1)
      NeoSWSerial *swSerial;
    #endif
      HardwareSerial *hwSerial;
    };

    #endif

And the .cpp file:

    /***************************************************
      This is a library for our optical Fingerprint sensor

      Designed specifically to work with the Adafruit Fingerprint sensor
      ----> http://www.adafruit.com/products/751

      These displays use TTL Serial to communicate, 2 pins are required to
      interface
      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    #include "Adafruit_Fingerprint.h"

    //#define FINGERPRINT_DEBUG

    #if ARDUINO >= 100
    #define SERIAL_WRITE(...) mySerial->write(__VA_ARGS__)
    #else
    #define SERIAL_WRITE(...) mySerial->write(__VA_ARGS__, BYTE)
    #endif

    #define SERIAL_WRITE_U16(v)                                                    \
      SERIAL_WRITE((uint8_t)(v >> 8));                                             \
      SERIAL_WRITE((uint8_t)(v & 0xFF));

    #define GET_CMD_PACKET(...)                                                    \
      uint8_t data[] = {__VA_ARGS__};                                              \
      Adafruit_Fingerprint_Packet packet(FINGERPRINT_COMMANDPACKET, sizeof(data),  \
                                         data);                                    \
      writeStructuredPacket(packet);                                               \
      if (getStructuredPacket(&packet) != FINGERPRINT_OK)                          \
        return FINGERPRINT_PACKETRECIEVEERR;                                       \
      if (packet.type != FINGERPRINT_ACKPACKET)                                    \
        return FINGERPRINT_PACKETRECIEVEERR;

    #define SEND_CMD_PACKET(...)                                                   \
      GET_CMD_PACKET(__VA_ARGS__);                                                 \
      return packet.data[0];

    /***************************************************************************
     PUBLIC FUNCTIONS
     ***************************************************************************/

    #if defined(__AVR__) || defined(ESP8266) || defined(FREEDOM_E300_HIFIVE1)
    /**************************************************************************/
    /*!
        @brief  Instantiates sensor with Software Serial
        @param  ss Pointer to NeoSWSerial object
        @param  password 32-bit integer password (default is 0)
    */
    /**************************************************************************/
    Adafruit_Fingerprint::Adafruit_Fingerprint(NeoSWSerial *ss,
                                               uint32_t password) {
      thePassword = password;
      theAddress = 0xFFFFFFFF;

      hwSerial = NULL;
      swSerial = ss;
      mySerial = swSerial;
    }
    #endif

    /**************************************************************************/
    /*!
        @brief  Instantiates sensor with Hardware Serial
        @param  hs Pointer to HardwareSerial object
        @param  password 32-bit integer password (default is 0)

    */
    /**************************************************************************/
    Adafruit_Fingerprint::Adafruit_Fingerprint(HardwareSerial *hs,
                                               uint32_t password) {
      thePassword = password;
      theAddress = 0xFFFFFFFF;

    #if defined(__AVR__) || defined(ESP8266) || defined(FREEDOM_E300_HIFIVE1)
      swSerial = NULL;
    #endif
      hwSerial = hs;
      mySerial = hwSerial;
    }

    /**************************************************************************/
    /*!
        @brief  Initializes serial interface and baud rate
        @param  baudrate Sensor's UART baud rate (usually 57600, 9600 or 115200)
    */
    /**************************************************************************/
    void Adafruit_Fingerprint::begin(uint32_t baudrate) {
      delay(1000); // one second delay to let the sensor 'boot up'

      if (hwSerial)
        hwSerial->begin(baudrate);
    #if defined(__AVR__) || defined(ESP8266) || defined(FREEDOM_E300_HIFIVE1)
      if (swSerial)
        swSerial->begin(baudrate);
    #endif
    }

    /**************************************************************************/
    /*!
        @brief  Verifies the sensors' access password (default password is
       0x0000000). A good way to also check if the sensors is active and responding
        @returns True if password is correct
    */
    /**************************************************************************/
    boolean Adafruit_Fingerprint::verifyPassword(void) {
      return checkPassword() == FINGERPRINT_OK;
    }

    uint8_t Adafruit_Fingerprint::checkPassword(void) {
      GET_CMD_PACKET(FINGERPRINT_VERIFYPASSWORD, (uint8_t)(thePassword >> 24),
                     (uint8_t)(thePassword >> 16), (uint8_t)(thePassword >> 8),
                     (uint8_t)(thePassword & 0xFF));
      if (packet.data[0] == FINGERPRINT_OK)
        return FINGERPRINT_OK;
      else
        return FINGERPRINT_PACKETRECIEVEERR;
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to take an image of the finger pressed on surface
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_NOFINGER if no finger detected
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
        @returns FINGERPRINT_IMAGEFAIL on imaging error
    */
    /**************************************************************************/
    uint8_t Adafruit_Fingerprint::getImage(void) {
      SEND_CMD_PACKET(FINGERPRINT_GETIMAGE);
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to convert image to feature template
        @param slot Location to place feature template (put one in 1 and another in
       2 for verification to create model)
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_IMAGEMESS if image is too messy
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
        @returns FINGERPRINT_FEATUREFAIL on failure to identify
       fingerprint features
        @returns FINGERPRINT_INVALIDIMAGE on failure to identify
       fingerprint features
    */
    uint8_t Adafruit_Fingerprint::image2Tz(uint8_t slot) {
      SEND_CMD_PACKET(FINGERPRINT_IMAGE2TZ, slot);
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to take two print feature template and create a
       model
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
        @returns FINGERPRINT_ENROLLMISMATCH on mismatch of fingerprints
    */
    uint8_t Adafruit_Fingerprint::createModel(void) {
      SEND_CMD_PACKET(FINGERPRINT_REGMODEL);
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to store the calculated model for later matching
        @param   location The model location #
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_BADLOCATION if the location is invalid
        @returns FINGERPRINT_FLASHERR if the model couldn't be written
       to flash memory
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    uint8_t Adafruit_Fingerprint::storeModel(uint16_t location) {
      SEND_CMD_PACKET(FINGERPRINT_STORE, 0x01, (uint8_t)(location >> 8),
                      (uint8_t)(location & 0xFF));
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to load a fingerprint model from flash into buffer 1
        @param   location The model location #
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_BADLOCATION if the location is invalid
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    uint8_t Adafruit_Fingerprint::loadModel(uint16_t location) {
      SEND_CMD_PACKET(FINGERPRINT_LOAD, 0x01, (uint8_t)(location >> 8),
                      (uint8_t)(location & 0xFF));
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to transfer 256-byte fingerprint template from the
       buffer to the UART
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    uint8_t Adafruit_Fingerprint::getModel(void) {
      SEND_CMD_PACKET(FINGERPRINT_UPLOAD, 0x01);
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to delete a model in memory
        @param   location The model location #
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_BADLOCATION if the location is invalid
        @returns FINGERPRINT_FLASHERR if the model couldn't be written
       to flash memory
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    uint8_t Adafruit_Fingerprint::deleteModel(uint16_t location) {
      SEND_CMD_PACKET(FINGERPRINT_DELETE, (uint8_t)(location >> 8),
                      (uint8_t)(location & 0xFF), 0x00, 0x01);
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to delete ALL models in memory
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_BADLOCATION if the location is invalid
        @returns FINGERPRINT_FLASHERR if the model couldn't be written
       to flash memory
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    uint8_t Adafruit_Fingerprint::emptyDatabase(void) {
      SEND_CMD_PACKET(FINGERPRINT_EMPTY);
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor to search the current slot 1 fingerprint features to
       match saved templates. The matching location is stored in fingerID and
       the matching confidence in confidence
        @returns FINGERPRINT_OK on fingerprint match success
        @returns FINGERPRINT_NOTFOUND no match made
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    /**************************************************************************/
    uint8_t Adafruit_Fingerprint::fingerFastSearch(void) {
      // high speed search of slot #1 starting at page 0x0000 and page #0x00A3
      GET_CMD_PACKET(FINGERPRINT_HISPEEDSEARCH, 0x01, 0x00, 0x00, 0x00, 0xA3);
      fingerID = 0xFFFF;
      confidence = 0xFFFF;

      fingerID = packet.data[1];
      fingerID <<= 8;
      fingerID |= packet.data[2];

      confidence = packet.data[3];
      confidence <<= 8;
      confidence |= packet.data[4];

      return packet.data[0];
    }

    /**************************************************************************/
    /*!
        @brief   Ask the sensor for the number of templates stored in memory. The
       number is stored in templateCount on success.
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    /**************************************************************************/
    uint8_t Adafruit_Fingerprint::getTemplateCount(void) {
      GET_CMD_PACKET(FINGERPRINT_TEMPLATECOUNT);

      templateCount = packet.data[1];
      templateCount <<= 8;
      templateCount |= packet.data[2];

      return packet.data[0];
    }

    /**************************************************************************/
    /*!
        @brief   Set the password on the sensor (future communication will require
       password verification so don't forget it!!!)
        @param   password 32-bit password code
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_PACKETRECIEVEERR on communication error
    */
    /**************************************************************************/
    uint8_t Adafruit_Fingerprint::setPassword(uint32_t password) {
      SEND_CMD_PACKET(FINGERPRINT_SETPASSWORD, (password >> 24), (password >> 16),
                      (password >> 8), password);
    }

    /**************************************************************************/
    /*!
        @brief   Helper function to process a packet and send it over UART to the
       sensor
        @param   packet A structure containing the bytes to transmit
    */
    /**************************************************************************/

    void Adafruit_Fingerprint::writeStructuredPacket(
        const Adafruit_Fingerprint_Packet &packet) {
      SERIAL_WRITE_U16(packet.start_code);
      SERIAL_WRITE(packet.address[0]);
      SERIAL_WRITE(packet.address[1]);
      SERIAL_WRITE(packet.address[2]);
      SERIAL_WRITE(packet.address[3]);
      SERIAL_WRITE(packet.type);

      uint16_t wire_length = packet.length + 2;
      SERIAL_WRITE_U16(wire_length);

      uint16_t sum = ((wire_length) >> 8) + ((wire_length)&0xFF) + packet.type;
      for (uint8_t i = 0; i < packet.length; i++) {
        SERIAL_WRITE(packet.data[i]);
        sum += packet.data[i];
      }

      SERIAL_WRITE_U16(sum);
      return;
    }

    /**************************************************************************/
    /*!
        @brief   Helper function to receive data over UART from the sensor and
       process it into a packet
        @param   packet A structure containing the bytes received
        @param   timeout how many milliseconds we're willing to wait
        @returns FINGERPRINT_OK on success
        @returns FINGERPRINT_TIMEOUT or
       FINGERPRINT_BADPACKET on failure
    */
    /**************************************************************************/
    uint8_t
    Adafruit_Fingerprint::getStructuredPacket(Adafruit_Fingerprint_Packet *packet,
                                              uint16_t timeout) {
      uint8_t byte;
      uint16_t idx = 0, timer = 0;

      while (true) {
        while (!mySerial->available()) {
          delay(1);
          timer++;
          if (timer >= timeout) {
    #ifdef FINGERPRINT_DEBUG
            Serial.println("Timed out");
    #endif
            return FINGERPRINT_TIMEOUT;
          }
        }
        byte = mySerial->read();
    #ifdef FINGERPRINT_DEBUG
        Serial.print("<- 0x");
        Serial.println(byte, HEX);
    #endif
        switch (idx) {
        case 0:
          if (byte != (FINGERPRINT_STARTCODE >> 8))
            continue;
          packet->start_code = (uint16_t)byte << 8;
          break;
        case 1:
          packet->start_code |= byte;
          if (packet->start_code != FINGERPRINT_STARTCODE)
            return FINGERPRINT_BADPACKET;
          break;
        case 2:
        case 3:
        case 4:
        case 5:
          packet->address[idx - 2] = byte;
          break;
        case 6:
          packet->type = byte;
          break;
        case 7:
          packet->length = (uint16_t)byte << 8;
          break;
        case 8:
          packet->length |= byte;
          break;
        default:
          packet->data[idx - 9] = byte;
          if ((idx - 8) == packet->length)
            return FINGERPRINT_OK;
          break;
        }
        idx++;
      }
      // Shouldn't get here so...
      return FINGERPRINT_BADPACKET;
    }

Is what I'm doing at all possible or am I just doing it wrongly?

body:
I got it to work with NeoSWSerial and some help from AdaFruit. For those in the future:

 1. Write the blank example sketch to the arduino
 2. Go to device manager and switch the COM port that the arduino is connected to COM1 (Right click > Properties) - This applies even if you're using an FTDI breakout
 3. Download and extract the [SFG Demo Software][1]
 4. Click Open Device and select COM1
 5. Change the baud rate (lower left corner) to 19200 - anything else seems unreliable (from my testing)
 6. Replace all instances of SoftwareSerial to NeoSWSerial in the .cpp and .h files as well as your sketch. Change the finger.begin(57600) to finger.begin(19200) in the example sketches and that's it

If it doesn't work go back to device manager and change the baud rate on the COM port to 57600
Hope this helps someone!

  [1]: https://learn.adafruit.com/adafruit-optical-fingerprint-sensor/downloads


message:
HM-10 BLE controller is not responding to some AT commands

I have HM-10 BLE controller and it is not responding to some AT commands which I need to use.

AT commands which don't work:

 - `AT+TYPE2` returns `+TYPE=0`
 - `AT+VERR?` not responding
 - `AT+VERS?` not responding
 - `AT+RESTART` not responding
 - `AT` not responding but `AT+`responds with `OK`
 - `AT+VERSION` responding with `MLT-BT05-V4.1`

The most important command for me is `AT+TYPE2` because even if I set pin with command `AT+PIN112233`, in my Android App, `AlertDialog` with `password` field is not activated during connection with `bleGatt = bleDevice.connectGatt(this, true, bleGattCallback)` function.

I even tried to call `createBond()` function on this device, but it is not returning anything. I need to activate pairing with password with `AT+TYPE2` but its always returning 0 which is default connection without password and pairing method.

I'm not sure if I have some bugged HM-10 controller but I cant even reset it to default settings.
It is working fine with transfering data by characteristics but other stuff is not working.

I've used some weird iterating function to print out AT+HELP commands for this controller and AT+TYPE is not listed there as a command. That means I cant set pairing method? What kind of BLE device has pairing disabled and there is not option to set up at least password?

Here are my commands

    21:01:19.739 ->  Command             Description
    21:01:19.880 ->  ----------------------------------------------------------------
    21:01:19.949 ->  AT                  Check if the command terminal work normally
    21:01:20.054 ->  AT+RESET            Software reboot
    21:01:20.159 ->  AT+VERSION          Get firmware, bluetooth, HCI and LMP version
    21:01:20.271 ->  AT+HELP             List all the commands
    21:01:20.365 ->  AT+NAME             Get/Set local device name
    21:01:20.459 ->  AT+PIN              Get/Set pin code for pairing
    21:01:20.552 ->  AT+PASS             Get/Set pin code for pairing
    21:01:20.646 ->  AT+BAUD             Get/Set baud rate
    21:01:20.740 ->  AT+LADDR            Get local bluetooth address
    21:01:20.880 ->  AT+ADDR             Get local bluetooth address
    21:01:20.950 ->  AT+DEFAULT          Restore factory default
    21:01:21.054 ->  AT+RENEW            Restore factory default
    21:01:21.157 ->  AT+STATE            Get current state
    21:01:21.271 ->  AT+PWRM             Get/Set power on mode(low power)
    21:01:21.365 ->  AT+POWE             Get/Set RF transmit power
    21:01:21.459 ->  AT+SLEEP            Sleep mode
    21:01:21.553 ->  AT+ROLE             Get/Set current role.
    21:01:21.693 ->  AT+PARI             Get/Set UART parity bit.
    21:01:21.787 ->  AT+STOP             Get/Set UART stop bit.
    21:01:21.834 ->  AT+START            System start working.
    21:01:21.952 ->  AT+IMME             System wait for command when power on.
    21:01:22.056 ->  AT+IBEA             Switch iBeacon mode.
    21:01:22.161 ->  AT+IBE0             Set iBeacon UUID 0.
    21:01:22.264 ->  AT+IBE1             Set iBeacon UUID 1.
    21:01:22.381 ->  AT+IBE2             Set iBeacon UUID 2.
    21:01:22.475 ->  AT+IBE3             Set iBeacon UUID 3.
    21:01:22.569 ->  AT+MARJ             Set iBeacon MARJ .
    21:01:22.663 ->  AT+MINO             Set iBeacon MINO .
    21:01:22.756 ->  AT+MEA              Set iBeacon MEA .
    21:01:22.850 ->  AT+NOTI             Notify connection event .
    21:01:22.967 ->  AT+UUID             Get/Set system SERVER_UUID .
    21:01:23.071 ->  AT+CHAR             Get/Set system CHAR_UUID .
    21:01:23.174 ->  -----------------------------------------------------------------
    21:01:23.257 ->  Note: (M) = The command support slave mode only.

body:
same as me... clone of a hm10.
not very much info on this board.
at command doesn't works when they are in caps ..
no need ? or = after command.
you can paired with at+connX (x is the device number, the first founded is 1. the second is 2, etc etc).
it cannot auto connect even if you paired them before.
not much range (7 meter).


message:
It is possible an Arduino generate 3d graphics on tft or vga

It is possible to an Arduino render 3d graphics like very low polygonal 3d models or generating lighting efects non realtime shadows or realtime shadows and reflections. Rendering like first 3d video game consoles.
Someone can ask why you don't use an Rasberry Pi. Beacuse Linux can be more complex. Also Rasberry Pi is a computer runs Linux .Linux is hard and some people can say you can install Windows but it doesn't give freedom as Arduino on Arduino you have more control on system.It doesn't run operating system but Rasberry pi runs and you needed write programs for it. You can't do much  anything ( at least i know) than Linux or Windows will allow.

My goal was running very basic 3d graphics on a Vga.
Theres no rule it can be like old dos games.Fake 3d effect like distorting sprites to look like 3d and rotate them move change coordinates change camera position like a 3d but it's actually generating fake depth.
Must camera position controllable . Like a video game.

Sprites,effects are completely pre rendered. Only realtime rendered thing was distorting sprites by camera position. Changing room (Square area will reset view that will make after another room it would show another room).

Is there a library can done that?

Your solution can be for another Arduinos.

Your solution can be Arduino dependent. Like only works for due,mega etc.

Theres a vga library for Due supports 256 colors your solution can use this library problary called DueVGA

body:
On AVR based Arduinos: No, definitely not. It is possible to create a VGA signal, but only with very limited resolution and few colors (like 4 or so) and also a framerate, that will not be enough. Also they all have too few memory.

It might be possible on the Due (don't have much experience with it), but it is still a bad choice for a platform (also partly because the Due is in general such a bad designed board with no good documentation).

> Is there a library can done that?

I don't think, that you will find any library doing all what you want. You might find libraries, that help you draw on the display, but you will do all the hard stuff (creating and loading sprites, distorting them, animating them) yourself. This is, because Arduino is a bad choice for such a project.

Also: In the title you mentioned TFT. I guess you meant one of the TFT display modules, that you can connect to Arduinos. Forget about that. They are connected over rather slow serial data interfaces (not meaning the Arduino `Serial` here, but serial interfaces like I2C or SPI). You won't get a sufficient frame rate with them.

---

I would oppose your arguments against the Raspberry Pi. Sure, it has an OS, but that also means, that it can make use of a variety of languages and frameworks. You are not bound to plain C/C++. You can use the language or framework, that best suites your needs. That can be a bit complex at first to find the right one. But thats, because your project is complex. What you are describing is a very complex task, when you cannot rely on others, that have already implemented the hard stuff (which would be the case for the Arduino).

Also a Raspberry Pi has plenty of RAM and plenty of storage space. It runs at high speed and is actually capable of outputting video with a good framerate.

Without wanting to offend you: I think, as you are asking this question here, you are not qualified enough yet to do such a project on an Arduino. There are insanely capable people out there (wouldn't count myself to them), who do incredible things with Arduinos by milking the very last drop of resources out of them. But they are doing it for the grind, not for having a functioning product at the end. I guess you want this to work good at the end, without needing you to work on it for many years. Then you are result-focused and should choose the correct platform for this. A computer (like the Pi) will be easier.

---

>  Rasberry Pi had lot of things but some of them are unnecessary.

Yes, but is that really a problem? Is the unused potential really a no-go for the project? You could say the same thing about an Arduino. It has a lot of peripherals build in (depending on type Timers, Comparators, ADCs, DACs, several communication interfaces, power management peripherals, ...). Almost no project uses all of them. But that's simply the difference between general purpose chips/boards (like all Arduinos or Raspberry Pis) and custom made chips for a single purpose. If (!) a fitting chip for your project exists, that really only has what you need, it will most likely be very expensive. Chips for a single very narrow purpose have a very narrow target group, thus are more expensive (simple economy here). Companies have formally nearly everytime designed their own chips for gaming consoles (which is way beyond your current scope), like PS1 or N64. Current gaming consoles rely often on modified standard hardware, also because it is cheaper. The really old gaming consoles used the generic electronical chips, which means, that you didn't have one single programmable chip. Instead lots of the logic was build into the electronic design.

So you will always have some excessive features, that are not used. Why would you want to remove them from the project, just for the fuzzy goal of not wasting features. It will make your project only more complex and expensive. You will gain nearly nothing from minimizing the resources. This is a hobby project, not for selling it.

> In rasberry pi you just writing a computer program.You don't have much control like arduino

That depends on what type of control you mean. On a computer you are writing code on a higher level of abstraction. That also makes it easier to do complex things, since you can rely on the low level programming of others. What control do you want to have over the system, that you don't have on a computer like the Pi? Do you think, you can program better display drivers or graphic renderers, than all the other people? Then you can still do that on the Pi. A Pi also gives you control over the GPIO pins, which let's you do many hardware things, that you can also do on an Arduino.

Also Linux is open source. If you think, you need more low level interaction with the hardware (cannot think of a reason for needing it), then you can build your own OS, which gives you the needed freedom. Sure, that is very complex. But when you are able to use the low level programming, then you are also able to change the OS.

---

You seem to already have chosen the Arduino for your project. I, like others, have advised you to use a Pi instead to make it a lot easier and better. It is up to you, if you want to believe us or not. All in all I'm still not convinced, that you are able to pull that off on the Arduino platform, while still getting good results. You are simply not at that point of knowledge yet. You write confidently about the problems with an OS, while you don't seem to have a concept about the exact structure of these problems and how they impact you. We will not prevent you from doing it the hard way. Please for free to choose your own way.


body:
# VGA

I suggest you build the famous [world's worst video card](https://eater.net/vga). It's a great project and you'll definitely learn something when building it.

That graphics card uses only 2 bit per base color, which is 6 bits in total, or 64 colors. The resolution of the graphics card is 100x75 pixels. An image can basically become as good as

[![Finch][1]][1]

That picture is still 100x75 = 7.5 kB in size. That means it does not fit into the 2 kB of RAM of an Arduino Uno.

To clock the graphics card, Ben Eater uses a 10 MHz crystal to get the timing right. That means, your Arduino needs to output one color at a speed of 10 MHz. That's clearly not feasible for an Arduino Uno running at 16 MHz.

However, an Arduino Uno is nothing without some hardware attached. You could try to calculate the 3D graphics on the Arduino and write the results into an EEPROM (just like Ben Eater's graphics card) and let the EEPROM handle the output of the colors. That way, you could certainly generate single images. The frame rate will definitely not be high.

But: your request is not far fetched. My first computer, an Apple IIe was running at 1 MHz speed - but at least it had 64 kB of RAM. It could do all sorts of stuff, although I can't remember a 3D game. Using an Arduino Due with 84 MHz and 96 kB of RAM should be a realistic approach - and probably the reason why DueVGA exists.

# TFT

A TFT display already has its own memory, so you needn't worry about that aspect. People already did 3D rendering, although they were going through a lot of problems that I mentioned for VGA before. It requires a lot of optimization. A library is the [ATmega328 Tiny 3D Engine](https://github.com/mrt-prodz/ATmega328-Tiny-3D-Engine).

With shading it seems to render up to 3 frames per second on an Arduino, which is likely not enough to for smooth interaction.

# Raspberry Pi

> Linux is hard

Some Linuxes are. Especially Kali Linux. But Raspbian is really a good OS for the Raspberry Pi. We are teaching internships Linux + Shell + Python in 1 week (like [this project](https://github.com/BogyMitutoyoCTL/AI-Preparation)). It's enough to focus on the programming. Not much configuration needed.

> You can't do much anything ( at least i know) than Linux or Windows will allow.

That might be true. However, I am developing software that runs on operating systems since 1996 and have never had the feeling that the operating system restricts me from doing something. In the opposite: the OS provides features that would be very hard to implement on my own.

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


body:
While there is no VGA library for Arduinos with AVR, there is one for ESP32: [ESP32 VGA Library](https://github.com/bitluni/ESP32Lib).
It makes heavy use of the Hardware capabilities like I2S that are not present in in Arduino.


body:
I disagree with your premise. If you use a high-end Arduino, like one of the ones based on an ARM processor, and you optimize the snot out of it, you might be able to generate crude VGA level graphics, and gin up some 3D looking images. But expect to spend a lot of time on very fussy timing code that requires a LOT of expertise to get right.

(An Arduino does not have any display driver at all.)

You want a device that can output video through hardware. A Raspberry Pi is a much, much better choice. Sure, it runs UNIX. UNIX isn't going to bite you. Roll up your sleeves and


body:
You can definitely render 3D graphics on an Arduino-based MCU & TFT and [I have done exactly that with Teensy][1].

It requires quite a bit of work to implement software rasterizer though and I'm not aware of an off-the-shelf 3D library you could use. I would think that someone has written a 3D graphics iib though, so might be good to scour [GitHub][2] if you don't want to write a rasterizer yourself.

There are plenty of different TFT options with both SPI (serial) and 8/16bit parallel interfaces you can use and have decent frame rate. E.g. with Teensy you can update a 320x240x16bpp screen over SPI at ~30fps. You can also pass SPI data transfer to DMA to free spending MCU cycles for it if your MCU supports it. With parallel interface you can bit bang the data to TFT faster and have potentially higher frame rate, but then you have to waste MCU cycles for the data transmission.

Newer Teensy models has plenty of RAM (1MB) for 3D rendering but it can be quite challenging to render 3D graphics on some MCU's with only few kilobytes of RAM. I'm using tiled rendering, which renders a frame in small tiles (e.g. 64x64px) and thus doesn't need to maintain the whole frame & depth buffers in memory. Because of this I was able to get the [3D renderer running on Teensy LC][3], which has only 8kb of RAM, but it's much slower and simpler 3D model. I also store the 3D assets (geometry, textures) in the MCU flash in format that can be directly used for rendering to save RAM.

You can also implement [texture sampling on MCU][4], which opens possibility to implement various different effects, like sprites you mentioned.

  [1]: https://www.youtube.com/watch?v=Xs_5Sv9oBtk
  [2]: https://github.com/
  [3]: https://www.youtube.com/watch?v=g2QsMjPYEzo
  [4]: https://www.youtube.com/watch?v=z9uMW2oH0yI


message:
Arduino as USB HID is slowed down when PC doesn't read events

I have an Arduino Micro that is acting as a HID device for a Linux PC.

I use this call to send the HID values:

`HID().SendReport(1, _values, sizeof(_values));`

This works in principle, but I noticed this issue:

If my Linux PC is not actively reading the events from the Arduino, then the Arduino is slowed down. My rotary encoders are missing signals, is one symptom.

But as soon as I read the events with my Linux PC, the Arduino loop() runs at full speed again.

I suspect that this is due to recv/send time out delays in the USB core code? Because I noticed this in USBCore.cpp:

`        u8 timeout = 250;               // 250ms timeout on send? TODO`

Anyway, I tried to solve this issue in the following manners:

Check for configuration and suspension with:
```
     if (USBDevice.configured())
      if (!USBDevice.isSuspended())
         ...
```

Which did not work.

I also tried monitoring the increments of the frame number:

```
  // See if USB shows activity.
  static uint8_t prev_fr_num = UDFNUML;
  static uint8_t num_times_idle = 0;
  uint8_t fr_num = UDFNUML;
  if (fr_num == prev_fr_num )
  {
    if (num_times_idle < 255)
      num_times_idle++;
  }
  else
  {
    num_times_idle = 0;
    prev_fr_num = fr_num;
  }
```

And then only send if num_times_idle is smaller than a threshold. Again, this did not help.

The only way to make it fast, is by reading the events with linux, like so:

`$ jstest /dev/input/js0`

or alternatively:

`$ evtest /dev/input/event5`

How can I have the USB HID stuff not slow down my loop code when the PC is not paying attention?

Thanks!

  Bram

body:
For those that hit the same issue, here is how I solved it:

Expose the `USB_SendSpace()` information in the HID interface by editing

**/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.cpp**

```
u8 HID_::SendSpace(void)
{
        return USB_SendSpace(pluggedEndpoint);
}
```

And adding the interface to `class HID_` in:

**/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.h**

That way, before calling `HID().SendReport()` you can check for send buffer space available by calling the `HID().SendSpace()` method.

If there is no space, just skip the SendReport() calls, and the Arduino loop() will no longer be slowed down by time outs.


message:
Interrupt every second on ATTiny84 (and sleep the rest)

I'm building a digital watch just like in [this post](https://arduino.stackexchange.com/questions/50733/is-there-a-way-to-disable-modules-like-adc-without-a-sleep-mode/50734), except I'm using an ATTiny84. However, the ATTiny84 doesn't have an asynchronous Timer2 like the ATMega328 and does not have a power save mode, so it cannot wake up from the Timer2 interrupt as is suggested in that post.

I need to increment my 'seconds' counter every second, and I need to do it precisely so I don't lose/gain time (so I can't use the watchdog timer which, as I understand, does not use the crystal oscillator but rather its own imprecise clock). I was planning on just keeping the CPU on and using an external crystal, but it seems that that takes a lot of power (~3mA). Even with the SLEEP_MODE_IDLE, I could only get the current draw down to around (~1.2mA).

Like Nick Gammon suggested in that post, I feel like the real solution is to sleep when not changing the counter. Is there any way to wake up after a precise amount of time in the POWER_DOWN or STAND_BY modes?

body:
> Is there any way to wake up after a precise amount of time in the
> POWER\_DOWN or STAND\_BY modes?

I'm afraid not. You will have to use a timer. Since the ATtiny84 does
not have an asynchronous timer, you will have to keep your timer
clocked. This means the clkIO clock domain has to stay
active. Now, take a look at the table “_Active Clock Domains and Wake-up
Sources in Different Sleep Modes_”, on page 33 of the [ATtiny84
datasheet][datasheet]. It shown that “Idle” is the _only_ sleep mode
that keeps this clock domain active.

> Even with the SLEEP\_MODE\_IDLE, I could only get the current draw
> down to around (~1.2mA).

There are ways to bring this down. First, there is a collection of
functions named [`power_*_disable()` in the avr-libc][pwr]. You can use
these to power down every single peripheral except the one timer that
you will be using.

Most importantly, you can save power by reducing the clock speed. Since
these devices have extremely little leakage current, the current draw is
roughly proportional to the clock frequency. You can then achieve huge
power savings by drastically reducing that frequency. Obviously, your
processing power will also suffer, but this may not be an issue for a
simple binary clock.

I think the best option for you is to clock your ATtiny84 off a
32.768 kHz watch crystal. See the section
6.2.4 – _Low-Frequency Crystal Oscillator_ in the datasheet.
These crystals can be very accurate, as they are specifically designed
for time keeping. And the frequency is so low that the current draw from
the MCU will likely be negligible compared to whatever other components
are in your clock.

[datasheet]: http://ww1.microchip.com/downloads/en/devicedoc/doc8006.pdf
[pwr]: https://www.nongnu.org/avr-libc/user-manual/group__avr__power.html

**Edit**: answering the question in the comment.

> Wouldn't waking from idle still use the watchdog timer though? Or is
> there a way to wake up based on the 32.768 kHz crystal?

As the watchdog timer is way too inaccurate, it is of no use to you.
Instead, you would use either Timer 0 or Timer 1, and configure it to
deliver an interrupt every 32,768 CPU cycles. This interrupt will
be your 1 Hz wakeup source.

You can do this with either timer, in either CTC or fast PWM mode. You
have to configure the prescaler and the TOP value such that

prescaler\_factor × (TOP + 1) = 32,768

Then, enable the relevant interrupt, and define the corresponding ISR
that will advance your clock by one second.


message:
Using the LED pin for input

I have an Arduino-like device with few GPIO pins (DigiSpark clone). It is based on an 8-pin AtTiny85 IC so there are Power, Ground and six other pins, two of those six are being used for USB keyboard simulation which leaves 4 GPIO which I want to connect 4 buttons to with minimal circuitry. The normal way to do this is to enable the internal pullups and have the buttons connect the pin to ground. This works well for most pins.

The problem is the equivalent to Pin 13 (Pin 1 in this case) which is connected via a resistor and LED to ground. The internal pullup is too weak to raise the voltage enough. Consequently that pin always appears to be in a "button pressed" state.

One solution is to cut the tracks connecting the LED, but the board is so tiny and crowded that I doubt I have the eyesight and steadiness of hand to do this.

[![DigiSpark PCB][1]][1]
Problematic resistor + LED are at bottom right of AtTiny85 IC

It occurs to me I could either

1. Add an external pullup to this input,
2. Change the button wiring so when pressed, it connects the pin to 5v. Change the code to look for high, not low.

Are there any problems with either of these approaches?

  [1]: https://i.stack.imgur.com/hK5y7.jpg
  [2]: https://i.stack.imgur.com/9KDJN.jpg

body: In the end, stimulated by Majenko's advice to desolder the LED,  I instead carefully studied the PCB layout online, checked that it corresponded to my PCB, checked the location of nearby traces I didn't want to cut and then used multiple magnifying glasses and a fresh blade in my smallest utility knife and carefully cut the track leading from the LED to the IC. All was well.


message:
Bicycle Tail Light project

For my college course we currently have to carry out a project of our own choice.
I chose to make a Tail light system, with strobing indicators, fog-light and brake-light.

The lighting uses Neopixel strips and rings, with the indicator sections consisting of 2 neopixel strip 6 (in parallel); the fog light using a neopixel jewel; and the brake light using a neopixel ring 16.

The indicators need to strobe outward from the centre of the device (in the desired direction, left/right) based on a button input. The fog-light should turn on when the device is activated by switch, and the brake-light will turn on when receiving an input from another button.

I've only ever coded using Python during GCSE and can't wrap my head around Arduino code. Currently using tinkercad for creating this as I don't have any arduino kit, and don't want to spend out the money on unneeded components.

Any help is appreciated, and if a link to the tinkercad circuit would be useful let me know.

body:
Break down your project into steps, both hardware and software, and tackle a step at a time.

First do a block diagram of the system, showing the different components, the layout of the control buttons, etc.

Then map out the desired behavior, perhaps using a flowchart. What should it do when you first turn it on? How will it respond to different button inputs? Will it continue to flash in the current pattern indefinitely until there's another input? Will there be a cancel button?

Then read up on how to power and control NeoPixel LEDs. I believe they use I2C? Are there any NeoPixel libraries you can use?

You might then try using a circuit simulator to create a virtual prototype of your circuit. Figure out how big a battery & voltage regulator you're going to need. (If you're running off of batteries you should use a switching or "buck" type voltage regulator rather than a linear voltage regulator since they are much more efficient. Just make sure you pick a regulator that can provide enough current for all your LEDs plus your Arduino, with a little extra left over.))

Once you get a virtual circuit working, it's time to use real hardware.

For a bike tail-light, you should think about how to make it weather-proof. are there waterproof enclosures you can use? What about waterproof NeoPixels? If there are no waterproof NeoPixels, what about waterproof enclosures with clear covers?

Buy the Arduino you're going to use, and at least a few of your NeoPixels. Work out how to control and flash a single LED. Then gradually add complexity to your project until you get it working.


message:
2 SPI devices conflict

I want to connect a W5500 ethernet Module and an SD card module to arduino Uno using SPI (with different CS pins of course). When connected separately they work fine but when connected in the same circuit the ethernet module doesn't get a correct ip address and always gets an address 255.255.255.255. To me the ethernet module is the likely culprit as the SD card module works without problem even when the ethernet module is also connected.

Tried using Ethernet & Ethernet2 libraries but no difference. Tried manually assigning the IP address but it won't work. I have even set the CS pins HIGH in the setup before calling SD.begin & Ethernet.begin() to avoid both components "listening" at the same time but it still doesn't work. How can I fix it?

Here is the sketch I am working with. Although it doesn't use SD module but as mentioned above if SD module is connected in the circuit, ethernet module doesn't get incorrect ip address

    #include <SPI.h>
    #include <Ethernet2.h>

    //IPAddress ip(192, 168, 1, 22);

    // MAC address just has to be unique. This should work
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    EthernetServer server(80);

    void setup()
    {

      pinMode(8, OUTPUT); // SD module CS
      digitalWrite(8, HIGH);
      pinMode(10, OUTPUT); // Ethernet module CS
      digitalWrite(10, HIGH);
      delay(1);

      Serial.begin(9600);
      Ethernet.begin(mac);
      server.begin();
      Serial.print("Server started on: ");
      Serial.println(Ethernet.localIP());
    }

    void loop()
    {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client)
      {
        while (client.connected())
        {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          // send the body
          client.println("");
          client.println("
Arduino Server
");
          client.print("
A0=");
          client.print(analogRead(0));
          client.println("
");
          client.print("
millis=");
          client.print(millis());
          client.println("
");
          client.println("");
          client.stop();
        }
        delay(1);
      }
    }

Another sketch with reference to both SD and Ethernet Libraries

    #include <SPI.h>
    #include <Ethernet.h>
    #include <SD.h>

    byte mac[] = { 0x00, 0xC3, 0xA2, 0xE6, 0x3D, 0x57 };
    byte LED = 2;
    char wServer[] = "media.wizards.com";
    char wFile[] = "/images/magic/tcg/resources/rules/MagicCompRules_20140601.pdf";

    EthernetClient myClient;

    void setup() {
      //D53 on an Arduino Mega must be an output.
      pinMode(53, OUTPUT);

      pinMode(LED, OUTPUT);

      Serial.begin(9600);
      while (!Serial);

      Serial.print("Establishing network connection... ");

      if (Ethernet.begin(mac) == 0) {
        Serial.println("FAILED!");
        while (true) {
          digitalWrite(LED, HIGH);
          delay(500);
          digitalWrite(LED, LOW);
          delay(500);
        }
      }
      else {
        Serial.println("OK!");
      }
    }

    void loop() {

      Serial.print("Connecting to ");
      Serial.print(wServer);
      Serial.print("... ");

      if (myClient.connect(wServer, 80) == 1) {
        Serial.println("OK!");

        myClient.print("GET ");
        myClient.print(wFile);
        myClient.println(" HTTP/1.0");
        myClient.print("Host: ");
        myClient.println(wServer);
        myClient.println();

        if (SD.begin(8)) {
          if (SD.exists("MAGIC.PDF"))
            SD.remove("MAGIC.PDF");

          Serial.print("Saving response... ");
          digitalWrite(LED, HIGH);

          File dd = SD.open("MAGIC.PDF", FILE_WRITE);

          char lc;
          while (myClient.connected()) {
            if (myClient.available()) {
              char nc = myClient.read();
              if ((lc == 10) && (nc == 13)) {
                while (myClient.available() == 0);
                myClient.read();
                break;
              }
              else
                lc = nc;
            }
          }

          while (myClient.connected()) {
            if (myClient.available() > 0) {
              dd.write(myClient.read());
            }
          }

          dd.close();
          delay(500);
          Serial.println("OK");
          digitalWrite(LED, LOW);
        }
        else
          Serial.println("No SD card detected!");

        myClient.stop();
      }
      else
        Serial.println("FAILED!");

      delay(3600000);
      asm volatile(" jmp 0");

body:
I had the same problem with my SD card module.

I don't have too much knowledge about all details, but it is related that most SD card modules (the simple ones) do not have tri-state functionality, meaning they cannot cope with multiple SPI devices on the same bus.

Sadly, the Arduino has only one SPI connection, but there are solutions:

- There exist tri-state buffers which you can use  (somewhere in the CD or 74HC range). See comment of hcheung: use e.g. an 74AHC125  MISO tri-state buffer.
- However, another solution is to use e.g. an SD card shield, something like https://boutique.semageek.com/en/1445-sd-storage-shield-with-rtc-clock-for-arduino.html

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

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


message:
Boost an audio signal for analog read - Envelope Detector

I'm working on my first Arduino project and I have a sensitivity issue.

I'm building a module to listen to an audio signal and to start the power source of my speaker with a relay. Everything seems to work fine, but if I drop the volume of my sound, the analog pin doesn't record values (at maximum volume, it peaks at around 50, which is not a lot).

I thought about getting a capacitor but I'm really not sure on what I should get and how the wiring should be done.

body:
it sounds like what you are wanting to do is to detect a minimum threshold of sound so that your speaker power source can be turned on when an audio signal is playing.

You need to amplify your signal while also avoiding voltages that exceed the maximum input specification and also don't go negative. One way to accomplish this is with an operational amplifier (op-amp) circuit. A specific type will accomplish all three requirements. An op-amp that is powered by a single-sided supply, for example +5V and ground, will prevent negative voltages and limit the maximum voltage exceeding what the Arduino can take.

For your application, you don't really care about making a high-quality audio amplifier. You care about not distorting the signal (music) that you are monitoring and detecting a threshold level. Op-amps are good because they have high impedance inputs (they don't draw much (or any) current from your music signal) and they work with few external components.

A classic text for learning about electronics is [Horowitz and Hill](https://en.wikipedia.org/wiki/The_Art_of_Electronics). Alternatively, you can find references for circuit designs on-line with appropriate searches. For any op-amp that you buy, you can get a datasheet that tells you how to use it. The following [reference](http://www.ti.com/lit/an/sloa030a/sloa030a.pdf?ts=1588824875818) goes into detail (maybe too much) about single supply op-amps.

Circuits (and search terms) that you might find useful are op-amp follower, single supply, bias, and capacitive coupling. You'll need to purchase components. A good supplier is [DigiKey](https://www.digikey.com/). DigiKey has an on-line catalog that allows you to do a parametric search to identify the components that you need. You'll need a breadboard, resistors, capacitors, and the op-amp in a dual-inline package (DIP).

One [search](https://www.digikey.com/products/en/integrated-circuits-ics/linear-amplifiers-instrumentation-op-amps-buffer-amps/687?k=op+amp&k=single+supply&k=DIP&k=&pkeyword=op+amp&sv=0&pv7=6&pv161=316418&pv2094=i2&sf=0&FV=-8|687&quantity=&ColumnSort=0&page=1&pageSize=25) filters the list of possibilities from tens of thousands to a reasonable number. The LM833 [Datasheet here](http://www.ti.com/lit/ds/symlink/lm833.pdf?ts=1588827357359) is a reasonable choice.

Test equipment, like a single generator and oscilloscope can be very helpful when building amplifiers. You might be able to digitize your amplified signal with your Arduino if you don't have access to test equipment.


body:
What you're looking for is called a peak detector, or probably better in your case - an envelope detector. Pass this through an op-amp with adjustable gain to let you tune your sensitivity. R3 - your potentiometer will let you adjust the sensitivity.Your gain will be

<img src="https://latex.codecogs.com/gif.latex?V_{out}=&space;V_{in}(1+\frac{R_2}{R_3})" title="V_{out}= V_{in}(1+\frac{R_2}{R_3})" />.

Set Vdd to 5V and common ground with your Arduino.

It's unlikely your audio source is generating too much voltage given you're saying its not registering - but in the unlikely event you're above 5V put a reverse biased Zener diode in parallel with your capacitor to clamp voltage to 5V

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

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

<!-- End schematic -->

Hit simulate to see what playing with values does!

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

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