text:
How to extract code on one DT-06 board to another board?
I have two DT-06 boards DT06 datasheet.

The board stock firmware provides Web UI for wifi/network/serial setup. I've replaced the firmware on one board with other sketch; but now I want to revert it to the stock firmware. I cannot find the stock firmware source code anywhere. The DT-06 manufacturer also won't give it out.
Is it possible to extract the stock firmware from another DT-06 board and put it back into the other DT-06 board?
Thank you.

why are you looking for the firmware source?

Have you tried finding the firmware in binary? That would be enough. Mostly firmware isn't opensource, but can be downloaded as hex file.

It could be either binary or source. I can't find both. Can I extract its binary from one of my  DT-06?

Did you copy from one DT-06 to another DT-06 with the above program? I would also like you to show me the connections. Thanks.

Just save the stock firmware from one DT-06 on your pc/laptop and flash the saved firmware to another DT-06 which stock firmware was replaced earlier See my commands in my answer below.

Okay. I found a way to extract the binary file (stock firmware) from one DT-06 and flash it to another modified DT-06, by using esptool command
/*To extract firmware */:
esptool.py -p COM4 -b 460800 read_flash 0 0x400000 dt06_backup.bin
/*To flash the backup binary file to another DT-06 */
esptool.py -p com4 write_flash -fm dout 0x00000 dt06_backup.bin

I also have some DT-06 modules that did not come with the original firmware. I appreciate your knowledge. I'm just getting started with the arduino. It would be good for many if you could make the original firmware of the DT-06 Wifi module with the .ino extension as an arduino program.
, or you could send it. thank you: ferbela@freemail.hu

You may download its stock firmware (as a .bin file) from my google drive here:
https://drive.google.com/file/d/1oJyDso02NVfE8YmhDvKFJmyJGmnOsdw2/view?usp=sharing
or as a zip file here:
https://drive.google.com/file/d/1Z19SgD2dpa5PM9bHKWDcOLvxZjFnL2d3/view?usp=sharing
I did not use Arduino software to extract its stock firmware. I use python commands as posted here. Sorry I'm not sure how to make it as xxx.ino as you suggested.


text:
No "Huge APP partition scheme" (ESP32)
I recently downloaded the expressif ESP32 library and I'm trying to run the CameraWebServer example. Attempting to compile it results in the following error:
Sketch uses 2529577 bytes (192%) of program storage space. Maximum is 1310720 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.

