body:
when reading RFID(MIFARE) information using Arduino mega and display in serial monitor it works fine. But, when printing on 2004LCD only one information(Value) displays correctly. The other information Item Name display a decimal number. Could someone help on this?

     void Price(){
          block = 4;
          status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid));
          if (status != MFRC522::STATUS_OK) {
            Serial.print(F("Authentication failed: "));
            Serial.println(mfrc522.GetStatusCodeName(status));
            return;
          }
          status = mfrc522.MIFARE_Read(block, buffer1, &len);  // ***Note down buffer1 within the bracket
          if (status != MFRC522::STATUS_OK) {
            Serial.print(F("Reading failedl: "));
            Serial.println(mfrc522.GetStatusCodeName(status));
            return;
          }
                 //Display price information...
          for (uint8_t i = 0; i < 16; i++)
          {
            if (buffer1[i] != 32) // if buffer1[i] not equal to 32
            {
              Serial.write(buffer1[i]);  //Price
             //lcd.write(buffer1[i]);
              Value = buffer1[i];
              }
           }
          Serial.print("/=");
          Serial.println(" ");
          sscanf(buffer1,"%d",&Value);
          lcd.setCursor(0,1);
          lcd.println(Value);

         }
        //==========================================================
        void Item(){ //----- Get & Display Item information
            block = 1;
         status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid));
          if (status != MFRC522::STATUS_OK) {
            Serial.print(F("Authentication failed: "));
            Serial.println(mfrc522.GetStatusCodeName(status));
            return;
          }
          status = mfrc522.MIFARE_Read(block, buffer2, &len);
          if (status != MFRC522::STATUS_OK) {
            Serial.print(F("Reading failed: "));
            Serial.println(mfrc522.GetStatusCodeName(status));
            return;
          }
          for (uint8_t i = 0; i < 16; i++) { //
             Serial.write(buffer2[i]);       // Display Item
             lcd.write(buffer2[i]);
             Item_Name=buffer2[i];
            }
            sscanf(buffer2,"%s",&Item_Name);
           //sprintf(buffer2,"%d",&Item_Name);
              lcd.clear();
              lcd.setCursor(0,0);
              lcd.print(Item_Name);// displays numbers instead of "Fresh Milk 1Lt
         }

[![lcd][1]][1]
[![Serial op][2]][2]

  [1]: https://i.stack.imgur.com/9Cucx.jpg
  [2]: https://i.stack.imgur.com/jQwtI.jpg

title: lcd byte array display

Answers: 1

body:
Consider the following:

```c++
char buffer2[16];  // array of 16 chars
for (uint8_t i = 0; i < 16; i++) {
    do_something_with(buffer2[i]);  // handle one char at a time
}
```

Here we have an array of 16 cells, each having the `char` type (which I
assume is what you have). The loop goes through the array, handling one
cell a time. Within the loop, `buffer2[i]` represents the `char` being
currently handled.

Keep in mind that a `char` is just an 8-bit integer. It is somehow
implied that it is meant to represent a character, where 32 = `' '`
(space), 33 = `'!'`, 48 = `'0'`, 65 = `'A'` and so on (see [ASCII][]).
The Arduino `print()` methods do assume a `char` (unlike an `int`) is
intended to be displayed as a character.

Now your actual loop:

```c++
int Item_Name;
for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);  // write the char on the serial port
    lcd.write(buffer2[i]);     // write the char on the LCD
    Item_Name=buffer2[i];      // store the char in a variable
}
```

This will print the contents of the buffer to both the serial port and
the LCD. You would have seen the expected message on the LCD if you did
not have `lcd.clear()` right after the loop.

```c++
sscanf(buffer2, "%s", &Item_Name);
```

This means “extract from `buffer2` a sequence of contiguous
non-white-space characters, and store it in memory at the address of the
variable `ItemName`”. If the buffer contains “Fresh Milk 1Lt”, this will
write “Fresh” to that memory location. That is 6 bytes (5 letters and a
terminating NUL). Unfortunately, the compiler has only allocated 2 or
4 bytes of RAM for storing `ItemName` (depending on the Arduino model),
so this will write past the allocated storage, which is a type of bug
known as [buffer overflow][]. Now your Arduino's memory is corrupted and
anything can happen.

```c++
sprintf(buffer2, "%d", &Item_Name);
```

This tries to find within `byffer2` a textual representation of a
number, and store it into `Item_Name`. This is safe, but only makes
sense if the buffer contains a number, written as text, which is not the
case here.

```c++
lcd.print(Item_Name);
```

This is asking the LCD to print an integer (namely `Item_Name`). It will
convert the integer to decimal text and print the corresponding digits
on the LCD.

Let's assume for example that `Item_Name` contains the numeric value
`32` (which is the ASCII representation of a space). `lcd.print()` will
convert that into a sequence of two characters: `'3'` and `'2'` (the
decimal representation of 32). It will then send those characters to the
LCD (ASCII values 51 and 50), and you will see the text “32”.

If you want to see the text contained within the buffer, the you can
either send the characters one by one (like you already did right before
`lcd.clear()`), or provide to `lcd.print()` a `char*` pointer with the
whole message:

```c++
lcd.print(buffer2);
```

This assumes that the buffer is terminated with a NUL character. If it
is not, then you can either use the char-at-a-time method, or change
your code in order to put a NUL terminator in the buffer.

[ASCII]: https://en.wikipedia.org/wiki/ASCII
[buffer overflow]: https://en.wikipedia.org/wiki/Buffer_overflow


body:
In my ESP32 project I have the following platformio.io file:

    [env:esp32-poe]
    platform = espressif32
    board = esp32-poe
    framework = arduino
    lib_deps =
     openslab-osu/SSLClient@^1.6.7
     knolleary/PubSubClient@^2.8
     bblanchon/ArduinoJson@^6.16.1
    monitor_speed = 115200

    [env:custom_builtin_table]
    board_build.partitions = default.csv

the [default.csv][1] table is this one:

    # Name,   Type, SubType, Offset,  Size, Flags
    nvs,      data, nvs,     0x9000,  0x5000,
    otadata,  data, ota,     0xe000,  0x2000,
    app0,     app,  ota_0,   0x10000, 0x140000,
    app1,     app,  ota_1,   0x150000,0x140000,
    spiffs,   data, spiffs,  0x290000,0x170000,

I noticed that when I upload the code to my ESP32 the output is like this:

    [...]
    Configuring flash size...
    Auto-detected Flash size: 4MB
    Compressed 17104 bytes to 11193...
    Writing at 0x00001000... (100 %)
    Wrote 17104 bytes (11193 compressed) at 0x00001000 in 0.3 seconds (effective 521.5 kbit/s)...
    Hash of data verified.
    Compressed 3072 bytes to 128...
    Writing at 0x00008000... (100 %)
    Wrote 3072 bytes (128 compressed) at 0x00008000 in 0.0 seconds (effective 5621.7 kbit/s)...
    Hash of data verified.
    Compressed 8192 bytes to 47...
    Writing at 0x0000e000... (100 %)
    Wrote 8192 bytes (47 compressed) at 0x0000e000 in 0.0 seconds (effective 27422.0 kbit/s)...
    Hash of data verified.
    Compressed 1003456 bytes to 585011...
    Writing at 0x00010000... (2 %)
    [...]

Hence, it writes at:

- 0x1000
- 0x8000
- 0xe000 (otadata)
- 0x10000 (app0)

But I cannot understand what are the first two writings.

  [1]: https://github.com/espressif/arduino-esp32/blob/master/tools/partitions/default.csv

title: ESP32 partition table and writing location

Answers: 1

body:
0x1000 is the "second stage" bootloader. This is the code that is responsible for loading the code according to the layout specified in the partition table.

> In ESP-IDF, the binary image which resides at offset 0x1000 in flash is the second stage bootloader. Second stage bootloader source code is available in components/bootloader directory of ESP-IDF. Note that this arrangement is not the only one possible with the ESP32 chip. It is possible to write a fully featured application which would work when flashed to offset 0x1000, but this is out of scope of this document. Second stage bootloader is used in ESP-IDF to add flexibility to flash layout (using partition tables), and allow for various flows associated with flash encryption, secure boot, and over-the-air updates (OTA) to take place.

0x8000 is the partition table itself.

> Second stage bootloader reads the partition table found at offset 0x8000. See partition tables documentation for more information. The bootloader finds factory and OTA partitions, and decides which one to boot based on data found in OTA info partition.

All this is detailed in the [ESP-IDF manual](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/general-notes.html).


body:
I am writing an SIM900A + arduino(Arduino UNO with Atmega 328P) code to just send the current time stamp every 20 minutes.
The code keeps crashing in the `SendMessage()` function as the setup prints keep coming again and again. Please let me know what I am doing wrong. Thanks in advance
```
#include <SoftwareSerial.h>
#include <LowPower.h>
SoftwareSerial mySerial(9, 10);
char msg;
char call;
int ctr;

#define TIME_STR_LEN 100  // the actual number of characters for date and time

char timeStamp[TIME_STR_LEN]; // holds the time string

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  Serial.println("GSM SIM900A BEGIN");
  mySerial.println( "AT+CLTS=1");
  delay(1000);
  ctr = 0;
  delay(10000);
}

void loop()
{

  if(mySerial.available()>0)
  {
    while (mySerial.available()>0)
    {
      mySerial.read();
    }
  }

  if (ctr%1 == 0)
  {
    delay(1000);
    SendMessage();
    delay(100);
    ctr = 0;
    Serial.println("just sent a message");
  }
  delay(60000);
  ctr++;
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART0_OFF, TWI_OFF);
}

void SendMessage()
{
 mySerial.println( "AT+CCLK?" );
 delay(2000);

 int i = 0;

 if (mySerial.available()>0)
 {
      while (mySerial.available()>0 && i < TIME_STR_LEN)
      {
        timeStamp[i]=(mySerial.read());
        i++;
      }
  }
  delay(2000);

  mySerial.println("AT+CMGF=1");
  delay(1000);
  mySerial.println("AT+CMGS=\"xxxxxxxxxx\"\r");
  delay(1000);
  mySerial.println("Motor is ON ");
  delay(100);
  mySerial.println(timeStamp);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}
```

title: Arduino code crashing

Answers: 0