I can reduce this number (192%) to 120% by changing partition scheme from "Default" to "No OTA (Large APP)". Online I've seen people using a partition scheme called "Huge APP", which I believe would solve my problem, but I don't see that option in Tools. Only "Default", "Large App" and "Minimal SPIFFS" (which doesn't work either).
How can I get the "Huge APP" partition scheme option in Arduino IDE?

Did the people online tell what core they are using for their ESP32? Also the used board is important. I use the esp32 core by Espressif Systems and I cannot see such a partition scheme for the Wemos Lolin32, but the ESP32 Dev Module shows more partition options up to 3MB for the app.

I do see the option if I switch the board the ESP32 Dev Module and it compiles successfully! My teacher told me to use the Wemos Lolin32 board, so will it work fine if I change the board to Dev Module?

It's possible to manually edit the board definition (boards.txt) to add a "Huge" partition scheme, if there'e enough storage space available. You can look up the syntax of the board definitions and add huge_app.upload.maximum_size=3145728 (or more, if there's space available) and its associated entries as a new partition scheme under the board entry for your ESP32Cam.

Thank you so much, I found the file and added the partition scheme and it looks like it's working.

I was able to fix the issue by editing the boards.txt file and adding the following lines:
lolin32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
lolin32.menu.PartitionScheme.huge_app.build.partitions=huge_app
lolin32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728

This will add a "Huge APP" partition scheme to WEMOS Lolin32.

Exactly, this is what I described in my comment. Make sure you have a copy or backup of the altered boards.txt files as it will be overwritten when you update the ESP32 Board Manager.

source: Stack Exchange

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

sort: votes


text:
Usage of SPI inside an ISR
I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?
Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.
I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work.
Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP.

This is why you don't use port expanders for timing-sensitive applications.

And instead of port expanders i shall use what?

Real IO pins on the microcontroller.

@Majenko: Which I have to poll. :(

No you don't - there's such a thing as Pin Change Interrupt which is (IIRC) available on every IO pin.

Reads interesting. Is the only difference between those Pin Change Interrupts and INT0/1 the fact that the latter can additionally trigger on high and low?

Please post your code. Majenko is perfectly correct. SPI does not use interrupts, at least during SPI.transfer(). I learned, that SPI-code uses interrupts. - where did you learn that?

apparently doesn't work. - I hate that expression. What happened? What did you expect to happen? In what way did they differ?

As a sidenote. You can use interrupts inside an ISR. Just call sei(); at the beginning of the ISR. There are however some side effect that you have to know about. It's therefor generally advised not to do this, unless you know what you are doing.

@NichGammon: The ISR is never called. To control the behaviour of the ISR I let it increase a global counter. But the counter stays at 0, while the INTCAP register of the port expander shows evidence for activity. But considering the answers here, the error must be elsewhere.

SPI doesn't use interrupts.  It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:
SPDR = data;
asm volatile("nop");
while (!(SPSR & _BV(SPIF))) ; // wait
return SPDR;

It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see https://www.arduino.cc/en/Reference/SPIusingInterrupt for instance.

Ok, I missed that. Then there must be another thing I apparently have botched...

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


text:
Including libraries from header files sometimes doesn't work
I, once again have difficulties including libraries from code files other than my .ino file.
I have several .cpp and .h files in my project to keep it sorted and clean.
However one of my header files starting like this:
#ifndef DPLANDEF
#define DPLANDEF
#include <Arduino.h>
#include <EEPROM.h>
#include "syssettings.h"

yields the following errors:

In file included from
  /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.cpp:2:0:
  /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.h:5:20:
  fatal error: EEPROM.h: No such file or directory  #include
                      ^ compilation terminated. Fehler beim Kompilieren.

EEPROM.h should be known to the IDE, because I can find it in the libraries menu, too. If it was a custom library, I might have botched something during installation, but this is a standard library. It should work out of the box. What's the problem here?

See Classes and objects: how many and which file types I actually need to use them? - that mentions the issue of putting your includes in the main .ino file.

@NickGammon Interesting roundup of the whole thing. bookmarked now.

The problem here is that it's a header file.  The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.
In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.

Thanks a lot. In the past I fiddled cluelessly around until it finally somehow worked out. After adding all libs to my INO header file, all libraries are detected, but I have a new problem. The IDE somehow managed to circumvent the include guard definition of PinChangeInt.h (custom library, which I tested already successfully). Linker is now complaining about lots of double definitions. Sigh. I guess time to move to a "real" IDE!?

@Ariser Include guards only work within the same compilation unit.  If you include the file in separate cpp or ino files it will exist multiple times, and any variables or functions defined in there will be conflicting.  You should never have functions or variables in headers - put them (once) in cpp or ino files and put extern references to them in the header files.  The header files then act like a "sharing" point for the variables and functions in the other cpp and ino files.

Sigh. I guess time to move to a "real" IDE!? - you would have that problem anywhere. As Majenko said, .h files are for declarations. To define something it should be done once, in a .c or .cpp file. You won't get double definitions on the class declaration. Your PinChangeInt library should also have a PinChangeInt.cpp file which is compiled once.

@Majenko I'm familiar with separation of declaration and definition. But I didn't suspect that this library was broken. I should have been alerted by the fact, that it was i linker and not a compiler error. Looking closely, this library lacks a source file completely. What a mess, I'm going to rewrite it...

@NickGammon: More like passing to a real build process.
The Arduino builds stuff in a way that is meant to help newbies, but it's disconcerting, to say the least, to those who are used to more traditional Unix ways of building code. Make, to mention one.

@Ariser: you could have a look at this: http://www.instructables.com/id/How-to-get-started-with-Eclipse-and-AVR/?ALLSTEPS
I'm not too fond of Eclipse, but it beats to a pulp the Arduino IDE hands down any day. And if you have an AVR Dragon, you can also ditch the serial prints and debug like it's supposed to be done on embedded devices: http://www.larsen-b.com/Article/315.html

@IgorStoppa - yes it is intended for newbies, and you must surely admit that Make is not for the faint-hearted. The process is described in a reply I made. I note that Ariser now says that the library is a mess, which presumably lets the build process of the hook a bit. The IDE can't help it if people put all their functions into .h files.

@NickGammon: the build process is still a mess as it does (black) magic with headers and I consider it as an encouragement to people doing even more evil things with headers.

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


text:
Adafruit TFT 1.3 inch display with arduino-rotate the font
I am using Arduino MKR1500 with adafruit 1.3 inch display(https://www.adafruit.com/product/4313) and I want to rotate the font on the screen by 90 degree. I tried setRotation() and added an angle in the brackets. but that did not help.
Can someone please let me know what command do I need to use to do that?

setRotation usually takes a number 0-3 for 90 degree steps

Hi Majenko, I tried setting it up to 0,1,2 in void setup() none of them changed the display setting . Is there something I could be missing?

Sorry, I figured it out. I was supposed to configure that in void tftPrintTest().

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


text:
Comparison of a string received from MQTT/Cloud/Arduino
I am trying to compare the string of data which I am receiving from the MQTT broker. If I receive the keyword faster I want to print "increase motor speed" and when I get slower keyword or any other keyword, I want to print "decrease motor speed". I am not sure how to store the data I receive from mqttClient.read()and then store it in string to then compare it
Below is the snippet of the code where I have added it and it seems not to work correctly in my case. can you look at it and let me know what is the mistake?
while (mqttClient.available()) {
Serial.print((char)mqttClient.read());
String ipstring= String("(char)mqttClient.read()");
String fast ="faster";
if((char)mqttClient.read()==fast)
{
Serial.println("increase motor speed");}
else
{
Serial.println("decrease motor speed");
}*
}

I have also attached the code for reference.
Thank you!
/*
  Azure IoT Hub NB

  This sketch securely connects to an Azure IoT Hub using MQTT over NB IoT/LTE Cat M1.
  It uses a private key stored in the ATECC508A and a self signed public
  certificate for SSL/TLS authetication.

  It publishes a message every 5 seconds to "devices/{deviceId}/messages/events/" topic
  and subscribes to messages on the "devices/{deviceId}/messages/devicebound/#"
  topic.

  The circuit:
  - MKR NB 1500 board
  - Antenna
  - SIM card with a data plan
  - LiPo battery

  The following tutorial on Arduino Project Hub can be used
  to setup your Azure account and the MKR board:

  https://create.arduino.cc/projecthub/Arduino_Genuino/securely-connecting-an-arduino-nb-1500-to-azure-iot-hub-af6470

  This example code is in the public domain.
*/

#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <MKRNB.h>

#include "arduino_secrets.h"
int sensorValue;

/////// Enter your sensitive data in arduino_secrets.h
const char pinnumber[]   = SECRET_PINNUMBER;
const char broker[]      = SECRET_BROKER;
String     deviceId      = SECRET_DEVICE_ID;

NB nbAccess;
GPRS gprs;

NBClient      nbClient;            // Used for the TCP socket connection
BearSSLClient sslClient(nbClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient    mqttClient(sslClient);

unsigned long lastMillis = 0;

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

  if (!ECCX08.begin()) {
    Serial.println("No ECCX08 present!");
    while (1);
  }

  // reconstruct the self signed cert
  ECCX08SelfSignedCert.beginReconstruction(0, 8);
  ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
  ECCX08SelfSignedCert.endReconstruction();

  // Set a callback to get the current time
  // used to validate the servers certificate
  ArduinoBearSSL.onGetTime(getTime);

  // Set the ECCX08 slot to use for the private key
  // and the accompanying public certificate for it
  sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());

  // Set the client id used for MQTT as the device id
  mqttClient.setId(deviceId);

  // Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
  String username;

  username += broker;
  username += "/";
  username += deviceId;
  username += "/api-version=2018-06-30";

  mqttClient.setUsernamePassword(username, "");

  // Set the message callback, this function is
  // called when the MQTTClient receives a message
  mqttClient.onMessage(onMessageReceived);
}

void loop() {
  if (nbAccess.status() != NB_READY || gprs.status() != GPRS_READY) {
    connectNB();
  }

  if (!mqttClient.connected()) {
    // MQTT client is disconnected, connect
    connectMQTT();
  }

  // poll for new MQTT messages and send keep alives
  mqttClient.poll();

  // publish a message roughly every 5 seconds.
  if (millis() - lastMillis > 5000) {
    lastMillis = millis();

    publishMessage();
  }
}

unsigned long getTime() {
  // get the current time from the cellular module
  return nbAccess.getTime();
}

void connectNB() {
  Serial.println("Attempting to connect to the cellular network");

  while ((nbAccess.begin(pinnumber) != NB_READY) ||
         (gprs.attachGPRS() != GPRS_READY)) {
    // failed, retry
    Serial.print(".");
    delay(1000);
  }

  Serial.println("You're connected to the cellular network");
  Serial.println();
}

void connectMQTT() {
  Serial.print("Attempting to MQTT broker: ");
  Serial.print(broker);
  Serial.println(" ");

  while (!mqttClient.connect(broker, 8883)) {
    // failed, retry
    Serial.print(".");
    Serial.println(mqttClient.connectError());
    delay(5000);
  }
  Serial.println();

  Serial.println("You're connected to the MQTT broker");
  Serial.println();

  // subscribe to a topic
  mqttClient.subscribe("devices/" + deviceId + "/messages/devicebound/#");
}

void publishMessage() {
  Serial.println("Publishing message");

  // send message, the Print interface can be used to set the message contents
  mqttClient.beginMessage("devices/" + deviceId + "/messages/events/");
  mqttClient.print("hello ");
  sensorValue = analogRead(A0);
  mqttClient.println(sensorValue);
  //mqttClient.print(millis());

  mqttClient.endMessage();
}

void onMessageReceived(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.print("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    Serial.print((char)mqttClient.read());
    String ipstring= String("(char)mqttClient.read()");
    String fast ="faster";
    if((char)mqttClient.read()==fast)
    {
      Serial.println("increase motor speed");}
      else
      {
        Serial.println("decrease motor speed");
        }
  }
  Serial.println();

  Serial.println();
}

Comments are not for extended discussion; this conversation has been moved to chat.

As I read the comments, I see the project requirements are evolving. The 0 = Off command structure will severely limit what you can do, but it is a good starting point.
Regarding the first block of code starting with while (mqttClient.available()) {, then adding your one digit / char commands idea, I have this test sketch for you to try.
You don't need the String object to accomplish your goal. You may have to do something like this though  input = (char)mqttClient.read() where the test sketch uses this input = Serial.read();.
char input;

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

void loop(){

  if(Serial.available() > 0){

    input = Serial.read();

    if(input == '0'){
      Serial.println("Turn Off");
    }

    else if(input == '1'){
      Serial.println("Turn On");
    }

    else if(input == '2'){
      Serial.println("Decrease Speed");
    }

    else if(input == '3'){
      Serial.println("Increase Speed");
    }
  }
}

To take it a step further, let's say you want to send commands that start with a single letter, then after the letter, the remaining digits, or chars have a purpose, if you want them to. For example, lets say you send the following command d50. The d could mean decrease speed, and the 50 could mean 50%, 50 steps, etc.
The following test sketch illustrates my point.
char inputBuffer[64 + 1];

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

void loop(){

  while(Serial.available() > 0){

    Serial.readBytesUntil('\n', inputBuffer, sizeof(inputBuffer));

    if(inputBuffer[0] == 'f'){
      Serial.println("Letter 'f' entered");
    }

    // Letter "r". Everything after the "r" should be digits.
    else if(inputBuffer[0] == 'r'){
      Serial.print("Letter 'r' entered\t");
      // Change the letter "r" to the digit 0 to keep atol() happy.
      inputBuffer[0] = B110000;
      Serial.print("Number entered = ");
      Serial.println(atol(inputBuffer));

      // Your code here that uses the number parsed using atol().

    }

    // Letter "s". Everything after the "s" should have a max
    // length of up to 64 chars long for a 64 + 1 char buffer.
    else if(inputBuffer[0] == 's'){

      // MAX CHARS example with a 64 byte buffer:
      // s123456789a123456789b123456789c123456789d123456789e123456789f + CR + NL
      Serial.print("Letter 's' entered\tText entered = ");

      // Print out the chars in the buffer.
      for(int i = 1; i < strlen(inputBuffer); i++){
        Serial.print(inputBuffer[i]);
      }
      Serial.println();

      // Your code here that uses the char data after the letter "s" is entered.

    }
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}


text:
Unable to import the libraries correctly
I am trying to use the Arduino IDE 1.8.15 to program my Arduino. When I download the following code along with the libraries from the same link: https://github.com/SolidGeek/VescUart and using the example: https://github.com/SolidGeek/VescUart/tree/master/examples/getVescValuescompile it, it seems to giving me an error that the VescUart file seems to be missing. I did ctrl+shift+N and also tried adding the library files and these library files are in the same folder as the .ino code. but still it keeps giving me that the header file is missing. Can someone help me with this please?
Error message below:
Arduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: "Arduino MKR NB 1500"

getVescValues:9:10: fatal error: VescUart.h: No such file or directory

 #include <VescUart.h>

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

compilation terminated.

exit status 1

VescUart.h: No such file or directory

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

Also attached is the image for reference

Please put the library in your library folder

Thanks! that worked

Does this answer your question? I have downloaded the library but not sure what went wrong


text:
Arduino MKR NB 1500 websockets
I am trying to implement websockets for MKR1500 and I am having trouble finding a perfect example to implement it. Can someone guide me to an example that works with MKR1500?

I would try ArduinoHttpClient library with MKRNB library


text:
How to send AT commands to the ubox modem on MKR NB 1500
I am trying to send AT commands to the modem to keep the modem always active. I tried the File > Examples > MKRNB > Tools > SerialSarapassThrough example, but that gave me a +CME ERROR: operation not supported. Here is the output for the commands I sent via serial monitor:
AT
OK
AT+UPSV=0
+CME ERROR: operation not supported

Is there a built in code or any other code which I could use to send that command?

I'm not familiar with that modem, but if the firmware tells you, that is doesn't support that command, then it doesn't support it. Are you sure, that the modem is capable of what you want?

yes i am sure, I read the documentation of the modem and it specifies that sending commands will set it up according to my requirement

Please link to that part of the documentation

https://www.u-blox.com/sites/default/files/SARA-R4_ATCommands_UBX-17003787.pdf

The command is : AT+UPSV=0

You have to try SerialSARAPassthrough.ino from examples menu under MKRNB.
If it works properly, you can start writing AT in serial monitor line. You must see answer as OK. Then you can look at the u-blox commands document that is shared above


text:
Issue displaying on Adafruit display when enabling GSM communication
I am trying to write to the adafruit display using Arduino MKR1500 when it is connected to the internet. The issue I am facing is when I add the code to connect to the cloud, the display stops working. If I removed that piece of code, the display outputs correctly.
As of now I am just printing "hello world" on the screen.
Below is the code without the cloud connection:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  The 1.14" TFT breakout
  ----> https://www.adafruit.com/product/4383
  The 1.3" TFT breakout
  ----> https://www.adafruit.com/product/4313
  The 1.54" TFT breakout
    ----> https://www.adafruit.com/product/3787
  The 2.0" TFT breakout
    ----> https://www.adafruit.com/product/4311
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  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.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/
#include <Adafruit_Fingerprint.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2
//#include <EEPROM.h>
#include <FlashStorage.h>

#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
#define TFT_CS         14
#define TFT_RST        15
#define TFT_DC         32

#elif defined(ESP8266)
#define TFT_CS         4
#define TFT_RST        16
#define TFT_DC         5

#else
// For the breakout board, you can use any 2 or 3 pins.
// These pins will also work for the 1.8" TFT shield.
#define TFT_CS        1 // D v25 changes to use pin 1 for CS in MKR1500
#define TFT_RST        -1 // Or set to -1 and connect to Arduino RESET pin // D v25 changes to use built in reset pinout in MKR1500
#define TFT_DC         2 // D v25 changes to use pin 2 for CS in MKR1500
#endif

//D v15 for audrino to connect to fingerprint sensor
//D v2
#if (defined(__AVR__) || defined(ESP8266)) && !defined(__AVR_ATmega2560__)
// 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)
// Set up the serial port to use softwareserial..
SoftwareSerial mySerial(2, 4);

#else
// On Leonardo/M0/etc, others with hardware serial, use hardware serial!
// #0 is green wire, #1 is white
#define mySerial Serial1

#endif

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

// For 1.44" and 1.8" TFT with ST7735 use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); // D v21 uncomment this and comment the line below to use 1.44inch display.Need to change the display font in case I use 1.44"

// For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789:
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST); // D v22 uncommment to use this display

#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>
#include <MKRNB.h>

// Debug options
#define PRINT_AT        true   // Show or hide AT command output from the modem

// PIN Number
const char PINNUMBER[]     = "";
char apn[] = "soracom.io";
char user[] = "sora";
char pass[] = "sora";

// Server details
const char server[] = "unified.soracom.io";
const int  port = 80;

NBClient client;
GPRS gprs;
NB nbAccess(PRINT_AT);
HttpClient http(client, server, port);

// connection state
  bool connected = false;

// Publish interval
long previousMillis = 0;
long interval = 1000; // milliseconds // D v2orginial value: long interval = 20000; chnages the time interval in which it will report

void setup(void) {

  // tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
  tft.init(240, 240);           // Init ST7789 240x240  // D v22 uncommment to use this display

  // tft print function!
  tftPrintTest();

  pinMode(SARA_RESETN, OUTPUT);
  digitalWrite(SARA_RESETN, LOW);
  pinMode(SARA_PWR_ON, OUTPUT);

  //Initialize serial and wait for port to open:
  Serial.begin(115200);

  //D v33
  /*while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }*/

  start_and_connect_modem();

  }

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

  tft.setTextColor(ST77XX_GREEN);
  tft.setCursor(0, 10);

    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);

    tft.println("hello world");

    }

void tftPrintTest() {
  tft.setRotation(3);
  tft.setTextWrap(true);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(2);
}

Below is the code with the cloud connection added
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  The 1.14" TFT breakout
  ----> https://www.adafruit.com/product/4383
  The 1.3" TFT breakout
  ----> https://www.adafruit.com/product/4313
  The 1.54" TFT breakout
    ----> https://www.adafruit.com/product/3787
  The 2.0" TFT breakout
    ----> https://www.adafruit.com/product/4311
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  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.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/
#include <Adafruit_Fingerprint.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2
//#include <EEPROM.h>
#include <FlashStorage.h>

#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
#define TFT_CS         14
#define TFT_RST        15
#define TFT_DC         32

#elif defined(ESP8266)
#define TFT_CS         4
#define TFT_RST        16
#define TFT_DC         5

#else
// For the breakout board, you can use any 2 or 3 pins.
// These pins will also work for the 1.8" TFT shield.
#define TFT_CS        1 // D v25 changes to use pin 1 for CS in MKR1500
#define TFT_RST        -1 // Or set to -1 and connect to Arduino RESET pin // D v25 changes to use built in reset pinout in MKR1500
#define TFT_DC         2 // D v25 changes to use pin 2 for CS in MKR1500
#endif

//D v15 for audrino to connect to fingerprint sensor
//D v2
#if (defined(__AVR__) || defined(ESP8266)) && !defined(__AVR_ATmega2560__)
// 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)
// Set up the serial port to use softwareserial..
SoftwareSerial mySerial(2, 4);

#else
// On Leonardo/M0/etc, others with hardware serial, use hardware serial!
// #0 is green wire, #1 is white
#define mySerial Serial1

#endif

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

// For 1.44" and 1.8" TFT with ST7735 use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); // D v21 uncomment this and comment the line below to use 1.44inch display.Need to change the display font in case I use 1.44"

// For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789:
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST); // D v22 uncommment to use this display

#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>
#include <MKRNB.h>

// Debug options
#define PRINT_AT        true   // Show or hide AT command output from the modem

// PIN Number
const char PINNUMBER[]     = "";
char apn[] = "soracom.io";
char user[] = "sora";
char pass[] = "sora";

// Server details
const char server[] = "unified.soracom.io";
const int  port = 80;

NBClient client;
GPRS gprs;
NB nbAccess(PRINT_AT);
HttpClient http(client, server, port);

// connection state
  bool connected = false;

// Publish interval
long previousMillis = 0;
long interval = 1000; // milliseconds // D v2orginial value: long interval = 20000; chnages the time interval in which it will report

void setup(void) {

  // tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
  tft.init(240, 240);           // Init ST7789 240x240  // D v22 uncommment to use this display

  // tft print function!
  tftPrintTest();

  pinMode(SARA_RESETN, OUTPUT);
  digitalWrite(SARA_RESETN, LOW);
  pinMode(SARA_PWR_ON, OUTPUT);

  //Initialize serial and wait for port to open:
  Serial.begin(115200);

  //D v33
  /*while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }*/

  start_and_connect_modem();

  }

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

  tft.setTextColor(ST77XX_GREEN);
  tft.setCursor(0, 10);

    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);

    tft.println("hello world");

    }