body:
I'm using **[botletics / SIM7000-LTE-Shield][1]** with Arduino Uno. I ran LTE-Demo example with the following adjustments based on this **[source][2]**:

 - fona.setNetworkSettings(F("**jawalnet.com.sa**"));
 - fona.setPreferredMode(**2**);
 - fona.setPreferredLTEMode(**3**);
 - fona.setOperatingBand("**NB-IOT**", **12**);
 - fona.enableRTC(**true**);

But I'm getting no where and there is no registered network. I even tried Band (**CAT-M**) with *no luck*

I'm powering the shield from UNO with no external battery. 2 Green leds are led + blue led is flashing

**Any Idea what am I doing wrong?**

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    FONA basic test
    Initializing....(May take several seconds)
    Configuring to 9600 baud
    Attempting to open comm with ATs
     ---> AT
     <--- AT
     ---> ATE0
     <--- ATE0
     ---> ATE0
     <--- OK
     ---> ATI
     <--- SIM7000G R1529

    OK

     ---> AT+CPMS="SM","SM","SM"
     <--- +CPMS: 0,100,0,100,0,100
    FONA is OK
    Found SIM7000
     ---> AT+GSN
     <--- 869951031081155
    Module IMEI: 869951031081155
     ---> AT+CFUN=1
     <--- OK
     ---> AT+CGDCONT=1,"IP","jawalnet.com.sa"
     <--- OK
     ---> AT+CNMP=2
     <--- OK
     ---> AT+CMNB=3
     <--- OK
     ---> AT+CBANDCFG="NB-IOT",12
     <--- OK
     ---> AT+CLTS=1
     <--- OK
     ---> AT&W
     <--- OK
    -------------------------------------
    [?] Print this menu
    [a] Read the ADC; 2.8V max for SIM800/808, 0V-VBAT for SIM7000 shield
    [b] Read supply voltage
    [C] Read the SIM CCID
    [U] Unlock SIM with PIN code
    [i] Read signal strength (RSSI)
    [n] Get network status
    [1] Get network connection info
    [c] Make phone Call
    [A] Get call status
    [h] Hang up phone
    [p] Pick up phone
    [N] Number of SMSs
    [r] Read SMS #
    [R] Read all SMS
    [d] Delete SMS #
    [s] Send SMS
    [u] Send USSD
    [y] Enable local time stamp (SIM800/808/70X0)
    [Y] Enable NTP time sync (SIM800/808/70X0)
    [t] Get network time
    [G] Enable cellular data
    [g] Disable cellular data
    [l] Query GSMLOC (2G)
    [O] Turn GPS on (SIM808/5320/7XX0)
    [o] Turn GPS off (SIM808/5320/7XX0)
    [L] Query GPS location (SIM808/5320/7XX0)

    -------------------------------------

    FONA> C
     ---> AT+CCID
     <--- 8996601730099550895f
    SIM CCID = 8996601730099550895f
    FONA> n
     ---> AT+CREG?
     <--- +CREG: 0,2
    Network status 2: Not registered (searching)
    FONA> l
     ---> AT+CIPGSMLOC=1,1
     <--- ERROR
    Failed!
    Fail code #2
    FONA> n
     ---> AT+CREG?
     <--- +CREG: 0,2
    Network status 2: Not registered (searching)
    FONA>  n
 ---> AT+CREG?
 <---
    Network status 0: Not registered
    FONA>

<!-- end snippet -->

  [1]: https://github.com/botletics/SIM7000-LTE-Shield
  [2]: https://halberdbastion.com/intelligence/mobile-networks/saudi-telecom-company-stc

title: SIM7000G Connectivity Issue

Answers: 0


body:
For a specific project, I need to convert an int to a const int variable type.

    int i = 10;
    boolean ShiftRegister[i] //Throws error

    const int i = 10;
    boolean ShiftRegister[i]// Works Fine

as i am making my own custom library where the size of boolean can be defined by creating an object by the user

    myLib Library(20); // user defined boolean size

 and the size is stored to a struct like this as it can't directly be converted to a const int.

The header file ...

    #ifndef myLib_h
    #define myLib_h
    #include "Arduino.h"

    class myLib{

    public:
    myLib(int input);
    private:
    int input;

    };
    #endif

the C++ code

    #include "myLib.h"
    #include "Arduino.h"

     struct Data {
      int BoolSize;
     }Data[0];

     myLib::myLib(int input){
     Data[0].BoolSize=input
     }

     const int boolSize = Data[0].BoolSize;

     bool DataBoolean[boolSize];

Whenever i run this library, it throws an error untill i dont predefine the boolean size in cpp code like this..

    bool DataBoolean[20];

that means there is something error converting the int to const int in this line

    const int boolSize = Data[0].BoolSize;

so what i want is, i dont want to predefine the boolean size in the cpp code. i would rather like to
define boolean size by creating an object(where the code crashed), storing the size to a structure then assigning the structure integer to the const int variable. I need an efficiant way to

turn this struct variable

    Data[0].BoolSize;

into a const variable and assign to it like this without any errors

    const int boolSize = Data[0].BoolSize;

so how can i convert an integer to a const int so that i can continue to my project?

any helps please? thanks for your kind support.

title: How to convert an int to const int in Arduino?

Answers: 2

body:
At the time the constructor of your class is called, its size must be already defined, because the memory allocation takes place before. But you try to give it as a parameter to the constructor. This cannot work.

You have at least these alternatives. *(Note: This is an invitation to edit this answer and add more, if you know some serious solution.)*

### 1. Use a template for the size

Please be aware that each different size will generate another implementation in machine code.

```c++
template<size_t size>
class myLib {
public:
    inline myLib<size>() {}
private:
    bool data[size];
};
```

### 2. Allocate the requested memory dynamically

```c++
class myLib {
public:
    inline explicit myLib(size_t size) : data(new bool[size]) {}
    inline ~myLib() {
        delete[] data;
    }
private:
    bool* data;
};
```

*Note: Depending on the version of C++ you're using, you need to consider the [Rule of Three][1] (before C++11) or the [Rule of Five][2] (beginning with C++11). Since the implementation of the missing methods depends on specific details, it is left as an exercise to the reader.*

  [1]: https://en.wikipedia.org/wiki/Rule_of_three_(C++_programming)
  [2]: https://en.wikipedia.org/wiki/Rule_of_three_(C++_programming)#Rule_of_Five

body:
If you want variable length of an array, then you can use malloc.
With same conext, if you want to initiate an array with specific length of value you have to use malloc.


body:
I have bought the [Brushless DC-Flat Motors Series 2610][1] and Pin number 6 is called FG which is defined as frequency output. I have plugged this pin into the Arduino in A0 and I have tried displaying the outputs. The outputs is either 0 or 1023 and I am not sure how I can convert this to angular speed or RPM. Any help will be appreciated

  [1]: https://www.faulhaber.com/en/products/series/2610b-sc/

title: FG Frequency output

Answers: 0


body:
I'm giving Visual Studio Code (VSC) a try and am getting unexpected results. I have a program (sketch) that compiles fine in the Arduino IDE. I create a workspace in VSC, initialize the project, and after some more mucking about I get a compile there appears to succeed:

    [Done] Finished verify sketch - RanchMonitor2.ino

But the console pane shows four "problems":

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

How can the compilation have succeeded if there are problems?

The same sort of thing is happening with one of the samples - HelloServer.ino
In this case the problems are an incomplete type and memcpy_P not defined.

I wouldn't think it should make a difference, but I'm working without a board physically attached to the USB port.

UPDATE:
I think "Problems" are issues identified by Intellisense. They appear even before a compilation is attempted. All I have to do is open the workspace and wait a few seconds, then the "problems" appear. Hence my conjecture they are Intellisense warnings, not compilation errors.
Adding "ESP8266" to the Defines section of c_cpp_properties.json got rid of the error "WiFiManager" is undefined.

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

title: Compiling for Wemos D1 mini with Visual Studio Code

Answers: 1

body:
Intellisense reports "Problems" - these are distinct from compile time errors. Just because Intellisense can't resolve a literal or something doesn't mean it won't be resolved in the compiler; thus it's possible to have the IDE report a problem but still be able to have a successful compile. In the case described above, two changes to the c_cpp_properties.json file provided Intellisense with the information it needed. A header file was added to the forcedInclude section to provide pin definitions. A literal "ESP8266" was added to the defines section to indicate the processor type. This define is used in lots of header files so it must be know to Intellisense when reading the headers. Here are the relevant sections of that .json file:

            "forcedInclude": [
                "C:\\Users\\David\\AppData\\Local\\Arduino15\\packages\\esp8266\\hardware\\esp8266\\2.7.1\\variants\\d1_mini\\pins_arduino.h"
            ],
            "defines": [
                "USBCON",
                "ESP8266"
            ],


body:
I'm using pyserial to communicate with my arduino. I set up the connection and everything works fine. Now I have these two writing commands:

```python
pyserial.write("conn".encode())
pyserial.write("mod1".encode())
```

On my arduino:

```c++
while (!Serial.available());
String s = Serial.readString();
if (s=="conn") do...;
if (s=="mod1") do...;
```

The problem is that none of the `if` statements are true because `s` becomes `"connmod1"`, because the messages are sent almost at the same time I guess. I know I could use some delimiter to split the string, but I would like to know what the convenient solution might be?

title: How to use pyserial to write two separate message?

Answers: 1

body:
If you want a quick, cheap, and easy solution, you could just use `sleep()` in your Python script to put a delay between the commands. This obviously isn't a perfect solution, but it's not difficult to implement.

Or, like you said, you could use a delimiter. It's not as easy to implement, but it'll work better.

If you go the delimiter rout, you'll probably need to use `Serial.read()` instead of `Serial.readString()`. That way you can examine characters individually as they come in. You can store your characters in a String or char array until you detect your delimiter and then execute your command.

Hope that helps!


body:
I want to include a function in my sketch I moved to a .h file.

I did it as follows:

My code:
```
#include "header.h"

void setup() {
  fct();
}

void loop() {

}
```

My header:
```
#include "Arduino.h"
#ifndef MYHELPERS_H
#define MYHELPERS_H

void fct() {
// stuff
}

#endif
```

The same process seems to work for variables but the IDE says this function in not declared in this scope...

I don't understand what I'm doing wrong...

Thanks guys!

title: Using functions in header files

Answers: 1

body:
I found a solution somewhere else on internet...

This portion:

    #ifndef MYHELPERS_H
    #define MYHELPERS_H