void tftPrintTest() {
  tft.setRotation(3);
  tft.setTextWrap(true);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(2);
}

void post_data(String postData) {
 //Serial.println("making POST request");
  String contentType = "application/json";

  http.post("/", contentType, postData);

  // read the status code and body of the response
  int statusCode = http.responseStatusCode();
  String response = http.responseBody();

  /*Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);*/

}

void start_and_connect_modem(){
  pinMode(SARA_RESETN, OUTPUT);
  digitalWrite(SARA_RESETN, LOW);
  pinMode(SARA_PWR_ON, OUTPUT);

  // Send Poweron pulse
  digitalWrite(SARA_PWR_ON, HIGH);
  delay(150);
  digitalWrite(SARA_PWR_ON, LOW);
  delay(500);
  // Turn on the modem
  if (Serial) Serial.print(">>> Turning on modem...");
  if (MODEM.begin()) {
    if (Serial) Serial.println(" done!");
  } else {
    if (Serial) Serial.println(" error, could not turn on modem! Try power-cycling.");
    return;
  }

  while (!MODEM.noop());
  MODEM.sendf("ATI9");
  MODEM.waitForResponse(2000);

  // Run AT commands to reset the modem to global default settings
  Serial.print(">>> Resetting modem to default settings...");
  MODEM.sendf("AT+CFUN=0");
  MODEM.waitForResponse(6000);
  MODEM.sendf("AT+UMNOPROF=2");
  MODEM.waitForResponse(2000);
  MODEM.sendf("AT+CFUN=15");
  MODEM.waitForResponse(6000);
  MODEM.sendf("AT+CFUN=0");
  MODEM.waitForResponse(2000);
  MODEM.sendf("AT+UMNOPROF=0");
  MODEM.waitForResponse(2000);
  MODEM.sendf("AT+CFUN=15");
  MODEM.waitForResponse(2000);
  MODEM.sendf("AT+URAT=7");
  MODEM.waitForResponse(2000);
  //D v33
  /*MODEM.sendf("AT+UBANDMASK?");
  MODEM.waitForResponse(6000);*/
  Serial.println(" done!");

  delay(2000);
  // attempt to connect to GSM and GPRS:
  Serial.print("Attempting to connect to GSM and GPRS");
  //Serial.println();
  connect_modem();

}

void connect_modem(){
  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected) {
    if ((nbAccess.begin(PINNUMBER, apn, user, pass) == NB_READY) &&
        (gprs.attachGPRS() == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("You're connected to the network");
}

Can someone please let me know what I am missing?


text:
Arduino Nano 33 BLE Sense TFlite inference hangs when using bluetooth
I'm running into an issue where when I try to set up a BLE service my tflite inference seems to hang/crash. I used https://experiments.withgoogle.com/tiny-motion-trainer to train a model to recognize a few gestures with my nano. The code I'm using is mostly sample code generated by the site. Here's the code that correctly outputs gestures to the Serial monitor:
/**
* TinyML Trainer Example.
* Version: v005
*
* This is an example generated by Tiny Motion Trainer
* It is pre-filled with your trained model and your capture settings
*
* Required Libraries:
* - TensorFlow Lite for Microcontrollers (tested with v2.4-beta)
* - Arduino_LSM9DS1
*
* Usage:
* - Make sure the Arduino BLE 33 board is installed (tools->board->Board Manager) and connected
* - Make sure you have the required libraries installed
* - Build and upload the sketch
* - Keep the Arduino connected via USB and open the Serial Monitor (Tools->Serial Monitor)
* - The sketch will log out the label with the highest score once detected.
*
* This is meant as an example for you to develop your own code, and is not production ready.
*
**/

//==============================================================================
// Includes
//==============================================================================

#include <Arduino_LSM9DS1.h>
#include <ArduinoBLE.h>
#include <TensorFlowLite.h>
#include <tensorflow/lite/micro/all_ops_resolver.h>
#include <tensorflow/lite/micro/micro_error_reporter.h>
#include <tensorflow/lite/micro/micro_interpreter.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <tensorflow/lite/version.h>

//==============================================================================
// Your custom data / settings
// - Editing these is not recommended
//==============================================================================

// This is the model you trained in Tiny Motion Trainer, converted to
// a C style byte array.
#include "model.h"

// Values from Tiny Motion Trainer
#define MOTION_THRESHOLD 0.2
#define CAPTURE_DELAY 200 // This is now in milliseconds
#define NUM_SAMPLES 20

// Array to map gesture index to a name
const char *GESTURES[] = {
    "gesture1", "gesture2", "gesture3"
};

//==============================================================================
// Capture variables
//==============================================================================

#define NUM_GESTURES (sizeof(GESTURES) / sizeof(GESTURES[0]))

bool isCapturing = false;

// Num samples read from the IMU sensors
// "Full" by default to start in idle
int numSamplesRead = 0;

//==============================================================================
// TensorFlow variables
//==============================================================================

// Global variables used for TensorFlow Lite (Micro)
tflite::MicroErrorReporter tflErrorReporter;

// Auto resolve all the TensorFlow Lite for MicroInterpreters ops, for reduced memory-footprint change this to only
// include the op's you need.
tflite::AllOpsResolver tflOpsResolver;

// Setup model
const tflite::Model* tflModel = nullptr;
tflite::MicroInterpreter* tflInterpreter = nullptr;
TfLiteTensor* tflInputTensor = nullptr;
TfLiteTensor* tflOutputTensor = nullptr;

// Create a static memory buffer for TensorFlow Lite for MicroInterpreters, the size may need to
// be adjusted based on the model you are using
constexpr int tensorArenaSize = 8 * 1024;
byte tensorArena[tensorArenaSize];

//==============================================================================
// Setup / Loop
//==============================================================================

// Variables to hold IMU data
float aX, aY, aZ, gX, gY, gZ;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.begin(9600);

  // Wait for serial monitor to connect
  while (!Serial);

  // Initialize IMU sensors
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }

  // Print out the samples rates of the IMUs
  Serial.print("Accelerometer sample rate: ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println(" Hz");
  Serial.print("Gyroscope sample rate: ");
  Serial.print(IMU.gyroscopeSampleRate());
  Serial.println(" Hz");

  Serial.println();

  // Get the TFL representation of the model byte array
  tflModel = tflite::GetModel(model);
  if (tflModel->version() != TFLITE_SCHEMA_VERSION) {
    Serial.println("Model schema mismatch!");
    while (1);
  }

  // Create an interpreter to run the model
  tflInterpreter = new tflite::MicroInterpreter(tflModel, tflOpsResolver, tensorArena, tensorArenaSize, &tflErrorReporter);

  // Allocate memory for the model's input and output tensors
  tflInterpreter->AllocateTensors();

  // Get pointers for the model's input and output tensors
  tflInputTensor = tflInterpreter->input(0);
  tflOutputTensor = tflInterpreter->output(0);
}

void loop() {
  // Wait for motion above the threshold setting
 if (!isCapturing) {
    if (IMU.accelerationAvailable() && IMU.gyroscopeAvailable()) {

      IMU.readAcceleration(aX, aY, aZ);
      IMU.readGyroscope(gX, gY, gZ);

      // Sum absolute values
      float average = fabs(aX / 4.0) + fabs(aY / 4.0) + fabs(aZ / 4.0) + fabs(gX / 2000.0) + fabs(gY / 2000.0) + fabs(gZ / 2000.0);
      average /= 6.;

      // Above the threshold?
      if (average >= MOTION_THRESHOLD) {
        isCapturing = true;
        numSamplesRead = 0;
        //break;
      }
    }
  }

  if (isCapturing) {

    // Check if both acceleration and gyroscope data is available
    if (IMU.accelerationAvailable() && IMU.gyroscopeAvailable()) {

      // read the acceleration and gyroscope data
      IMU.readAcceleration(aX, aY, aZ);
      IMU.readGyroscope(gX, gY, gZ);

      // Normalize the IMU data between -1 to 1 and store in the model's
      // input tensor. Accelerometer data ranges between -4 and 4,
      // gyroscope data ranges between -2000 and 2000
      tflInputTensor->data.f[numSamplesRead * 6 + 0] = aX / 4.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 1] = aY / 4.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 2] = aZ / 4.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 3] = gX / 2000.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 4] = gY / 2000.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 5] = gZ / 2000.0;

      numSamplesRead++;

      // Do we have the samples we need?
      if (numSamplesRead == NUM_SAMPLES) {

        // Stop capturing
        isCapturing = false;

        // Run inference
        Serial.println("invoking");
        TfLiteStatus invokeStatus = tflInterpreter->Invoke();
        Serial.println("invoked");
        if (invokeStatus != kTfLiteOk) {
          Serial.println("Error: Invoke failed!");
          while (1);
          return;
        }

        // Loop through the output tensor values from the model
        int maxIndex = 0;
        float maxValue = 0;
        for (int i = 0; i < NUM_GESTURES; i++) {
          float _value = tflOutputTensor->data.f[i];
          if(_value > maxValue){
            maxValue = _value;
            maxIndex = i;
          }
          Serial.print(GESTURES[i]);
          Serial.print(": ");
          Serial.println(tflOutputTensor->data.f[i], 6);
        }

        Serial.print("Winner: ");
        Serial.print(GESTURES[maxIndex]);

        Serial.println();

        // Add delay to not double trigger
        delay(CAPTURE_DELAY);
      }
    }
  }
}

When I add the declaration BLEService service("4798e0f2-0000-4d68-af64-8a8f5258404e"); before the setup function, this code no longer works. I see
Accelerometer sample rate: 119.00 Hz
Gyroscope sample rate: 119.00 Hz

invoking

in my Serial monitor and then nothing. It seems like just declaring this service is somehow causing the inference code to crash. Does anyone have any idea why that would be happening? I'd really appreciate any help!

Did you ever solve this? I’m having the same issue


text:
Push button unexpected increment/decrement. I'm using attachInterrupt
I'm new to Arduino and need assistance from knowledgeable people.
I'm having a problem with my code, which allows the user to increase or decrease the number by pressing buttons. From time to time, the number does not change by one, but by two or three. This occurs on a sporadic basis. This is known as "bouncing." I googled "attachInterrupt debounce" in vain, but I couldn't find a suitable solution. My code is here.
int digit_state = 0;
void increment(void){
  digit_state = digit_state + 1;
  }
void decrement(void){
  digit_state = digit_state - 1;
  }
String user_input = "";
String password = "3452";
int enterbutton = 11;
int increment_button = 2;
int decrement_button = 3;
int counter = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(enterbutton,INPUT);
  attachInterrupt(digitalPinToInterrupt(increment_button),increment,FALLING);
  attachInterrupt(digitalPinToInterrupt(decrement_button),decrement,FALLING);
}

void loop() {
  // put your main code here, to run repeatedly:
  lastButtonState = reading;
  while(counter<=3){
    delay(500);
    Serial.println(digit_state);
    if(digitalRead(enterbutton)==LOW){
      user_input = user_input + digit_state;
      Serial.println("Saved input so far is "+user_input);
      if(user_input == password){
        Serial.println("検証できた");
      }
      delay(500);
      digit_state = 0;
      counter++;
  }
}
}

As the user presses, I need to stop it from bouncing and get an accurate password all the time.

First: It is not necessary to use interrupts for buttons, because when humans press buttons they will be at least actived for about 100ms, which is very slow for a microcontroller. You would just need to rewrite your code to be non-blocking (for example by ditching all delay() calls and instead use millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE). Then you can also use existing libraries for debouncing like Bounce2.

A very simple approach would be to set a timeout after each button press, where no new button press will be registrated, like 10ms (should be plenty enough for debouncing, though you can test for your setup yourself). This can be done with millis() by maintaining a timestamp of the last button press:
#define DEBOUNCE_TIME  10
volatile unsigned long button_press_timestamp = 0;

void increment(void){
  if(millis()-button_press_timestamp > DEBOUNCE_TIME){
      digit_state = digit_state + 1;
      button_press_timestamp = millis();
  }
}

First in global scope we are defining our debounce time and a variable for holding the timestamp, when the last button press was registered. In the ISR (here only increment() as example) we then check the difference between this timestamp and the current time. If that is bigger than the debounce time we execute the buttons action (incrementing in this case). Then we update the timestamp to the current time.
On a button press the first falling edge will trigger the button action. Any falling edges from the bouncing will appear inside the debounce time and thus will be ignored (the ISR gets called but the code in the if statement is not executed).
This debouncing principle is not perfect but easy to implement and it might be enough for you.

Thank you for the solution.


text:
How to calculating requirements of power supply for a project
I am starting with electronics and been working with Arduino for some time now. I did some basic LED and servo motor project and was hoping to jump into making an obstacle-avoidance car. I used 4 AA batteries to make it, but the voltage was too low, as the motors were not moving. Then I knew about the volt requirements and all that. I also tried with a 9v alkaline battery, but it didn't help much.
Here are the electrical parts I used:

Arduino
Ultrasonic sensor
4 toy motor
1 hobby servo motor
Motor driver shield L293D
Battery

These are the operating voltages that I know of:

Arduino = 7 to 12 v
Hobby servo motor =  3.0V~ 7.2V
Toy motor = 3v ~ 12v dc; has a No load current 40 - 80 mA

Because AA batteries are of 1.5v and are in series, it has 6v, and I am assuming that was the reason it was not working as expected. What I am confused about is, how do I choose a battery or power supply to be specific.
Please forgive me for asking such a noob question. Since 1 Arduino + 4 toy motor  + 1 hobby servo motor = 7v + 4 x 12v + 7v = 62 v, but I checked and I couldn't find battery that is above 15v. I surely don't understand how to pick a power supply. Could you please help me out on how to calculate and choose the right battery/power supply? Also, what to look for if for example, I want to run it for a minimum of 10 minutes?

The loads of a supply are typically connected in parallel, not in series. Read Series and Parallel Circuits.

9V batteries can hardly handle any current, so that's probably why that didn't work for you. I'd add more AA batteries in series. Using 6 would give you 6-9V (6V when empty, 9V when full). 8 would give you 8-12V. In that case you'd have to run the servo from the regulated 5V on the Arduino, as to not exceed its rated voltage.

A power supply a 9V battery is not. Since you are using batteries the L293D is a very poor choice for a driver, it uses silicon transistors which I believe are in a darlington configuration which will cause a voltage drop of from 1.4 to 2.8 volt on the motor.  The 4 (or more) AA batteries will work but use a MOSFET bridge. You can always use a small SEPIC (Buck/Boost) converter to power it, that will keep the voltage constant until the batteries are exhausted. Set it to about 9V and power the arduino via the VIN input for more filtering. You will need a way of measuring voltage. You will lose less power with the converter then you are losing in your current driver.