Was not written correctly... "MYHELPERS_H" should've been replaced by the name of my file. Now it works just fine.


body:
I have been having trouble finding any recourses for a DAC chip that I bought. It is the HiLetgo PCM5102 DCA.

https://www.amazon.com/gp/product/B07Q9K5MT8/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1

There are 6 ports to be routed. VIN, GND (I know these) LCK, DIN, BCK, SCK, but the rest are a mystery to me. The Adafruit version has tutorials online but I got this one because of the built in 3.5mm jack is what I really needed. Any and all help is greatly appreciated. Let me know if I need to post any other resources.

I am trying to read the audio data coming in from songs through the 3.5mm jack.

Here is the data sheet for the Adafruit version of the DCA with a 3.5mm audio jack

I am asking for help in reading audio data from the input jack.

https://cdn-learn.adafruit.com/downloads/pdf/adafruit-i2s-stereo-decoder-uda1334a.pdf

title: Proper wiring for a HiLetgo DAC to Arduino

Answers: 0


body:
I've been trying to implement a project that's been in my head for a while, I want to wirelessly control my light and fan switches using an ESP32 and 2 servos (one for each switch) through an HTML page, and then later integrate it with Alexa

I have seen how **one** servo can be controlled by connecting the servo's power cable to the ESP32's Vin pin, but how can I control **two**? I want to avoid using an external power supply like a battery pack because I want it to be a completely automated process, and I don't want to have to keep switching out batteries often for the thing to work. I'll be using a 5V wall outlet to power the ESP32 using a USB.

Also, if anyone can provide a few more tips on how I can make my project more efficient or point out where I might be making a mistake, I'd be glad. I'm still new to the microcontroller world.

Thanks

**EDIT** :  I've attached a picture of the circuit diagram, just have a look and let me know if it is workable[![enter image description here][1]][1]

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

title: How can I control 2 servos without an external power supply?

Answers: 1

body:
The power wire is just needed, well, to power the servo. The control is done via the third wire (the other wire being Ground).

You can connect the second servo's power in parallel, only the control wire must be separated from the first servo's control wire.

*Note: You need to make sure that the current consumption of both servos does not exceed the provided power.*


body:
I am using the following SEN0114 moisture sensor with an ESP32:  https://datasheetspdf.com/datasheet/SEN0114.html

How come when submerged in water I only get a reading of ~2500?  Should this not read ~4095 as the ESP32 analog pins are 12-bit?

title: SEN0114 moisture sensor low max reading?

Answers: 1

body:
This is a resistive sensor and "plain" water is not infinitely conductive. In fact, pure or distilled water is a very poor conductor. Also, "plain" water - tap water, I assume - will vary in its dissolved solids, not only from source to source, but likely over time, too, for some sources and it is these solutes that are responsible for increased conductivity. That goes double for plant-moisture sensing because it is really measuring the resistance of damp dirt, which again, varies in composition.

So the sensor can give you a range from dry to very moist, *per plant*, but the absolute measurements won't be very meaningful.


body:
I have a sketch that prints out a value from 0 to 100.  I want it to take up the whole screen.

I can't figure out how to make the font bigger I think that the part of the code defines the size of the font is :

        oled.setFont(System5x7)

But if I alter the value 5x7 it just spits out errors messages.

This is all the code:

```c++
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"
SSD1306AsciiAvrI2c oled;
#define I2C_ADDRESS 0x3C

int TankValue0;
int TankValue1;

void setup() {
  Serial.begin(9600);
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
  oled.setFont(System5x7);
  oled.clear();
}

void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 300, 785, 100, 0);
  TankValue1 = map(sensorTankValue1, 300, 785, 000, 0);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  oled.print(TankValue0);
  oled.print(" L");
  oled.println(" ");
  //oled.print("T1=");
 // oled.print(TankValue1);
 // oled.println(" ");
  oled.setCursor(0, 0);
  delay(1000);
}
```

title: OLED 128x64 make text bigger

Answers: 0


body:
I bought this tft display on Aliexpress:
https://www.aliexpress.com/item/1005001579367288.html?spm=a2g0s.9042311.0.0.72164c4doyqAub

it says "MCUDEV_TFT1.44" below the display.

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

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

I can't find online how to connect it to Arduino.
The pins are as follows:
BLK RS RST CS SC DI GND VCC

on Aliexpress it says "Drive IC: ST7735" but I googled ST7735 displays and they have different pins.
Anyone has any idea?
Thanks!

title: anyone heard of MCUDEV_TFT1.44 display? I can't figure out how to connect it to Arduino

Answers: 1

body:
If anyone else have the same display and wondering how to make it work, here is how I connected and the script I used.

I couldn't find my display model so I just used this in Fritzing and added the pins names as a note.

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

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

#define TFT_CS        10
#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
#define TFT_DC         8

#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

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

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

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

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

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

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
  delay(1000);

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

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

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

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

  testdrawrects(ST77XX_GREEN);
  delay(500);

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

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

  testroundrects();
  delay(500);

  testtriangles();
  delay(500);

  mediabuttons();
  delay(500);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

**LIBRARIES:**
* Go to Sketch -> Include Library -> Manage Libraries
* Search for **Adafruit GFX Library** and install the latest version and install all the dependencies as well when it asks
* Search for **Adafruit ST7735 and ST7789 Library** and install the latest version and install all the dependencies as well when it asks

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


body:
Arduino Nano Every [schematic][1] informs us that we can use ATMega4809's pins PF03 and PF02 to communicate via I2C.

[ATMega4809 manual][2] says in page 19 that in order to use those pins as I2C we need to use PORTMUX.

I'm not really an expert and I don't understand how to do that.
Any help would be approciated.

  [1]: https://content.arduino.cc/assets/NANOEveryV3.0_sch.pdf
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega4808-4809-Data-Sheet-DS40002173A.pdf

title: Arduino Nano Every I2C PORTMUX

Answers: 1

body:
In the Nano Every schematic, PF2 and PF3 are connected over to PA2 and PA3 respectively.  That is, Arduino pin A5 and ATMega4809 pins PF03 and PA03 are connected together by PCB traces such that there's no distinction between them, PF03 doesn't have its own header pin anywhere distinct from PA03.  They're both A5.  Likewise for Arduino pin A4 and ATMega4809 pins PF02 and PA02.

The Nano Every was designed to be compatible with the [original Nano boards][1] that used the ATMega328P.  On these boards the A5, `analogRead`-capable pin, is *also* the I2C/Wire clock signal.  Likewise,
A4, `analogRead`-capable pin, is *also* the I2C/Wire data signal.

On the ATMega4809 the I2C/Wire Master/Slave signals on PORTA routed to the A5 and A4 pins are not *also* `analogRead`-capable.  That is, they are not connected to the analog-to-digital converter in the chip as they were in the Atmega328P on the old Arduino Nano boards.

To mirror the workings of the [original Nano][1], where A4 and A5 were *both* `analogRead` pins and I2C/Wire Master/Slave pins, they connected A4 and A5 to *pairs* of ATMega4809 pins.  One of these pins on PORT**F** is connected to make the Arduino pin `analogRead`-capable and the other pins on PORT**A** are connected to make the Arduino pin Wire/I2C Master/Slave capable.  In other words, they used two AVR pins to synthesize a single Arduino pin capable of both functions that were available on that pin on the older Nano boards.

When it comes to using PORTMUX to switch choice of I2C pins, practically speaking, you won't be able to if you're looking to get alternate pins for TWI Master.  PORTMUX lets you switch the I2C Master/Slave or just Master peripheral onto pins PC2 and PC3 instead of PA2 and PA3.  But, in the [Nano Every schematic][2], you can see these are not connected to anything.  So if you wanted to do that, it would mean something like soldering wiring-wrap wire directly to the MCU pin, which would be difficult.  And PC2 and PC3 are the only two other ATMega4809 pins that PORTMUX will route the hardware I2C Master/Slave peripheral to.    So, practically speaking, if you want I2C any pins other than A4 and A5 on a Nano Every, it means using a software (bit-banged) implementation of I2C.

You asked (in comments) about the TWI support indicated on PF2 and PF3 in the ATMega4809 datasheet.  I think I'd either been looking at an older datasheet or maybe disregarded those pins because of how they're hardwired over to PORTA on the Nano Every.  The ATMega4809 has a "Dual TWI" mode apparently, where you can have just master mode on the pins that are normally both, and just slave mode on an alternate set of pins.  In two configurations of PORTMUX under Dual TWI, the PF2 and PF3 are where the slave-only capability of the peripheral are broken out.  With PORTC's TWI pins unconnected and PORTA's TWI pins hardwired to PORTF's TWI pins, it's unclear to me what advantage you could get out changing PORTMUX on an Arduino Nano Every.

  [1]: https://store.arduino.cc/usa/arduino-nano
  [2]: https://content.arduino.cc/assets/NANOEveryV3.0_sch.pdf


body:
Recently, we developed the UTRAQ L100 GNSS Module base board for testing all the capabilities of the GPS receiver.

*https://www.elementzonline.com/blog/utraq-gps-l100-module-based-on-irnss-supported-by-gagan-navic*

But we couldn't find a way to use the AGPS functionality. Is there any AGPS server available that can be used to download the satellite ephemeris data and feed that to the GPS module?

I got a reference that uses Skytraq AGPS, but not sure if the same is applicable for all receivers with AGPS functionality.

https://github.com/r0ro/skytraq

The above reference uses python code, but hopefully, it can be ported to an Arduino library if the functionality actually works well.

title: Use AGPS functionality with Arduino and GPS module

Answers: 0


body:
Using the `.init` function for the ST7789 TFT screen prevents my WDT ISR from firing. What explains this behaviour, and is there something I can do? Any other timer ISR I could use instead?

    #include <Adafruit_ST7789.h>    // Includes Adafruit_GFX.h

    #define TFT_CS 10 // define chip select pin
    #define TFT_DC 9  // define data/command pin
    #define TFT_RST 8 // define reset pin, or set to -1 and connect to Arduino RESET pin

    Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

    void setup()
    {
        //Serial.begin(9600);
        pinMode(13, OUTPUT);

        WDTCSR = (24); // Change enable and WDE - also resets
        //prescalers only - get rid of the WDE and WDCE bit.
        WDTCSR = (6); // 1 sec
        WDTCSR |= (1 << 6); //enable interrupt mode - WDT as an interrupt is useful to wake up from sleep
        sei();

        tft.init(240, 240, SPI_MODE2); // comment this out and WDT works fine
        tft.setRotation(0);
        tft.setTextWrap(true);
    }

    void loop()
    {

    }

    ISR(WDT_vect)
    {
      digitalWrite(13, (digitalRead(13) ^ 1));   // toggle LED pin
    }

Thanks!

title: WDT ISR not called when SPI ST7789 module initiated

Answers: 1

body:
You can't use the LED on pin 13 on Uno, Nano or Nano Every, if you use SPI . It is the clock pin of the SPI.

The init function of the display initializes SPI which dedicates the pin to SPI peripheral and disconnects it from pin IO peripheral.


body:
I have Arduino Uno (sender) and Arduino Uno Wifi rev 2 (receiver). I want to send the ping value to the other one via serial - jumper wires.
Arduino Uno is using the newping example, and I want the Uno Wifi to receive the sensor value and print it to serial.
I am using SoftwareSerial.h
jumper wires go TX<->RX , RX <->TX, GRD-GRD according to the pins in the sketch below.

The problem is the sketch code for the Uno WiFi (receiver), it keeps printing garbage and seems like no carriage return sometimes.
```
13
⸮10
⸮52
⸮5LC⸮1⸮H⸮10
5⸮H⸮51
13C⸮10
⸮5⸮H⸮5LC⸮13
10
⸮52
51C⸮13
10
⸮52
5LC⸮13
⸮10C⸮52
⸮51
13
10
⸮52
50
```

Code on Uno (sender):
```
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
#include <SoftwareSerial.h>
#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
SoftwareSerial mySerial(9, 10); // RX, TX

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

 Serial.println("Hello World Serial");
 mySerial.begin(4800);
 mySerial.println("Hello World, mySerial");
}
void loop() {
  delay(500);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  mySerial.print(sonar.ping_cm());
  mySerial.println();
  }
```
code on uno wifi (reciever):
```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);

}

void loop() { // run over and over

    Serial.println(mySerial.read());
    delay(1000);

}
```

I can see the Uno (sender) with NewPing is printing the correct data to it's serial but I can't get the Uno wifi (listener) to get the same value. Its just garbage. I am new to this, what am I doing wrong?

title: Arduino recieve sensor data from other arduino SPI

Answers: 1

body:
Well had a bit of luck after spending all day on this.

Arduino UNO (sender): Like mentioned by chrisl, use `Serial.write` and not `Serial.print`

```c++
mySerial.write(sonar.ping_cm());
```

UNO Wifi (receiver):

```c++
Serial.println(mySerial.readString());
```

So, instead of `mySerial.read` I used `mySerial.readString`.
This is most likely a obvious mistake to almost everybody here; took me two days. Sigh.


body:
I am trying to use an ultrasonic sensor in conjuncture with different devices like a proximity sensor and a solenoid and alarm.

This is how the project is supposed to work:

A container is placed on a fixture and the proximity sensor detects the placement of the container. Once the container is detected the ultrasonic sensor needs to be activated and the pulse time is measured and the distance is calculated. The container has unique features on each side and the aim of the ultrasonic sensor is to measure the distance and if the distance value is within the required spec then it should turn on a solenoid to allow the next operation or if it's outside the spec it should raise an alarm.

following is the code:
```
/*Objective of this project

1. To be able to detect when a container is placed in the wrong oreientation and cut of the supply to pneumatic system if so.
We will use the following devices to do so

1. Ultrasonic sensor to measure distance differences of both sides of the container
2. IR sensor to measure if the conatiner has been placed or not (This sensor will activate the ultra sonic sensor)
3. A soliend that will be controlled by the output of the ultrasonic sensor. The solenoid will control the air flow.

*/

int trigPin = 7;
int echoPin = 8;
int contSig = 2;
int solSig = 12;
int errSig = 13;
void setup() {

  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(contSig,INPUT_PULLUP);
  pinMode(echoPin,INPUT);
  pinMode(solSig,OUTPUT);
  pinMode(errSig,OUTPUT);

  }

void loop() {
  if (digitalRead(contSig) == 0){
    Serial.println(digitalRead(contSig));
    digitalWrite(trigPin,LOW);
    delayMicroseconds(10);
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(10);
    int duration = pulseIn(echoPin,HIGH);
    Serial.println(duration);
    float dist = (duration/2) * 0.034;
    Serial.println(dist);
    if (dist >=20 && dist <= 60){
      digitalWrite(solSig,HIGH);
      digitalWrite(errSig,LOW);
    }
    else{
      digitalWrite(solSig,LOW);
      digitalWrite(errSig,HIGH);
    }
  }

}

```

I am facing a few issues.

1.The first If statement at the beginning does not seem to work properly.

2.The output on the serial monitor alternates between zeros and actual values.  I am not sure why this set of zeroes keeps coming inbetween but this will make the project fail.

Following is the output from the serial monitor:

0

0

0.00

0

2892

49.16

[![I have been trying to simulate this on tinkercad][1]][1]

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

title: Error in program that measures distance from a ultrasonic sensor

Answers: 0


body:
With the ReadWrite example in Arduino IDE, the sketch size is 10980 bytes (34%) of an Arduino UNO's storage. How can we reduce the sketch size? There isn't any kind of `#define` to turn on/off features in `SD.h`. I only need `read`, `write`, `append` and `seek` features, not anything else.

I have found the [PetitFS][1] port for Arduino, but it doesn't support appending to a file. There is also [TinySDLogger][2] but I think it's for good for logging rather than normal file writing. I have found [SdFat][3] too.

My main work has used `26234+` bytes of flash and I cannot add more 10KB to the sketch!

  [1]: https://github.com/greiman/PetitFS
  [2]: https://github.com/Nick507/TinySDLogger
  [3]: https://www.if.ufrj.br/~pef/producao_academica/artigos/audiotermometro/audiotermometro-I/bibliotecas/SdFat/

title: How can we remove unused feature in Arduino's standard SD library so we can reduce the sketch size?

Answers: 0


body:
I have a problem with my arduino buzzer:
the code should be doing the following:
I have a security system where in order to open the door you have to enter a 4 digit code from the remote. If the code is correct the door opens. if not you can try again.
You have 3 chances to try to enter the pin before an alarm goes on. here comes the problem: the alarms code triggers but the buzzer isn't making any sound.

here is the code for the alarm sound:

    if (tryCount>=3) { // if the pin is wrong 3 times we sound an alarm
        Serial.println("got in alarm");
        while(true) {
            Serial.println("got in while");
            noTone(buzzer);
            tone(buzzer,100,300);
            delay(300);
            noTone(buzzer);
            tone(buzzer,1000,300);
            delay(300);
        }
    }

here is the proof the alarm code triggers:

[![trigger proof][2]][2]

here is the full code:
https://create.arduino.cc/editor/mihimbc/8ec2fe30-d812-45cc-b0ae-850b437eb05b/preview

and here is the hardware schematics:

[![arduino schmatics][3]][3]

  [1]: https://i.stack.imgur.com/BLYwt.png
  [2]: https://i.stack.imgur.com/nmgbl.png
  [3]: https://i.stack.imgur.com/39UOb.png

title: Arduino buzzer code sequence not triggering

Answers: 1

body:
The problem was with the buzzer, somehow was a faulty buzzer, I've managed to replace it and the problem was solved.
Thanks everybody for your time trying to help me!


body:
I have bought this cheap AVR Programmer Board and I thougth that I would be OK just plugging it into my USB port. Then after I did that nothing happened so I passed last 4 hours trying to understand what was going wrong. I learned that ATTiny85 microchips often come with no bootloader.
[![cheap AVR Programmer Board][1]][1]
So first I tested it with Arduino as ISP and simple blink code. It worked. Then I downloaded micronucleus and i flashed it via Arduino as ISP. I think this process worked pretty well as the output show

    > avrdude -C ../etc/avrdude.conf -c arduino -p t85 -P COM3 -b 19200 -U flash:w:/micronucleus/firmware/releases/t85_default.hex

     avrdude: AVR device initialized and ready to accept instructions

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

     avrdude: Device signature = 0x1e930b (probably t85) avrdude: NOTE:
     "flash" memory has been specified, an erase cycle will be performed
              To disable this feature, specify the -D option. avrdude: erasing chip avrdude: reading input file
     "/micronucleus/firmware/releases/t85_default.hex" avrdude: input file
     /micronucleus/firmware/releases/t85_default.hex auto detected as Intel
     Hex avrdude: writing flash (8166 bytes):

     Writing | ################################################## | 100%
     0.09s

     avrdude: 8166 bytes of flash written avrdude: verifying flash memory
     against /micronucleus/firmware/releases/t85_default.hex: avrdude: load
     data flash data from input file
     /micronucleus/firmware/releases/t85_default.hex: avrdude: input file
     /micronucleus/firmware/releases/t85_default.hex auto detected as Intel
     Hex avrdude: input file
     /micronucleus/firmware/releases/t85_default.hex contains 8166 bytes
     avrdude: reading on-chip flash data:

     Reading | ################################################## | 100%
     0.09s

     avrdude: verifying ... avrdude: 8166 bytes of flash verified

     avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

     avrdude done.  Thank you.

Problem that I'm now facing is that when I try to upload a code using ATTiny Development Board via arduino IDE (selecting Attiny85 digispark default 16.5mhz) and it asks me to plug in the device, device is not recognized.

I already installed drivers downloaded from github release section of [DevicestumpArduino repository][2], tried installing micronucleus configuration driver via zadiag like i read [in this question][3] but nothing worked.
What am I missing?

  [1]: https://i.stack.imgur.com/0MAY7.jpg
  [2]: https://github.com/digistump/DigistumpArduino
  [3]: https://arduino.stackexchange.com/questions/72181/digispark-clone-not-recognised-when-plugged-in

title: ATTiny85 USB Troubleshooting. Device is not recognized when programmer asks to plug in device

Answers: 1

body:
From your AVRDude output:

> avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

It does not appear that you have [programmed the AVR configuration fuses][1].

One for thing, `E:FF`, is extended fuse value 0xFF, which is missing the `SELFPRGEN` (self-programming) fuse that would allow Micronucleus to load your code onto the AVR, that is allow the AVR to execute instructions to program itself.  So, assuming it managed to show up on USB, you wouldn't actually be able to use it to put code on your chip.