text:
OLED 'SH1106_WHITE' was not declared in this scope
I was following FREE Functions to draw graphs on OLED displays on YouTube but mine OLED display doesn't support Adafruit_SSD1306 library,but it works on Adafruit_SH1106.h driver.
The code that is shared with YouTube video
/*

  This program provides functions to draw:
  1. horizontal bar graph
  2. vertical bar graph
  3. dial
  4. cartesian graph

  It requires an microcrontrioller Arduino, teensy and a 0.96 dispaly (1306 driver chip)

  display. sources
  https://www.amazon.com/Diymall-Yellow-Arduino-display.-Raspberry/dp/B00O2LLT30/ref=pd_lpo_vtph_147_bs_t_1?_encoding=UTF8&psc=1&refRID=BQAPE07SVJQNDKEVMTQZ
  https://www.amazon.com/dp/B06XRCQZRX/ref=sspa_dk_detail_0?psc=1&pd_rd_i=B06XRCQZRX&pd_rd_wg=aGuhK&pd_rd_r=1WJPXAG68XFSADGDPNZR&pd_rd_w=DAAsB

  Adafruit libraries
  https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
  https://github.com/adafruit/Adafruit_SSD1306

  Revisions
  rev     date        author      description
  1       12-5-2017   kasprzak    initial creation

  Pin settings

  Arduino   device
  5V        Vin
  GND       GND
  A0        read an input voltage from a pot across Vcc and Gnd (just for demo purposes)
  A1
  A2
  A3
  A4        SDA on the display. or use dedicated pin on board if provided
  A5        SCL on the display. use dedicated pin on board if provided
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
  12
  13

*/

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define READ_PIN            A0
#define OLED_RESET          A4
#define LOGO16_GLCD_HEIGHT  16
#define LOGO16_GLCD_WIDTH   16

// create what ever variables you need
double volts;
double bvolts;
double x, y;

// these are a required variables for the graphing functions
bool Redraw1 = true;
bool Redraw2 = true;
bool Redraw3 = true;
bool Redraw4 = true;
double ox , oy ;

// create the display object
Adafruit_SSD1306 display(OLED_RESET);

void setup() {

  Serial.begin(9600);

  // initialize the display
  // note you may have to change the address
  // the most common are 0X3C and 0X3D

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  // if you distribute your code, the adafruit license requires you show their splash screen
  // otherwise clear the video buffer memory then display
  display.display();
  //delay(2000);
  display.clearDisplay();
  display.display();

  // establish whatever pin reads you need
  pinMode(A0, INPUT);

}

unsigned long OldTime;
unsigned long counter;

  void loop(void) {

  // read some values and convert to volts
  bvolts = analogRead(A0);
  volts = (bvolts  / 204.6 ) ;

  // draw any of the following, sorry for the crazy long arguement lists
  // note 0.96 isn't very big, so you can't show many graphs at the same time
  // also colors are hard coded
  // the display i use draws text at the top in yellow--we'll use that for drawing the title

  // call one of these functions
  DrawBarChartV(display, bvolts, 25,  60, 40, 40, 0, 1024 , 256, 0, "A0 (bits)", Redraw1);
  //  DrawBarChartH(display, volts, 10, 45, 100, 20, 0, 5, 1, 0, "A0 (volts)", Redraw2);
  //  DrawDial(display, volts, 65, 50, 25, 0, 5 , 1, 0, 200, "A0 (volts)", Redraw3);

  // for multiple graphs uncomment the next 2 lines
  //  DrawBarChartV(display, bvolts, 5,  60, 10, 40, 0, 1024 , 256, 0, "A0 (bits/volts)", Redraw1);
  //  DrawDial(display, volts, 90, 50, 25, 0, 5 , 1, 0, 200, "A0 (bits/volts)", Redraw3);

  // or show a cartesian style graph to plot values over time (or whatever)

    DrawCGraph(display, x++, bvolts, 30, 50, 75, 30, 0, 100, 25, 0, 1024, 512, 0, "Bits vs Seconds", Redraw4);
    if (x > 100) {
    while (1) {}
    }

  delay(1000);

  }

  /*
  This method will draw a vertical bar graph for single input
  it has a rather large arguement list and is as follows

  &d to pass the display object, mainly used if multiple displays are connected to the MCU
  curval = date to graph (must be between loval and hival)
  x = position of bar graph (lower left of bar)
  y = position of bar (lower left of bar
  w = width of bar graph
  h =  height of bar graph (does not need to be the same as the max scale)
  loval = lower value of the scale (can be negative)
  hival = upper value of the scale
  inc = scale division between loval and hival
  dig = format control to set number of digits to display. (not includeing the decimal)
  label = bottom lable text for the graph
  redraw = flag to redraw display. only on first pass (to reduce flickering)

*/

void DrawBarChartV(Adafruit_SSD1306 &d, double curval, double x , double y , double w, double h , double loval , double hival , double inc , double dig, String label, bool &Redraw)
{
  double stepval, my, level, i, data;

  if (Redraw) {
    Redraw = false;
    d.fillRect(0, 0,  127 , 14, SSD1306_WHITE);
    d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
    d.setTextSize(1);
    d.setCursor(2, 4);
    d.println(label);
    // step val basically scales the hival and low val to the height
    // deducting a small value to eliminate round off errors
    // this val may need to be adjusted
    stepval = ( inc) * (double (h) / (double (hival - loval))) - .001;
    for (i = 0; i <= h; i += stepval) {
      my =  y - h + i;
      d.drawFastHLine(x + w + 1, my,  5, SSD1306_WHITE);
      // draw lables
      d.setTextSize(1);
      d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
      d.setCursor(x + w + 12, my - 3 );
      data = hival - ( i * (inc / stepval));
      d.print(data, dig);
    }
  }
  // compute level of bar graph that is scaled to the  height and the hi and low vals
  // this is needed to accompdate for +/- range
  level = (h * (((curval - loval) / (hival - loval))));
  // draw the bar graph
  // write a upper and lower bar to minimize flicker cause by blanking out bar and redraw on update
  d.drawRect(x, y - h, w, h, SSD1306_WHITE);
  d.fillRect(x, y - h, w, h - level,  SSD1306_BLACK);
  d.drawRect(x, y - h, w, h, SSD1306_WHITE);
  d.fillRect(x, y - level, w,  level, SSD1306_WHITE);
  // up until now print sends data to a video buffer NOT the screen
  // this call sends the data to the screen
  d.display();

}

/*
  This method will draw a horizontal bar graph for single input
  it has a rather large arguement list and is as follows

  &display to pass the display object, mainly used if multiple displays are connected to the MCU
  x = position of bar graph (upper left of bar)
  curval = date to graph (must be between loval and hival)
  y = position of bar (upper left of bar (add some vale to leave room for label)
  w = width of bar graph (does not need to be the same as the max scale)
  h =  height of bar graph
  loval = lower value of the scale (can be negative)
  hival = upper value of the scale
  inc = scale division between loval and hival
  dig = format control to set number of digits to display. (not includeing the decimal)
  label = bottom lable text for the graph
  redraw = flag to redraw display. only on first pass (to reduce flickering)
*/

void DrawBarChartH(Adafruit_SSD1306 &d, double curval, double x , double y , double w, double h , double loval , double hival , double inc , double dig, String label, bool &Redraw)
{
  double stepval, mx, level, i, data;

  if (Redraw) {
    Redraw = false;
    d.fillRect(0, 0,  127 , 16, SSD1306_WHITE);
    d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
    d.setTextSize(1);
    d.setCursor(2, 4);
    d.println(label);
    // step val basically scales the hival and low val to the width
    stepval =  inc * (double (w) / (double (hival - loval))) - .00001;
    // draw the text
    for (i = 0; i <= w; i += stepval) {
      d.drawFastVLine(i + x , y ,  5, SSD1306_WHITE);
      // draw lables
      d.setTextSize(1);
      d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
      d.setCursor(i + x , y + 10);
      // addling a small value to eliminate round off errors
      // this val may need to be adjusted
      data =  ( i * (inc / stepval)) + loval + 0.00001;
      d.print(data, dig);
    }
  }
  // compute level of bar graph that is scaled to the width and the hi and low vals
  // this is needed to accompdate for +/- range capability
  // draw the bar graph
  // write a upper and lower bar to minimize flicker cause by blanking out bar and redraw on update
  level = (w * (((curval - loval) / (hival - loval))));
  d.fillRect(x + level, y - h, w - level, h,  SSD1306_BLACK);
  d.drawRect(x, y - h, w,  h, SSD1306_WHITE);
  d.fillRect(x, y - h, level,  h, SSD1306_WHITE);
  // up until now print sends data to a video buffer NOT the screen
  // this call sends the data to the screen
  d.display();

}

/*
  This method will draw a dial-type graph for single input
  it has a rather large arguement list and is as follows

  &display to pass the display object, mainly used if multiple displays are connected to the MCU
  curval = date to graph (must be between loval and hival)
  cx = center position of dial
  cy = center position of dial
  r = radius of the dial
  loval = lower value of the scale (can be negative)
  hival = upper value of the scale
  inc = scale division between loval and hival
  sa = sweep angle for the dials scale
  dig = format control to set number of digits to display. (not includeing the decimal)
  label = bottom lable text for the graph
  redraw = flag to redraw display. only on first pass (to reduce flickering)
*/

void DrawDial(Adafruit_SSD1306 &d, double curval, int cx, int cy, int r, double loval , double hival , double inc, double dig, double sa, String label, bool &Redraw) {

  double ix, iy, ox, oy, tx, ty, lx, rx, ly, ry, i, Offset, stepval, data, angle;
  double degtorad = .0174532778;
  static double px = cx, py = cy, pix = cx, piy = cy, plx = cx, ply = cy, prx = cx, pry = cy;

  if (Redraw) {
    Redraw = false;
    // draw the dial only one time--this will minimize flicker
    d.fillRect(0, 0,  127 , 16, SSD1306_WHITE);
    d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
    d.setTextSize(1);
    d.setCursor(2, 4);
    d.println(label);
    // center the scale about the vertical axis--and use this to offset the needle, and scale text
    Offset = (270 +  sa / 2) * degtorad;
    // find hte scale step value based on the hival low val and the scale sweep angle
    // deducting a small value to eliminate round off errors
    // this val may need to be adjusted
    stepval = ( inc) * (double (sa) / (double (hival - loval))) + .00;
    // draw the scale and numbers
    // note draw this each time to repaint where the needle was
    for (i = 0; i <= sa; i += stepval) {
      angle = ( i  * degtorad);
      angle = Offset - angle ;
      ox =  (r - 2) * cos(angle) + cx;
      oy =  (r - 2) * sin(angle) + cy;
      ix =  (r - 10) * cos(angle) + cx;
      iy =  (r - 10) * sin(angle) + cy;
      tx =  (r + 10) * cos(angle) + cx + 8;
      ty =  (r + 10) * sin(angle) + cy;
      d.drawLine(ox, oy, ix, iy, SSD1306_WHITE);
      d.setTextSize(1);
      d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
      d.setCursor(tx - 10, ty );
      data = hival - ( i * (inc / stepval)) ;
      d.println(data, dig);
    }
    for (i = 0; i <= sa; i ++) {
      angle = ( i  * degtorad);
      angle = Offset - angle ;
      ox =  (r - 2) * cos(angle) + cx;
      oy =  (r - 2) * sin(angle) + cy;
      d.drawPixel(ox, oy, SSD1306_WHITE);
    }
  }
  // compute and draw the needle
  angle = (sa * (1 - (((curval - loval) / (hival - loval)))));
  angle = angle * degtorad;
  angle = Offset - angle  ;
  ix =  (r - 10) * cos(angle) + cx;
  iy =  (r - 10) * sin(angle) + cy;
  // draw a triangle for the needle (compute and store 3 vertiticies)
  lx =  2 * cos(angle - 90 * degtorad) + cx;
  ly =  2 * sin(angle - 90 * degtorad) + cy;
  rx =  2 * cos(angle + 90 * degtorad) + cx;
  ry =  2 * sin(angle + 90 * degtorad) + cy;

  // blank out the old needle
  d.fillTriangle (pix, piy, plx, ply, prx, pry, SSD1306_BLACK);

  // then draw the new needle
  d.fillTriangle (ix, iy, lx, ly, rx, ry, SSD1306_WHITE);

  // draw a cute little dial center
  d.fillCircle(cx, cy, 3, SSD1306_WHITE);

  //save all current to old so the previous dial can be hidden
  pix = ix;
  piy = iy;
  plx = lx;
  ply = ly;
  prx = rx;
  pry = ry;
  // up until now print sends data to a video buffer NOT the screen
  // this call sends the data to the screen
  d.display();

}

/*

  function to draw a cartesian coordinate system and plot whatever data you want
  just pass x and y and the graph will be drawn huge arguement list

  &display to pass the display object, mainly used if multiple displays are connected to the MCU
  x = x data point
  y = y datapont
  gx = x graph location (lower left)
  gy = y graph location (lower left)
  w = width of graph
  h = height of graph
  xlo = lower bound of x axis
  xhi = upper bound of x asis
  xinc = division of x axis (distance not count)
  ylo = lower bound of y axis
  yhi = upper bound of y asis
  yinc = division of y axis (distance not count)
  title = title of graph
  &redraw = flag to redraw graph on fist call only

*/

void DrawCGraph(Adafruit_SSD1306 &d, double x, double y, double gx, double gy, double w, double h, double xlo, double xhi, double xinc, double ylo, double yhi, double yinc, double dig, String title, boolean &Redraw) {

  double i;
  double temp;
  int rot, newrot;

  if (Redraw == true) {
    Redraw = false;
    d.fillRect(0, 0,  127 , 16, SSD1306_WHITE);
    d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
    d.setTextSize(1);
    d.setCursor(2, 4);
    d.println(title);
    ox = (x - xlo) * ( w) / (xhi - xlo) + gx;
    oy = (y - ylo) * (gy - h - gy) / (yhi - ylo) + gy;
    // draw y scale
    d.setTextSize(1);
    d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
    for ( i = ylo; i <= yhi; i += yinc) {
      // compute the transform
      // note my transform funcition is the same as the map function, except the map uses long and we need doubles
      temp =  (i - ylo) * (gy - h - gy) / (yhi - ylo) + gy;
      if (i == 0) {
        d.drawFastHLine(gx - 3, temp, w + 3, SSD1306_WHITE);
      }
      else {
        d.drawFastHLine(gx - 3, temp, 3, SSD1306_WHITE);
      }
      d.setCursor(gx - 27, temp - 3);
      d.println(i, dig);
    }
    // draw x scale
    for (i = xlo; i <= xhi; i += xinc) {
      // compute the transform
      d.setTextSize(1);
      d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
      temp =  (i - xlo) * ( w) / (xhi - xlo) + gx;
      if (i == 0) {
        d.drawFastVLine(temp, gy - h, h + 3, SSD1306_WHITE);
      }
      else {
        d.drawFastVLine(temp, gy, 3, SSD1306_WHITE);
      }
      d.setCursor(temp, gy + 6);
      d.println(i, dig);
    }
  }

  // graph drawn now plot the data
  // the entire plotting code are these few lines...

  x =  (x - xlo) * ( w) / (xhi - xlo) + gx;
  y =  (y - ylo) * (gy - h - gy) / (yhi - ylo) + gy;
  d.drawLine(ox, oy, x, y, SSD1306_WHITE);
  d.drawLine(ox, oy - 1, x, y - 1, SSD1306_WHITE);
  ox = x;
  oy = y;

  // up until now print sends data to a video buffer NOT the screen
  // this call sends the data to the screen
  d.display();

}

/////////////////////////////////////////////////////////

For my purpose of running this project in my OLED I replaced all SSD1306 keyword with SH1106. Except this project every other projects works on this OLED by replacing SSD1306 keyword with SH1106.
Getting this error in Ardunio IDE 'SH1106_WHITE' was not declared in this scope
Arduino: 1.8.13 Hourly Build 2020/04/21 12:25 (Linux), Board: "Arduino Uno"

/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawBarChartV(Adafruit_SH1106&, double, double, double, double, double, double, double, double, double, String, bool&)':
sketch_oct07a:162:33: error: 'SH1106_WHITE' was not declared in this scope
     d.fillRect(0, 0,  127 , 14, SH1106_WHITE);
                                 ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:162:33: note: suggested alternative: 'SH1106_LCDWIDTH'
     d.fillRect(0, 0,  127 , 14, SH1106_WHITE);
                                 ^~~~~~~~~~~~
                                 SH1106_LCDWIDTH
sketch_oct07a:163:20: error: 'SH1106_BLACK' was not declared in this scope
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:163:20: note: suggested alternative: 'SH1106_128_64'
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
                    SH1106_128_64
sketch_oct07a:187:30: error: 'SH1106_WHITE' was not declared in this scope
   d.drawRect(x, y - h, w, h, SH1106_WHITE);
                              ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:187:30: note: suggested alternative: 'SH1106_LCDWIDTH'
   d.drawRect(x, y - h, w, h, SH1106_WHITE);
                              ^~~~~~~~~~~~
                              SH1106_LCDWIDTH
sketch_oct07a:188:39: error: 'SH1106_BLACK' was not declared in this scope
   d.fillRect(x, y - h, w, h - level,  SH1106_BLACK);
                                       ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:188:39: note: suggested alternative: 'SH1106_128_64'
   d.fillRect(x, y - h, w, h - level,  SH1106_BLACK);
                                       ^~~~~~~~~~~~
                                       SH1106_128_64
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawBarChartH(Adafruit_SH1106&, double, double, double, double, double, double, double, double, double, String, bool&)':
sketch_oct07a:221:33: error: 'SH1106_WHITE' was not declared in this scope
     d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                 ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:221:33: note: suggested alternative: 'SH1106_LCDWIDTH'
     d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                 ^~~~~~~~~~~~
                                 SH1106_LCDWIDTH
sketch_oct07a:222:20: error: 'SH1106_BLACK' was not declared in this scope
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:222:20: note: suggested alternative: 'SH1106_128_64'
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
                    SH1106_128_64
sketch_oct07a:246:47: error: 'SH1106_BLACK' was not declared in this scope
   d.fillRect(x + level, y - h, w - level, h,  SH1106_BLACK);
                                               ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:246:47: note: suggested alternative: 'SH1106_128_64'
   d.fillRect(x + level, y - h, w - level, h,  SH1106_BLACK);
                                               ^~~~~~~~~~~~
                                               SH1106_128_64
sketch_oct07a:247:31: error: 'SH1106_WHITE' was not declared in this scope
   d.drawRect(x, y - h, w,  h, SH1106_WHITE);
                               ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:247:31: note: suggested alternative: 'SH1106_LCDWIDTH'
   d.drawRect(x, y - h, w,  h, SH1106_WHITE);
                               ^~~~~~~~~~~~
                               SH1106_LCDWIDTH
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawDial(Adafruit_SH1106&, double, int, int, int, double, double, double, double, double, String, bool&)':
sketch_oct07a:283:33: error: 'SH1106_WHITE' was not declared in this scope
     d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                 ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:283:33: note: suggested alternative: 'SH1106_LCDWIDTH'
     d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                 ^~~~~~~~~~~~
                                 SH1106_LCDWIDTH
sketch_oct07a:284:20: error: 'SH1106_BLACK' was not declared in this scope
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:284:20: note: suggested alternative: 'SH1106_128_64'
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
                    SH1106_128_64
sketch_oct07a:333:49: error: 'SH1106_BLACK' was not declared in this scope
   d.fillTriangle (pix, piy, plx, ply, prx, pry, SH1106_BLACK);
                                                 ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:333:49: note: suggested alternative: 'SH1106_128_64'
   d.fillTriangle (pix, piy, plx, ply, prx, pry, SH1106_BLACK);
                                                 ^~~~~~~~~~~~
                                                 SH1106_128_64
sketch_oct07a:336:43: error: 'SH1106_WHITE' was not declared in this scope
   d.fillTriangle (ix, iy, lx, ly, rx, ry, SH1106_WHITE);
                                           ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:336:43: note: suggested alternative: 'SH1106_LCDWIDTH'
   d.fillTriangle (ix, iy, lx, ly, rx, ry, SH1106_WHITE);
                                           ^~~~~~~~~~~~
                                           SH1106_LCDWIDTH
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawCGraph(Adafruit_SH1106&, double, double, double, double, double, double, double, double, double, double, double, double, double, String, boolean&)':
sketch_oct07a:388:33: error: 'SH1106_WHITE' was not declared in this scope
     d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                 ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:388:33: note: suggested alternative: 'SH1106_LCDWIDTH'
     d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                 ^~~~~~~~~~~~
                                 SH1106_LCDWIDTH
sketch_oct07a:389:20: error: 'SH1106_BLACK' was not declared in this scope
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:389:20: note: suggested alternative: 'SH1106_128_64'
     d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                    ^~~~~~~~~~~~
                    SH1106_128_64
sketch_oct07a:433:28: error: 'SH1106_WHITE' was not declared in this scope
   d.drawLine(ox, oy, x, y, SH1106_WHITE);
                            ^~~~~~~~~~~~
/tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:433:28: note: suggested alternative: 'SH1106_LCDWIDTH'
   d.drawLine(ox, oy, x, y, SH1106_WHITE);
                            ^~~~~~~~~~~~
                            SH1106_LCDWIDTH
exit status 1
'SH1106_WHITE' was not declared in this scope

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

I am new to this field. Any help will be appreciated.

In the Adafruit_SH1106.h header file, SH1106_WHITE and SH1106_BLACK are defined simply as WHITE and BLACK respectively.
So instead of writing SH1106_WHITE try replacing it WHITE and SH1106_BLACK as BLACK respectively.
Eg:-  fillRect(0, 0,  127 , 14, WHITE);

Also change the SH1106_BLACK to BLACK


text:
Arduino Pro Mini is burned by 12v. Can I save it?
I have this Arduino Pro Mini clone (ATmega328) 5v.
I gave it exactly 12 volts through the RAW power input, but it instantly got hot and started fuming. Fumes were coming out of the area close to the black S4 thingy.
I don't know why, because I thought it can accept up to 12v through that input.
Now when I give it 5v only the middle led is lighting up and it's not connecting to the USB-UART interface anymore.
Is there any chance to save it?

By the description it sounds like you either, hooked the 12v in reverse (damaging the input diode [s5]) or accidentally burned out the power regulator. What happens when you put the 5v (regulated source) to the VCC & GND pins bypassing the regulator?

@Tim_Stewart when I give it 5v through VCC input, the main red light is just lighting up. If I give it 5v through the RAW input, it also lights up, although it is dimmer. In neither case the built-in led (L) is lighting. And also it does nothing when I click on the red button.

@Sergio, what happens if you completely desolder the voltage regulator I circled in my answer I added? Can you then use the Arduino Pro Mini by powering it with a regulated 5V directly to Vcc?

1. Your microcontroller is probably/maybe fine; your tiny little voltage regulator is dead; here's why:
Sergio, yes, you can probably/perhaps save it: your Arduino (the microcontroller--ie: processor at least) is likely just fine, assuming the linear regulator smoked and failed open, meaning it did NOT pass through the raw input voltage to your ATmega328 mcu. It's the linear voltage regulator that is fried! That's this circled component below:

So, desolder that part and throw it away and you can continue using the Arduino just fine. Just power it with a regulated 5V directly to VCC is all and you'll be fine. I've done exactly this on some parts I exploded or smoked the regulator on (see below), and they continued working just fine.
IMPORTANT: if this is a safety-critical part, or a product, throw away the whole Arduino just in case.
Details on the fixes:

Desolder the voltage regular (circled in the image above, and shown desoldered on my Pro Mini in the photo below) and throw the desoldered voltage regulator away.

Power the board now through Vcc with anything between 3.3V and 5V (recommended: a regulated 5V into Vcc, such as the 5V line coming straight out of your USB hub).

Reflash the bootloader with a USBasp programmer (shown in 2nd of the two photos below).

Upload a new blink sketch via the external USB serial UART to blink the built-in LED13. This works fine on my Pro Mini below shown with exploded and desoldered regulator:
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);                       // wait for a half-second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(500);                       // wait for a half-second
}

Unplug the USBasp programmer when done, and continue development with just the external serial UART plugged in.

Here's some photos of my Arduino Pro Mini with exploded voltage regulator that I desoldered. I found it today. The Arduino still works fine! I desoldered the regulator around the year 2014 or so, but just re-flashed the bootloader, uploaded the code, tested it, and took these photos today:
Image 1: Arduino Pro Mini used as a data-logging altimeter in ~2014; photo from today. The voltage regulator exploded (read below), so I desoldered it. Both the power LED (top center of board), and LED13 (bottom-left of board) are ON. The power LED comes on automatically so long as you are powering the board through Vcc and GND from your USB port through your USB UART adapter, and the LED13 is blinking ON here due to the blink sketch above AND by powering the board with Vcc and GND from the USB serial UART to the Pro Mini. Note that the LED13 would NOT light up properly with just the USBasp plugged in, even when it was properly powered and programmed by the USBasp. I think it's because the USBasp was interfering with that pin. Plugging in the external serial UART to the Pro Mini's Vcc and GND fixed that, allowing LED13 to function properly as well while the Pro Mini ran the blink sketch above.

Image 2: External USB serial UART (in the USB hub top port), USBasp programmer wired to program the bootloader (in the USB hub under the USB UART), Pro Mini (bottom left) with power LED ON and LED13 (bottom-left of board) OFF.

On the surface, you didn't do anything wrong! You plugged 12V into the correct pin (RAW, which is the battery-in or voltage in line), and that is within the voltage limits of this part. BUT, what you neglected to consider is the power dissipation capability of this footprint or size of a part. The power dissipation capability is soooo low that realistically, 12V is too much, and will destroy the part.
6 years ago or so I made a couple little data-logging altimeters with the Arduino Pro Mini, connected 12.6V (a fully-charged 3S LiPo battery) to the RAW pin, and 15 seconds later: pop! They exploded! Literally, that little voltage regulator exploded into bits with 12.6V in. After that, I never put more than 8.4V in (a fully-charged 2S Lipo battery), and all was well. Since I was powering it from my main RC plane's 3S LiPo motor battery, this was accomplished by just tapping off of 2 of the 3 cells in the battery by plugging into the correct points on the battery's balance lead. So, I was able to use the same battery but just use 2 of its 3 cells instead of all 3 of them.
These regulators are just so tiny that they can't take much heat is all, and since they are linear regulators, all excess voltage is burned off as heat. Here's a couple example power dissipation calculations to make the point:
Imagine you are drawing 100mA total (0.1A) from this regulator. With 12V plugged in, you have to burn off 12V - 5V = 7V in that regulator chip.
Power_dissipated = Current*Voltage = I*V = 0.1A * 7V = 700mW

700mW is HUGE! Pop! Explosion! Dead voltage regulator chip.
But, if you feed it just 8V this same chip would have to burn off only 8V - 5V = 3V of excess voltage:
Power_dissipated = Current*Voltage = I*V = 0.1A * 3V = 300mW

That's 300mW/700mW = 43% as much power, or 57% less power. These numbers are just for example purposes, but you get the point.
Solution? 1) switch to Arduino Nanos, and/or 2) use a much lower input voltage (ex: 8~9V instead of 12V!). Nanos have MUCH bigger and beefier voltage regulators, and Nanos cost like $1 more when buying the Chinese clones.
2. How to calculate 1) how much power your regulator can dissipate without burning up, and 2) how much current you can therefore draw for different raw input voltages to the voltage regulator:
(Also: I wrote an article on my website covering more of these power, current, and voltage specs--see link here and at bottom.)
By the way, looking at the Pro Mini schematic here, I see that the original board used a MIC5205 linear regulator. The Chinese clone you have certainly uses a different regulator, but let's look up the MIC5205 datasheet for benchmarking purposes. A google search for "mic5205 datasheet" leads me here: https://ww1.microchip.com/downloads/en/DeviceDoc/20005785A.pdf. The device is rated up to 150mA current and up to +16V input voltage, but you must consider power!
The equation for that is hidden on pg 5 here:

Power_dissiplation_max =  P_D_max = (T_J_max – T_A)/theta_JA

theta_JA = thermal resistance from Junction to Ambient = 220 degC/W

T_A = ambient temperature = let's say, 40 deg C (104 deg F)

T_J_max = max junction (internal chip) temperature = +125 degC

So, we crunch the numbers:
P_D_max = (125C - 40C)/220 C/W = 85C / 220 C/W = 0.386W = 386mW max
power.

Final result: this tiny, linear voltage regulator, assuming absolute max junction temperature of +125 C (257 F) [HOT HOT HOT!--not good] and ambient air temperature of 40C (104 F) can dissipate 386mW max power before you risk making it go "pop"!
So, assuming you power it with 12V, how much current can you draw?
Voltage drop across the regulator = V_D = Vin - Vout = 12V - 5V = 7V

Power dissipation in the regulator = P_D = current * voltage drop = I*V_D

Solve for I:
I = P_D/V_D = 0.386W/7V = 0.055A = 55mA current!

With 12Vin and 5Vout, any more than 55mA current draw goes "pop" or smokes the chip!
With 8Vin, however, you could draw:
V_D = 8V - 5V = 3V
I = P_D/V_D = 0.386W/3V = 0.129A = 129mA current

With 8Vin and 5Vout, any more than 129mA current draw goes "pop" or smokes the chip!
So, use a lower input voltage and you can draw much more current! How low can you go? Don't go lower than 5V + dropout voltage. The datasheet on p3 for this regulator shows a max dropout voltage of ~350mV, so stay > 5.35V input to get a regulated 5V output.

That's all for this MIC5205 chip, though. Note that other voltage regulators may have dropout voltages as high as 2~3V, so you'd have to have an input voltage of at least 7V or so to ensure a regulated 5V output. I can't see the numbers well enough on your chip to google for its actual Chinese or whatever datasheet to do the calculations for your chip, but you can use my example calculations above to redo these calculations for any datasheet or part.
Other reading:

Google search for "sot 23-5 power dissipation"

Microchip Application Note AN792: A Method to Determine How Much Power a SOT23 Can
Dissipate in an Application

I also wrote an article on my personal website on 6 Jan. 2014 called "Arduino Power, Current, and Voltage Limitations", here, for more info. on these limitations.

Please explain downvotes. This is one of my more well-thought-out answers, and one where I have real experience with this exact same part and exact same scenario at the exact same input voltage.

Nevermind. I know who downvoted my answer. Enough said. It's not related to the answer quality, educational content, or correctness. Anyone other than that person, please consider the quality and correctness of this answer in making a judgement on whether or not to downvote it or upvote it.

Do not worry about down-votes. The system lets people up or down vote answers as a way of eventually "grading" answers (or questions). A single down-vote means nothing.

Unfortunately I've seen more than one of those cheap voltage regulators fail as a short.

@Pelle, yeah when that is the case, the Atmega328 probably gets killed too.

Thank you for such a thorough answer! I desoldered it completely as you suggested, it still lights up the middle light (but not the built-in one) and also it fails to connect to USB-UART adapter. Sad.

Have you tried reflashing the bootloader? Or, just programming it via ICSP with a USBasp programmer or another Arduino as a programmer?