You can see what they should be where the makefile [`fuse` target][2] defers to your [`t85_default` configuration][3]:

```make
FUSEOPT = -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m
```

The fuses that are actually preventing it from showing up on USB are more likely the clock related fuse bits in the low fuse byte.  In particular `CKDIV8` (factory default) is set to divide-by-8 where it is not in the makefile.  The `CKSEL` bits are set to 0x2 (factory default) for the 8Mhz internal RC oscillator whereas the makefile wants them to be set to 0x1, for internal PLL (phase locked loop) that generates higher clock rates from the RC oscillator.  In short, your chip is running at 1MHz rather than 16Mhz.  The Micronucleus code may also be written such that it needs PLL for bit-banging USB, though I haven't looked into that to be certain.

  [1]: https://github.com/micronucleus/micronucleus/blob/v2.5/Readme.txt#L78
  [2]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/Makefile#L79
  [3]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/Makefile.inc#L22


body:
I am learning about interrupts and one of the interrupt modes is LOW which triggers anytime the pin is a digital low.

Can someone tell me what voltage that is for an Arduino nano? I did a google search and it said a LOW can be anywhere from 0 to 2V.

I am making a project using a nano and I am powering it with batteries. It would be great if I could set up an interrupt to turn on an LED when the batteries were getting weak so I would know when to change them.

title: what voltage level is a digital low for the interrupt mode LOW?

Answers: 1

body:
> It would be great if I could set up an interrupt to turn on an LED
> when the batteries were getting weak

That won't work. The thresholds for the pin registering LOW or HIGH
depend on the supply voltage. Very roughly:

* a pin in guaranteed to register LOW if its voltage is below ⅓ Vcc
* it is guaranteed to register HIGH if it's above ⅔ Vcc
* nothing is guaranteed between ⅓ and ⅔ of Vcc.

For the exact voltage levels, you should check the datasheet.

Note also that those are _guaranteed_ levels. The actual thresholds are
closer to ½ Vcc, with an hysteresis of roughly Vcc/10.

For detecting a low battery condition, you should use the ADC, combined
with either a voltage divider on Vcc or the internal bandgap reference.


body:
I am trying to use an IR Remote to input date's and time's for a countdown, so then the LCD will display a countdown, like this:

```none
LCD: Enter Year
Remote-Input: 2021
LCD: Enter Month
Remote-Input: 08
LCD: Enter Day
Remote-Input: 20
LCD: Enter Hour
Remote-Input: 08
LCD: Enter Minute
Remote-Input: 00
LCD: Enter Second:
Remote-Input: 00
LCD: You have __ Years, __ Months, __ Days, __ Hours, __ Minutes, __ Seconds.
```

How do I do this?

title: How to use LCD Screen and IR Remote to broadcast a countdown

Answers: 1

body:
> How do I do this?

I have no clue how you do that but I do know I would do that.

> I know how to ask a question.

Apparently not, your question is far from perfect (and my answer above is technically the only correct answer to that specific question). It doesn't tell us what you've tried, it doesn't tell us what you haven't tried. It not specific nor practical. Doesn't state your experience with Arduino, doesn't state which hardware you (would) be using. (Though I must say your example output thing is quite nice)

> I was just in a rush.

Isn't everyone nowadays? And why would we invest time in an answer on a question which has no effort put into it?

----------

You're basically asking "How to do an Arduino project" (or any project), there's many ways but let's dive into it.

**0. Split up your project into smaller projects.**

Since it sounds as if you have no clue on how to get started or if you feel this project is daunting, it may help to make the 'problem' easier to get started. You can always add more complexity.

Make one Arduino program, which shows "Hello World" on the LCD.

Make one Arduino program, which receives IR codes and depending on which button pressed, shows "Hello" or "World" in your terminal.

**1. Research**

Search the internet, maybe there's projects like this. Try to google for "Arduino Countdown Timer". Check what design choices they made, what hardware they use and how they work in general.

**2. Design**

Make a design, not only about the aesthetic part, but also functionally. What happens if the timer depletes? Should it also have a buzzer? Does it need an enclosure?

And technically, how will it be powered?

**3. Acquire hardware**

As a starter; it can help to buy hardware from stores that also include example code.
Use the example code to test and verify your hardware and connections.

**4. Software**

If you're asking "How to write software", you're better off starting out with some example projects/tutorials which include the code and explain it.

But basically you should use the example code to drive the hardware, use examples on the internet combined with your own experience to create a program that matches your required behavior.

----------

**If, along this path, you have a practical question. We will be much more able to, and happy to, help.**


body:
I have been working on trying to get the MAXREFDES#117 PPG and the LIS3DH Accelerometer to run together. I am modifying the sample code found here to do so:

https://github.com/MaximIntegratedRefDesTeam/RD117_ARDUINO

However, when I add the line lis.begin(0x18) to the PPG code the code stops running correctly. There is no error and the only thing that will print to the Serial Monitor is “LIS”. I have gotten the accelerometer to run using acceldemo and the PPG sensor running using the code from GitHub (above), so I do not think it is a connection issue. I am not quite sure what the problem is and would greatly appreciate help.

    //PPG

    #include <Arduino.h>
    #include "algorithm.h"
    #include "max30102.h"

    //Accelerometer

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

    #define MAX_BRIGHTNESS 255

    #if defined(ARDUINO_AVR_UNO)
    //Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format
    //To solve this problem, 16-bit MSB of the sampled data will be truncated.  Samples become 16-bit data.
    uint16_t aun_ir_buffer[100]; //infrared LED sensor data
    uint16_t aun_red_buffer[100];  //red LED sensor data
    #else
    uint32_t aun_ir_buffer[100]; //infrared LED sensor data
    uint32_t aun_red_buffer[100];  //red LED sensor data
    #endif
    int32_t n_ir_buffer_length; //data length
    int32_t n_spo2;  //SPO2 value
    int8_t ch_spo2_valid;  //indicator to show if the SPO2 calculation is valid
    int32_t n_heart_rate; //heart rate value
    int8_t  ch_hr_valid;  //indicator to show if the heart rate calculation is valid
    uint8_t uch_dummy;

    Adafruit_LIS3DH lis = Adafruit_LIS3DH();

    // the setup routine runs once when you press reset:
    void setup() {
       // initialize serial communication at 115200 bits per second:
       Serial.begin(115200);
       while (!Serial) delay(10);     // will pause Zero, Leonardo, etc until      serial console open

       Serial.println("LIS3DH initializing");
       lis.begin(0x18);
       Serial.println("LIS3DH initialized!");

       maxim_max30102_reset(); //resets the MAX30102
       pinMode(10, INPUT);  //pin D10 connects to the interrupt output pin of the MAX30102

       delay(1000);
       maxim_max30102_read_reg(REG_INTR_STATUS_1,&uch_dummy);  //Reads/clears  the interrupt status register

       while(Serial.available()==0)  //wait until user presses a key
       {

          Serial.write(27);       // ESC command
          Serial.print(F("[2J"));    // clear screen command
          Serial.println(F("Press any key to start conversion"));
          delay(1000);

       }

       uch_dummy=Serial.read();
       maxim_max30102_init();  //initialize the MAX30102
    }

    // the loop routine runs over and over again forever:

    void loop() {
      uint32_t un_min, un_max, un_prev_data, un_brightness;  //variables to calculate the on-board LED brightness that reflects the heartbeats
      int32_t i;
      float f_temp;

      un_brightness=0;
      un_min=0x3FFFF;
      un_max=0;

      n_ir_buffer_length=100;  //buffer length of 100 stores 4 seconds of samples running at 25sps

      //read the first 100 samples, and determine the signal range
      for(i=0;i<n_ir_buffer_length;i++)
      {
        while(digitalRead(10)==1);  //wait until the interrupt pin asserts
        maxim_max30102_read_fifo((aun_red_buffer+i), (aun_ir_buffer+i));  //read from MAX30102 FIFO

        if(un_min>aun_red_buffer[i])
          un_min=aun_red_buffer[i];  //update signal min
        if(un_max<aun_red_buffer[i])
          un_max=aun_red_buffer[i];  //update signal max
        Serial.print(F("red="));
        Serial.print(aun_red_buffer[i], DEC);
        Serial.print(F(", ir="));
        Serial.println(aun_ir_buffer[i], DEC);
      }

      un_prev_data=aun_red_buffer[i];

      //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
      maxim_heart_rate_and_oxygen_saturation(aun_ir_buffer, n_ir_buffer_length, aun_red_buffer, &n_spo2, &ch_spo2_valid, &n_heart_rate, &ch_hr_valid);

      //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
      while(1)
      {
        i=0;
        un_min=0x3FFFF;
        un_max=0;

        //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
        for(i=25;i<100;i++)
        {
          aun_red_buffer[i-25]=aun_red_buffer[i];
          aun_ir_buffer[i-25]=aun_ir_buffer[i];

          //update the signal min and max
          if(un_min>aun_red_buffer[i])
            un_min=aun_red_buffer[i];
          if(un_max<aun_red_buffer[i])
            un_max=aun_red_buffer[i];
        }

        //take 25 sets of samples before calculating the heart rate.
        for(i=75;i<100;i++)
        {
          un_prev_data=aun_red_buffer[i-1];
          while(digitalRead(10)==1);
          digitalWrite(9, !digitalRead(9));
          maxim_max30102_read_fifo((aun_red_buffer+i), (aun_ir_buffer+i));

          //calculate the brightness of the LED
          if(aun_red_buffer[i]>un_prev_data)
          {
            f_temp=aun_red_buffer[i]-un_prev_data;
            f_temp/=(un_max-un_min);
            f_temp*=MAX_BRIGHTNESS;
            f_temp=un_brightness-f_temp;
            if(f_temp<0)
              un_brightness=0;
            else
              un_brightness=(int)f_temp;
          }
          else
          {
            f_temp=un_prev_data-aun_red_buffer[i];
            f_temp/=(un_max-un_min);
            f_temp*=MAX_BRIGHTNESS;
            un_brightness+=(int)f_temp;
            if(un_brightness>MAX_BRIGHTNESS)
              un_brightness=MAX_BRIGHTNESS;
          }
    #if defined(ARDUINO_AVR_LILYPAD_USB)
          analogWrite(13, un_brightness);
    #endif

    #if defined(ARDUINO_AVR_FLORA8)
          LED.setPixelColor(0, un_brightness/BRIGHTNESS_DIVISOR, 0, 0);
          LED.show();
    #endif

          //send samples and calculation result to terminal program through UART
          Serial.print(F("red="));
          Serial.print(aun_red_buffer[i], DEC);
          Serial.print(F(", ir="));
          Serial.print(aun_ir_buffer[i], DEC);

          Serial.print(F(", HR="));
          Serial.print(n_heart_rate, DEC);

          Serial.print(F(", HRvalid="));
          Serial.print(ch_hr_valid, DEC);

          Serial.print(F(", SPO2="));
          Serial.print(n_spo2, DEC);

          Serial.print(F(", SPO2Valid="));
          Serial.println(ch_spo2_valid, DEC);
        }
        maxim_heart_rate_and_oxygen_saturation(aun_ir_buffer, n_ir_buffer_length, aun_red_buffer, &n_spo2, &ch_spo2_valid, &n_heart_rate, &ch_hr_valid);
      }
    }

Here is a picture of how the two sensors are wired:

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

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

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

  [1]: https://i.stack.imgur.com/lcC4G.jpg
  [2]: https://i.stack.imgur.com/2n9iZ.jpg
  [3]: https://i.stack.imgur.com/PxQSz.jpg

title: Arduino Uno I2C two sensor connection Issues

Answers: 0


body:
I know this is probably a very asked question, but I am building a fairly basic radar type thing which sweeps left and right and uses an ultrasonic sensor to determine the distance to an object and a buzzer is set off if something is detected.

The device itself works  but I've noticed that because I have used delay() to allow the servo to complete its full movements, it is holding up the rest of the code, and as a result the buzzer and returning of the distance is extremely unresponsive and sluggish.

So far I have looked at simply returning a value whenever the motor reaches a certain step but it doesn't achieve exactly what I'm looking for, and I have looked into using millis() for timing asynchronously, but I'm struggling to wrap my head around it a bit in terms of how it will work for a servo.

My current working but sluggish code:

    //Servo Stuff
    #include <Servo.h>
    int servoPin = 12; // Pin for interacting with servo defined
    int servoStart = 0; //Starting position of servo motor
    int servoEnd = 90; //End position of servo means it rotates 90 degrees
    int waitTime = 1000; // Allows servo to fully rotate before moving again
    int servoPos = 20; // For incrementing the position of the servo
    int servoStep = 20; //amount to increment servo position by
    Servo myServo; // Creates an instance of a servo object

    //Ultrasonic stuff
    int trigPin = 9;
    int echoPin = 10;
    long duration;
    int distance;
    int maxDistance = 329; // The max range of the ultrasonic sensor

    //Buzzer stuff
    int buzzerPin = 11;
    int buzzerWait = 200;

    void setup(){

    //Attach the servo object to the pin and begin serial monitor with
    // polling rate of 9600
    Serial.begin(9600);
      myServo.attach(servoPin);
      pinMode(buzzerPin, OUTPUT);

        pinMode(trigPin, OUTPUT); // Trig pin set as output
        pinMode(echoPin, INPUT); // echo pin set as i
          }

        void loop()
        {

          // Moving servo
          myServo.write(servoStart); //Moves servo to the starting pos
          //delay (waitTime); //allows servo to fully move before next move
          //myServo.write(servoEnd); //Moves to end position
          //delay (waitTime); // waits before reverting back to start pos

        //myServo.write(servoStart);
        //delay(waitTime);
        //myServo.write(20);
        //delay(waitTime);
        //myServo.write(40);
        //delay(waitTime);
        //myServo.write(60);
        //delay(waitTime);

         // Using ultrasonic sensor

          // Clears the trig pin
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2);

        // Sets the trigPin on HIGH state for 10 microseconds
          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(trigPin, LOW);

        // reads echoPin and returns the travel time of the wave in microseconds
          duration = pulseIn(echoPin, HIGH);

        // Calculating distance
          distance = duration*0.0343/2;

        //Prints the distance to the Serial Monitor
          Serial.print("Distance: ");
          Serial.println(distance);
          Serial.println(distance);

          if (distance < maxDistance) {
          digitalWrite(buzzerPin, HIGH);
          //delay(buzzerWait);
          //digitalWrite(buzzerPin,LOW);
          //delay(buzzerWait);

          }else digitalWrite(buzzerPin, LOW);

        }

Any pointers to some good resources for this would be very appreciated, thanks.

title: How can I remove the delays in this code for sweeping the servo?

Answers: 1

body:
From your code it seems like you are doing all the servo movement before you read the distance and report back. A lot of code is commented out, so it's a bit difficult to follow. What I would do is something along the line of:

    [...]
    int servoStart=0;
    int servoEnd=90;
    int servoPos=0;

    [...]
    void setup() {
        [usual setup stuff like you do it now]
        myServo.write(servoPos);  //start at pos 0
        // Maybe a delay here to make sure we are at pos. 0
    }

    void loop() {
        //Switch direction if we reach end
        if (servoPos+servoStep < servoStart || servoPos+servoStep > servoEnd)
            servoStep = -servoStep;
        servoPos += servoStep;
        myServo.write(servoPos);
        //Small delay?
        //Read distance
        //Send distance to seraial
        //Buzz buzzer if needed
    }


body:
I'm using my ESP8266 as a web server to tilt a camera with the servo [Tower Pro Micro Servo 9G][1].

```c++
#include <Servo.h>
#include <ESP8266WiFi.h>

const char* ssid     = "SSID";
const char* password = "password";

Servo tilt;

WiFiServer server(8082);

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  Serial.println("Server started");
  tilt.attach(2);
  tilt.write(100);
}

void loop() {
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }
  Serial.println("Waiting for new client");
  while(!client.available())
  {
    delay(1);
  }
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  int value = LOW;

  if(request.indexOf("/SERVO=UP") != -1){
        int t = tilt.read();
        if(t <= 125) {
          delay(10);
          tilt.write(t+8);
        }
  }
  if(request.indexOf("/SERVO=DOWN") != -1){
        int t1 = tilt.read();
        if(t1 >= 75) {
          delay(10);
          tilt.write(t1-8);
        }
    }

  client.println("HTTP/1.1 200 OK"); //
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.print(" CONTROL Servo: ");

  if(value == HIGH)
  {
    client.print("ON");
  }
  else
  {
    client.print("OFF");
  }
  client.println("<br><br>");
  client.println("<a href=\"/SERVO=UP\"\"><button>ON</button></a>");
  client.println("<a href=\"/SERVO=DOWN\"\"><button>OFF</button></a><br />");
  client.println("</html>");
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
}
```

The first minutes it works fine but after a few minutes it starts turning 360° nonstop. Although, you can't turn this servo over 180°?!
Does anyone of you know what is going on here?
Thanks!

  [1]: http://www.towerpro.com.tw/product/sg90-analog/

title: Servo starts spinning 360 degrees after a few minutes

Answers: 1

body:
If it works and then doesn't, it makes this seem like a mechanical issue.

To check, write a simple program that just moves the servo around. Leave out all the extra web code. Wait to see if starts behaving erratically and you can save yourself the headache of hunting issues in your code that don't exist.


body:
I'm starting a test using Arduino to reproduce a set of temperature values in water each three hours and need some help with it.

I will use two ds18b20 sensors to control two thermostats connected to relays. The idea is that Arduino could access the data from a file in which there are simulated data for each day in the future. Something like this:

    Date,Time,Temperature
    01/01/2070,00:00:00,27.229211807251
    30/12/2070,21:00:00,24.6133060455322
    01/01/2070,06:00:00,22.1697025299072
    01/01/2070,09:00:00,20.3209171295166
    01/01/2070,12:00:00,27.7610721588135
    01/01/2070,15:00:00,33.6277084350586
    01/01/2070,18:00:00,34.5402450561523
    01/01/2070,21:00:00,31.9973392486572
    02/01/2070,00:00:00,26.2283573150635
    02/01/2070,03:00:00,21.5823612213135
    02/01/2070,06:00:00,18.6461429595947
    02/01/2070,09:00:00,17.2126712799072
    02/01/2070,12:00:00,24.8096561431885
    02/01/2070,15:00:00,30.6440677642822
    02/01/2070,18:00:00,33.8463973999023
    02/01/2070,21:00:00,31.3529300689697
    03/01/2070,00:00:00,25.2961673736572
    03/01/2070,03:00:00,20.8135623931885

Based on this info the sensor will control the thermostat to decrease or increase the temperature within three hours (8 different temperatures by day). I'm going to start with 1 week (7 day x 8 temperatures = 56 simulations), but want to increment it till 3 months (720 simulations).

Considering the use of if/else if, it seems that would be a massive amount of conditionals.

Does anybody have a good solution to run this temperature simulation based on predefined data?

Thanks in upfront.

title: Reproduce simulated temperature data with Arduino

Answers: 1

body:
You can use an array to go through the times.

Create a struct with the fields `time` and `temperature` (you should think about saving time as unix epoch, meaning seconds since 1970, so that you save memory).

    struct SetPoint {
        unsigned long time;
        float temperature;
    };

Then you can declare an array of type `SetPoint` to hold the tubles of time and temperature:

    #define DATA_SIZE  720
    SetPoint data[DATA_SIZE] = {
        {<time1>, <temp1>},
        {<time2>, <temp2>},
        ...
        };

In the above, you need to replace `<timeX>` and `<tempX>` by your data. Then declare a position variable, which the element index, which will be invoked next:

    unsigned int pos = 0;

We are starting with the first element (index 0) and compare its time to the current time. If it is equal (or current time is after the elements time), we will set the thermostat to the elements temperature and increment the position variable. Something like this:

    if(pos < DATA_SIZE && current_time >= data[pos].time){
        set_thermostat(data[pos].temperature);
        pos++;
    }

Note: I used the variable `current_time` here as standin for your way of getting the current time, and the `set_thermostat()` function as a standin for your way of setting the thermostat. Also I inserted a check into the if statement, to prevent the code going further, when it reached the data array end.

---

That said, depending on the used board you can easily get into memory trouble here. An Arduino Uno does not have enough memory to save 720 of the data points above. `float` and `unsigned long` both take 4 bytes each, so 8 bytes per element, which makes `8*720 = 5760` bytes. The Uno only has 2048 bytes total in RAM. There are enough boards, which have more RAM. The ESP32 for example would have way enough (though there are many others; the ESP32 is just the first to get into my mind here).