The lights you are describing don't mean anything to me. I don't have easy access to a Pro Mini right now to play with and I don't know what LEDs you're referring to when you say "middle one" and built-in one. It has a power led that should light when it's on, and an LED on pin 13 which should only light up if you programmed it to. I don't know what program you have loaded, and you may need to reflash the bootloader and reload the program.

I just checked the schematic. The power LED, right under the voltage regulator, should NOT turn on with 5V connected to VCC unless you've soldered the SJ1 jumper closed.

@Sergio, see the new "Details on the fixes" section in my answer now. I found my exact Pro Mini with exploded voltage regulator from > 6 yrs ago and just programmed it today. It worked fine in my case. You may just need a new bootloader on it, or to check your Vcc and GND connections from external USB serial UART to the Pro Mini. I'm hoping your board isn't really dead, but...perhaps it is. Before making that final determination though, try these new steps.

Downvote trolls here too huh? Is there a community on SE that doesn't have them?

Wall adapters are not all the same. They can have AC and DC outputs. The DC outputs can be regulated or unregulated. Assuming 1 12V DC wall adapter unregulated you can get maybe 19Vdc from it depending on the design.Always check first, it is much more cost effective then going to the store to buy a new Arduino and what other devices.

Unfortunately, it sounds like it is dead.
I did this early on when I started with arduinos.
In my case I plugged in a "12v 1amp" wall adapter from a linksys router that I didn't check with a DMM to a uno-R3 barrel jack.
The adapter was putting out 22v @ god only knows how many amps. But it had the exact same symptoms I am sorry to say.
I wound up going with a cheap 5v/3.3v selectable breadboard power supply. You might want to look into those for future use, I got mine for less than $3 on eBay.
https://www.ebay.com/itm/1pcs-Breadboard-Power-Supply-Module-Shield-3-3V-5V-MB102-Solderless-Bread-Board/133519600754?hash=item1f16636c72:g:9NcAAOSwZzNfYHel

god only knows how many amps - adapters don't "put out amps". They have a capacity for current. That's like saying I dipped my cup into a pond "god knows how much water was in it". You get out the amount you require. The excess capacity is not a problem.

@nick gammon, the point I was trying to make was the 12v adapter was damaged, I didn't check it. Once that part is blown, does it have the same resistance? (I.e volts / resistance = amps). Am I missing something?

Unregulated adapters may well have a higher voltage under little load. They would be designed to output (in your case) around 12V under the load of the device it is designed for. Regulated adapters output the advertised voltage (or should do) regardless of the load.


text:
My servo wont follow my cam
So i am trying to make the servo follow my face which will end up my camera following my face
But the servo isnt doing anything please look at this
(Also im only using Horizontal because I would like to start off with that first)
Question : how do i make it so it can move, what am i doing wrong?
Python code : https://pastebin.com/V6SegsQj
Arduino code :
#include<Servo.h>
Servo servoHor; //Horizontal Servo
int x;
int prevX;
void setup()
{
  Serial.begin(9600);
  servoHor.attach(6); //Attach Horizontal Servo to Pin 6
  servoHor.write(90);
}

void Pos()
{
  if(prevX != x)
  {
    int servoX = map(x, 600, 0, 70, 179);
    servoX = min(servoX, 179);
    servoX = max(servoX, 70);
    servoHor.write(servoX);
  }
}

void loop()
{
  if(Serial.available() > 0)
  {
    if(Serial.read() == 'X')
    {
      x = Serial.parseInt();
    }
    while(Serial.available() > 0)
    {
      Serial.read();
    }
  }
}

Pos() is never being called. It can't ever do anything.


text:
Can not upload to Arduino Nano BLE 33
I am new so please be nice :)
I am trying to upload the Blinky example to my Arduino Nano BLE 33 but I get this error message from the Arduino IDE:
No device found on ttyACM0
Set binary mode
Send auto-baud
An error occurred while uploading the sketch
Set binary mode

Any idea what I could try?
I am running the Arduino IDE as superuser in Manjaro (latest versions of everything). If you need any more information please feel free to ask.
Full IDE output:
Sketch uses 77820 bytes (7%) of program storage space. Maximum is 983040 bytes.
Global variables use 42192 bytes (16%) of dynamic memory, leaving 219952 bytes for local variables. Maximum is 262144 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
Uploading using selected port: /dev/ttyACM0
/root/.arduino15/packages/arduino/tools/bossac/1.9.1-arduino1/bossac -d --port=ttyACM0 -U -i -e -w /tmp/arduino_build_408944/Blink.ino.bin -R
No device found on ttyACM0
Set binary mode
Send auto-baud
An error occurred while uploading the sketch
Set binary mode

try a double-reset and then upload

are you being logged in as a root?

if you are running  as both user and root, the udev may have mapped device for user already, and as such is bussy with another process
Try sticking to user and giving yourself sufficient rights. it is not a good idea to do too much stuff as a root. Well build modern distro (less then 10 year old should give you sufficient access without need to resort to un-safe practices). If you are on advanced user distro (eg Gentoo)  see suitable Arduino How--to

Send us a picture of: Tools->Port (or write options down) when trying to program. they would be something like /dev/
Although tell us if you are using wired or wireless programming

@Tomas, the uploader output in Question shows, it can access the port

I have already tried double resetting, that did not work.
I am logged in as root.
I do not run as both user and root, however you are right and I should not run it as root. I did so to have the sufficient rights for sure.
The option for the Port is: /dev/ttyACM0 (Arduino Nano BLE 33)
Thank you guys.

Update: I just tried in Windows and uploading works fine here...
And now it is working in Manjaro as well, very weird.

It appears you are using Linux. In order to communicate you must establish yourself as being allowed to use it, that is the dial out function. "sudo usermod -a -G dialout " should work but you need to log out then back in before it takes effect. After that you are all set.

I am not sure if he is using serial port or over Bluetooth as I am not sure if nano BLE supports over bluetooth programing. (otherwise the nano may be mapped to /dev/ttyUSB0 (number may change).
While I appreciate that on ubuntu (Debian based Distros) you use sudo, but not all distros (I personally keep sudo disabled). Adding user to dialout group is only correct step on some distros and only for some form of programing... Better follow tutorial for your distro

the uploader output in Question shows, it can access the port. for access rights settings on Linux I am sure we have an answer here somewhere so this would be a duplicate

When trying to add the user to the dialout group I get this message: "usermod: group 'dialout' does not exist". However I am running the Arduino IDE as superuser so I should have sufficient rights.
I am using the USB port of the board to program it.
Unfortunately I have not found a solution for this problem anywhere.
Thank you guys.

I never run in supervisor as I can do a lot of damage to the system. Beyond this I cannot offer anymore help.


text:
Configure Arduino IDE to not quit when the last sketch is closed
The Arduino app takes a long time to launch on MacOS. (The Initializing Packages... stage takes over a minute.) It's very frustrating when you accidentally close the last sketch window and the app quits. Then you have to wait for it launch again.
Is there anything that can be done to stop it from closing automatically?

no, it's a single-document-interface (one app instance per sketch), so there's no "basket" to keep around like with multiple-document interfaces such as photoshop, notepad++, excel, etc

But opening additional documents happens instantly. You don't have that slow launch experience until after you close the last document.

It used to warn you when you tried to do that, I don't know why that warning was removed.

yes, some of the background processes, notably java, are shared between instances, so the first one is slower. You can try using some tool to hide the first instance so it can't be closed. on windows there was an app called "process control" which allowed that, not sure about mac...


text:
Many "expected `)' before ';' token" errors
As the title suggests, I have many "expected `)' before ';' token" errors. The issue is, I have this stuff in. So now I am confused, why am I getting this if the things are there.
I am new here and had an issue with adding code, so here is the pastebin link to it: http://pastebin.com/4WXxsXkB
And here is the the pastebin link to the error:
http://pastebin.com/QyehP86M
Does anyone understand how this could happen?

#defines do not have a ';' after them try removing these

You have two #define statements at the top of your code
#define trigPin 3;
#define echoPin 2;

The way #define works is that it replaces every instance of the name with everything after it on the line so trigPin is being replaced with 3; as opposed to 3 as intended.
Fixing this should solve some of your problems.


text:
How can I determine how many bytes an I2C master read from my Arduino acting as I2C slave?
I have an Atmega328 programmed using the Arduino software and libraries (but is standalone on on a board in the TSOP package) without bootloader and with ISP programming). I am using the Wire library to act as an I2C peripheral, where I implement (and register) the requestEvent and receiveEvent callbacks.
Is it possible to determine, either during the requestEvent callback or after it at some point, how many bytes were read by the master before it sent a NACK?

You can't.
The master will have to inform the slave how many bytes to transfer, or the master will have to query the slave how many bytes there are to receive.

I understand that the protocol doesn't specify that. I'm interested in getting the number of bytes that were actually sent by the slave until the master sent a NACK instead of an ACK, as I specified originally in the question (be it through another callback, by calling a Wire function, etc), after the send actually completes.

*actually completes at the physical level, after the master sends the NACK.

You have no access to that level of information through the API. You can count how many times your callback is called, but that's as close as you get. You would have to work out some way of knowing what is the first transfer though.

You would have to work entirely at the register level and implement your own I2C code.

OK, that clarification answers the question perfectly.


text:
Arduino parsing of a string using sscanf
Hello I am new to Arduino and C programming.
I wanted to parse string using sscanf fuction
This is my Program
String hith;
int field1,field2;
float field3;
int F1=0,F2=0;
float F3=0;
int h1,h3;
float h2;

void setup() {

  Serial.begin(9600);

}

void loop() {
  field1=5;
  field2=6;
  field3=56.67;
  F1=field1;
  F2=field2;
  F3=field3;

  hith =hith+F1+","+F3+","+F2;
  Serial.println(hith);

sscanf(hith.c_str(),"%d,%f,%d",&h1,&h2,&h3);

Serial.println(h1);
Serial.println(h2);
Serial.println(h3);
  hith="";

  delay(1000);
}

I am only able to Parse Integer values but not Floating points.

%f is not implemented in the Arduino world.

On 8-bit Arduinos support for %f from printf and scanf (and related functions) has been removed to save space.
Instead you should look at parsing the string into chunks with strtok() and use atof() to convert relevant chunks to floating point.