Or you can add an SD card module to your build and save the data points in a file. That would also make it way easier to get the data in your project or change the data. It would just involving writing the corresponding file on your SD card.

Then the workflow would be a bit different. Lets assume you save one data point per line as text:

- Open file and read one line. Close file.
- Parse read text into 2 variables (time and temperature)
- Use these variables for the if statement from above
- if the time of the loaded data point was reached, open the file again, read the next line and parse it into the variables
- The if statement now uses the next datapoint

and so on. If there is no line left to read, you could go into an infinite loop, stopping the code from running further than your data.

There are ready to use SD card modules to buy out there, and you can find many tutorials about how to use them online.

---

As Edgar Bonet correct stated in the comments, you can greatly reduce the needed RAM, when assuming regular intervals (3h in your case). Then you don't need to save the time for each data point. You only need the one start time for the series. Also above I used `float` for the temperature (as I assumed, that at this point it would be the easiest for you). But since temperature settings for thermostats are mostly working only down to the 1 digit after the decimal point, you can save memory space by using a different representation. For example you could save the temperature as a single byte signed integer with the unit of 0.1°C and a reasonable offset (for example 25°C being zero). So some example values would be:

    Temp | value
    ------------
    18°C | -70
    20°C | -50
    22°C | -30
    25°C | 0
    27°C | 20
    35°C | 100

That would give you the precision of one digit after the decimal point and a range from 12.3°C to 37.8°C. When changing the factor of `0.1°C`, you can also change the range (and precision with it) as you really need it.

So with the above you would only need 720 byte for the actual data, which is good for the Uno.

BUT: I would still suggest looking into the SD card reader. You will have more work building the project, but you won't have the same hassle with including or updating the data. That can come in especially handy, if you want to use to further use the device after the 3 months. Just loading new data on it (maybe even way more data, like for a full year) is easier with an SD card.


body: I'm doing a school project and I want to measure the difference in time that the lights are on in a classroom with and without a motion sensor controlling them. I haven't really found anything about recording how long sensors act or the time between activations. How could I possibly do this?

title: Set up a motion sensor to turn on lights and record how long the lights are on

Answers: 1

body: I would consider placing a light sensor close to one of the lights to signal when the lights are on. Placement is critical as you do not want a signal when the lamp is off. I am assuming they are permanent light fixtures and you are not allowed to tamper with the wiring.  Record the elapsed time when they are on.  Note the start time and then subtract that from the current time based on your watch. For elapsed time and subtract the ontime from that. With the sensor you can also record each time the light is turned on etc. That would all be in your software.


body:
I wish to config `WiFiManager` and `addParameter` of MQTT topic and local server on its ConfigPortal.

Additionally in a case of a power outage or any, in case of losing WiFi, to continue in a `NonBlocking` way.

The problem is when combining both features in one sketch, I get some errors.

Entire code is ( please notice comments marked `Marker[i]` ):

    #include <WiFiManager.h>
    #define MQTT_SERVER "192.168.3.200"
    WiFiManager wm;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);

      WiFiManagerParameter custom_mqtt_server("mqtt_server", "mqtt server", MQTT_SERVER, 40);
      WiFiManagerParameter custom_mqtt_user("mqtt_user", "mqtt user", "", 10);
      WiFiManagerParameter custom_mqtt_pwd("mqtt_pwd", "mqtt password", "", 10);
      WiFiManagerParameter custom_mqtt_topic("mqtt_topic", "mqtt topic", "", 10);
      WiFiManagerParameter custom_mqtt_group("mqtt_group", "mqtt group", "", 10);
      WiFiManagerParameter custom_mqtt_root("mqtt_root", "mqtt rootTopic", "", 10);
      wm.addParameter(&custom_mqtt_server);
      wm.addParameter(&custom_mqtt_user);
      wm.addParameter(&custom_mqtt_pwd);
      wm.addParameter(&custom_mqtt_topic);
      wm.addParameter(&custom_mqtt_group);
      wm.addParameter(&custom_mqtt_root);

      WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
      //  wm.resetSettings();

      //  wm.setConfigPortalTimeout(180);
      // wm.setConfigPortalBlocking(false);  // <--- Marker [#1]

      //  if (!wm.autoConnect("AutoConnectAP")) {
      //    Serial.println("failed to connect and hit timeout");
      //    delay(3000);
      //    //reset and try again, or maybe put it to deep sleep
      //    ESP.restart();
      //    delay(5000);
      //  }

      bool res;
      res = wm.autoConnect("test123", "password"); // password protected ap
    }

    void loop() {
      // put your main code here, to run repeatedly:
      //  wm.process(); //<--- Marker [2]
      Serial.println("hi");
      delay(100);

    }

1) When `Marker[1]` & `Marker[2]` are commented out ConfigPortal works as expected, and in `Blocked` state - meaning there is no `hi`'s on Serial monitor.

2) When only `Marker[2]` is commented out, ConfigPortal is reached, lacking all `addParameter` fields.

3) When `Marker[1]` & `Marker[2]` are not commented out, ConfigPortal is now reachable, but not having Non-Blocking feature...

4) What is the purpose of `wm.process()` ?

Guy

title: WiFiManager - Combine NonBlocking portal AND addParameter

Answers: 1

body:
The WiFiManger's `autoConnect` function starts the configuration web server (and AP) only if connection to configured WiFi network is not established.

If you want to run the WiFiManger's web server to reconfigure WiFi or to set other parameters, you can start the WM web server with the `startConfigPortal` function.

`autoConnect` and `startConfigPortal` are blocking by default. The library has a loop inside this functions which runs until the web server is stopped calling [Exit] action on the configuration web page or the timeout set with `setConfigPortalTimeout` is reached after last contact from browser.

To run the WM web server 'parallel' to your sketch you can configure it as not blocking with `setConfigPortalBlocking(false)`. Then to allow WM handling of the web server the sketch must periodically call `wm.process()`.

In not blocking mode the [Exit] action on the configuration wen page doesn't stop the web server. The server must be stopped in code.

The parameter definitions must by global in sketch, if you want to run WiFiManager with parameters outside of setup(). Parameters local in setup() don't exist after setup() finishes. WiFiManager detects this and doesn't use the parameters.

The `OnDemandWebPortal` example and `OnDemandNonBlocking` example demonstrate `startConfigPortal` in blocking and not blocking use.


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

I need to simulate a pulse train. Everything is in order with this code, it solves its problem.
The question is: I need to change the keys, but it is too difficult to manually type in so many zeros and ones each time.
On the other hand, I know that my hexadecimal key looks much shorter: "B8C4F9".
  Is it possible to create a string in such a way that the system itself translates to the binary system?

And the second question: How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

    const int KEY_LEN = 24;
    const char key[KEY_LEN] = {"101110001100010011111001"};

    int T = 200; // Pulse repetition period in microseconds
    int Zero = 80; //0.4*T; // Duration of zero in microseconds
    int One = 120; //0.6*T;// Duration of a unit in microseconds

    const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter

    void setup()
    {
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      for (int n = 0; n < KEY_LEN; n++)
      {
        if (key1[n] == '1') //If the bit read == 1
        {
          sendSignal(One);
        }

        else if (key1[n] == '0')//If the bit being read == 0
        {
          sendSignal(Zero);
        }
      }
    }

    void sendSignal(int duration)
    {
      digitalWrite(LED_PIN, LOW);
      delayMicroseconds(duration);
      digitalWrite(LED_PIN, HIGH);
      delayMicroseconds(T - duration);
    }

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

title: Convert from hexadecimal to binary

Answers: 1

body:
There is really no reason to save the key as a string, as you are doing. You can just save it as a normal number. Then you can also use the hexadecimal representation on your code:

    unsigned long key = 0xB8C4F9;

Then you need to send out each bit of that number:

    for (int n = 0; n < KEY_LEN; n++)
    {
        if (key & (1 << n)) { //If the bit read == 1
            sendSignal(One);
        } else {//If the bit being read == 0
            sendSignal(Zero);
        }
    }

The following is happening in the if statement: `(1 << n)` will take the value 1 (binary `0b00000001`) and will shift the bits to the left by n digits. For example: If n is 2, we get `(0b00000001 << 2) = 0b00000100`. With this we can select a bit in our number. Then we take that and do a bitwise AND `&` with the key. That will set all bits to zero, which are not currently selected. The resulting number is zero, if the corresponding bit in `key` is zero. If the corresponding bit is 1, this will return a number different from zero (which is interpreted as `true`. Thus we check, if the n-th bit of `key` is one or zero.

> How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

Generally you can calculate the size of an array with the `sizeof()` function:

    unsigned int size_of_array = sizeof(array)/sizeof(array[0]);

`sizeof()` returns the number of bytes. So to get the number of elements, we need to divide by the number of bytes in each element;

For the way shown above this is not that easy. Normally it is not really needed, since such keys normally don't change length very often. If you find a variable type, which exactly fits your key size, you could use `sizeof(key)*8` to get the number of bits in it. But your current value `0xB8C4F9` only needs 3 bytes. I don't know a type with 3 bytes, but maybe somewhere you can get something like `uint24_t`. Honestly here I would just use a hardcoded size, just like you are using a hardcoded key value.


body:
I have a project I'm working on for a chicken coop.  I want to control the door with timing of the sunrise and sunset.  Also looking to a few other things but somewhere along the way, I must have screwed up the placement of `setup()`, `loop()` and other void statements.  I'm not longer getting `Serial.print` statements to print.  I've done quite a bit of borrowing from other codes (which might be apparent to those that are much better at this than me).  For some of those borrowed codes, I'm getting serial prints.  I'm using this as my debug, so I can verify the values that I'm passing and to determine if they are what I'm expecting, specifically for the times of sunrise and sunset, to control my door actuator.

**Any ideas why these various serial.print lines are not printing?**

I've indicated some of the serial.print lines with `<------------------------`.

```c++
/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest

  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc
    Follow us:                  http://www.fb.com/blynkapp
                                http://twitter.com/blynk_app

  Blynk library is licensed under MIT license
  This example code is in public domain.

 *************************************************************
  WARNING!
    It's very tricky to get it working. Please read this article:
    http://help.blynk.cc/hardware-and-libraries/arduino/esp8266-with-at-firmware

  This example shows how value can be pushed from Arduino to
  the Blynk App.

  NOTE:
  BlynkTimer provides SimpleTimer functionality:
    http://playground.arduino.cc/Code/SimpleTimer

  App project setup:
    Value Display widget attached to Virtual Pin V5
 *************************************************************/

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include "DHT.h"
#include <Wire.h>
#include <time.h>
#include <TimeLib.h>
#include <Dusk2Dawn.h>
#include <DS1307RTC.h>

#define TIMEZONE    -6
#define LATITUDE    38.3970
#define LONGITUDE   -90.6412

//The type of DHT that is being used
#define DHTTYPE DHT11   // DHT 11
//Which pin the DHT output is connected to the Arduino
#define DHTPIN 5
DHT dht(DHTPIN, DHTTYPE);

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "d*********************************0";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "P**********k";
char pass[] = "m*****************a";

int DisconnectCount = 0;
int ReCnctFlag;
int ReCnctCount = 0;

  Dusk2Dawn HouseSprings(LATITUDE,LONGITUDE, TIMEZONE);
  tmElements_t tm;
  //Changes Mins to the same format as Sunrise/Sunset (minutes after midnight)
  int Mins = tm.Hour * 60 + tm.Minute;
  int Sunrise = HouseSprings.sunrise(tm.Year, tm.Month, tm.Day, true);
  int Sunset = HouseSprings.sunset(tm.Year, tm.Month, tm.Day, true);

//char Str_door_status[] = "";

// Hardware Serial on Mega, Leonardo, Micro...
//#define EspSerial Serial1

// or Software Serial on Uno, Nano...
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2, 3); // RX, TX

// Your ESP8266 baud rate: adjust per project
#define ESP8266_BAUD 9600

ESP8266 wifi(&EspSerial);

BlynkTimer timer;

//Section of code that will handle getting the humidity/temp data and where to send it
void send_sensor()
{
  //Set the variable h to the value for humidity
  float h = dht.readHumidity();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //Set the variable f to the value for temp
  float f = dht.readTemperature(true);
  //delay(1000);
  //Perform a check if either h or f has no value
  if (isnan(h) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  //These would be used to send data to the serial window
  Serial.println(h); // <------------------------
  Serial.println(f); // <------------------------
  //Set the virtual pin 3 of the blynk to the temperature value
  Blynk.virtualWrite(V3, f);
  //Set the virtual pin 4 of the blynk to the humidity value
  Blynk.virtualWrite(V4, h);
}

// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void myTimerEvent()
{
  // You can send any value at any time.
  // Please don't send more that 10 values per second.

}

int in1 = 11;
int in2 = 12;

void motor_stop()
{
  digitalWrite(in1,LOW);
  digitalWrite(in2,LOW);
  Blynk.virtualWrite(V6,0);
  Blynk.virtualWrite(V7,0);
}

BLYNK_WRITE(V6)
{
  int pinValue = param.asInt();
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  if (pinValue = 1);
  {
    digitalWrite(in1,HIGH);
    digitalWrite(in2,LOW);
    Blynk.virtualWrite(V0,1);
    //delay(35000);
    //digitalWrite(in1,LOW);
    //Blynk.virtualWrite(V6,0);
    timer.setTimeout(35000L, motor_stop);
    Blynk.virtualWrite(V0,2);
  }
}

BLYNK_WRITE(V7)
{
  int pinValue = param.asInt();
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  if (pinValue = 1);
  {
    digitalWrite(in1,LOW);
    digitalWrite(in2,HIGH);
    Blynk.virtualWrite(V0,1);
    //removed this delay function as Blynk doesn't like it
    //delay(35000);
    //digitalWrite(in1,LOW);
    //Blynk.virtualWrite(V6,0);
    //Secondary method of delay that Blynk appears to prefer
    timer.setTimeout(35000L, motor_stop);
    Blynk.virtualWrite(V0,0);
  }
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  Blynk.begin(auth, wifi, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, wifi, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, wifi, ssid, pass, IPAddress(192,168,1,100), 8080);

  // Setup a function to be called every second
  timer.setInterval(1000L, myTimerEvent);

  dht.begin();

  timer.setInterval(1000L, send_sensor);

  //RTC.read(tm);

}

BLYNK_CONNECTED() {
  Serial.println("Connected");
  ReCnctCount = 0;

}

  //Serial.println(Sunrise);  // 418
  //Serial.println(Sunset);   // 1004

void open_door()
{

}

void close_door()
{
  Serial.println("info"); // <------------------------
  Serial.println(Mins); // <------------------------
  Serial.println(Sunrise); // <------------------------
  Serial.println(Sunset); // <------------------------
  char time2[] = "00:00";
  Dusk2Dawn::min2str(time2, Sunrise);
  Serial.print("Sunrise: ");     // <------------------------
  Serial.println(time2); // 16:53  // <------------------------
  char time3[] = "00:00";
  Dusk2Dawn::min2str(time3, Sunset);
  Serial.print("Sunset: ");  // <------------------------
  Serial.println(time3); // 16:53 // <------------------------
}

void loop()
{
  Serial.println(Mins); // <------------------------
  Serial.println(Sunrise); // <------------------------
  Serial.println(Sunset); // <------------------------

  if (Blynk.connected())
  {
    Blynk.run();                                    // Starts Blynk connection
  }
  else if (ReCnctFlag == 0)
  {
    ReCnctFlag = 1;                                 // Set reconnection Flag
    Serial.println("Starting reconnection timer in 3 seconds...");
    timer.setTimeout(3000L, []() {                 // Lambda Reconnection Timer Function
      ReCnctFlag = 0;                             // Reset reconnection Flag
      ReCnctCount++;                              // Increment reconnection Counter
      Serial.print("Attempting reconnection #");
      Serial.println(ReCnctCount);
      Blynk.connect();                            // Try to reconnect to the server
    });
  }
  timer.run(); // Initiates BlynkTimer

  //if (Mins > Sunrise) {
    //Serial.println("Door is open");
  //}
  //if (Mins > Sunset) {
  //  Serial.println("Door is closed");
  //}

}
```

This is what I'm getting in the serial window:

```none
[45108333] Ready (ping: 53ms).
Connected
```

title: Need help - skipping over some serial.print statements

Answers: 0


body:
I had some problem setting up a working ATTiny85 outside of its development board.
Connection on my breadboard:

    pulled high (10K R)  -- 1  PIN 8  -- VCC (+5V)
         trouble here!!  -- 2  PIN 7  --
                         -- 3  PIN 6  -- LED
                   GND   -- 4  PIN 5  --

as you can guess pins are referred to actual chip's pins enumeration.
My simple test code:

```c++
void setup() {
  pinMode(1, OUTPUT);
}
void loop() {
  if (analogRead(A1) > 512) {
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
  } else {
    digitalWrite(1, HIGH);
    delay(1000);
    digitalWrite(1, LOW);
    delay(1000);
  }
}
```

I'm using Arduino IDE v1.8.13 with digistump avrboards v1.6.7.

I flashed t85_default [micronucleus][1] v2.5 bootloader in my chip with fuses set to lfuse:0xe1, hfuse:0xdd, efuse:0xfe.
The problem is that if I power the chip with PIN2 not pulled high it won't start execution of the code, it won't blink.  If it’s started from pulled high, it will start code about 5s after power on. If it’s started pulled low code won’t execute until is pulled high. As I pull high, even just for a second, PIN2 it will start blinking and executing code.

Is it normal? I think I have missed something.

  [1]: https://github.com/micronucleus/micronucleus

title: ATTiny85 won't boot if PIN2 is not pulled high

Answers: 2

body:
Well, I've made *some* headway.  I hope to update this with something more helpful though.

I don't have a digispark or even the correct Zener diodes to replicate the necessary parts of it.  However, I did install t85_default.hex on an ATTiny85 with some alterations to the hex file to place break instructions in a few strategic places.  And then I ran avarice/debugwire against it.

The basic problem is that it's trying to tune the internal oscillator against the USB frames by looking at the D- pin.  Basically, [it's stuck in `tuneOsccal`][1].

```None
988  00001d06 <tuneOsccal>:
   1     1d06:       b3 9b           sbis    0x16, 3 ; 22
   2     1d08:       fe cf           rjmp    .-4             ; 0x1d06 <tuneOsccal>
   3     1d0a:       07 d0           rcall   .+14            ; 0x1d1a <countFrame>
...
```

So if you want to [avoid this][2], you need to compile with that feature off, and [there is a feature to do that][3].

I have not yet run one with this feature disabled.  But I did compile t85_default once, using `make CONFIG=t85_default` and found it necessary to remove the `START_WITHOUT_PULLUP` from the [first line of the t85_default/bootloaderconfig.h file][4].

The code [mentions the existence][5] of `OSCCAL_SAVE_CALIB`, which lets you specify your own OSCCAL value, assuming the factory one for the chip isn't good enough for whatever reason.  But there doesn't seem to be any guidance on how you're supposed store it or where.  Looking at the code though, if enabled, you can see it [loads the OSCCAL value][6] from [just before][7] where the [bootloader starts][8].

A simple way to put it there without messing with command-lines and linker scripts would be to just edit the the t85_default.hex that results from building with `OSCCAL_SAVE_CALIB` enabled, and add an extra record for setting the osccal value at the correct address, which I guess would be 0x19FA, so:

:0119FA00**XX***SS*

Where **XX** is whatever you've determined your OSCCAL value is and *SS* is [the checksum value][9], or `0x100 - ((0x14 + XX) & 0xFF)` in this case.  Or, if you want to be lazy, put whatever you want for *SS* and let AVRDude complain tell you what it's supposed to be when it tries to load the .hex file.  It will report the expected value in decimal, which you can convert to hex and patch into the file, and run AVRDude again.

  [1]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/osccal.S#L47
  [2]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/main.c#L439
  [3]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/bootloaderconfig.h#L246
  [4]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/bootloaderconfig.h#L1
  [5]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/bootloaderconfig.h#L239
  [6]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/main.c#L218
  [7]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/main.c#L50
  [8]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/Makefile.inc#L20
  [9]: https://en.wikipedia.org/wiki/Intel_HEX#Checksum_calculation

body: I had the same problem, I changed to firmware micronucleus-1.11-upgrade.hex (from 2.3 to 1.11) and it was solved, you can find ir here https://github.com/micronucleus/micronucleus/tree/v1.11/upgrade/releases