body:
I suspect that I might be using too many resources, because of the strings, but I am new to Arduino, so not sure where I am going wrong.  Any help would be appreciated.

What it should do when complete:
"Birthday Reminder"
 - Read the SD card for a "birthday" file ("MM-DD.txt" ) that matches
   "today".
 - The file contains the Name of the person and year of
   birth.
 - Flash LED's and display the person's name and age on the
   OLED.
 - The unit will not displayed anything until someone's birthday.

I am using the SD card with a simple format, to easily add new birthday's.

    Output:
    ⸮Initializing SD card...
    card initialized.
    25
    111
    opening: 04-25.txt
    2020"Test Person"
    bYearStr: 20

**The sd card file:**

    Name: MM-DD.txt
    Example: 04-25.txt

    Contents: Birthyear, Name
    Example: 2020"Test Person"

**The Sketch**

    #include <SPI.h>
    #include <SD.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include "RTClib.h"

    RTC_DS3231 rtc;

    int age;
    int led;
    int dly;
    String bName;
    String bYearStr;
    int bYear;
    int currentDay;
    int  tDy;
    int  tMth;
    int  tYr;

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels
    #define OLED_RESET -1
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

    void setup() {
      Serial.begin(9600);
      delay(3000); // wait for console opening

      // Setup Candle pins
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (rtc.lostPower()) {
        Serial.println("RTC lost power, lets set the time!");
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }

      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      display.clearDisplay();
      display.display(); // this command will display all the data which is in buffer
      display.setTextColor(WHITE, BLACK);

      const int SdCardPin = 10;
      Serial.println("Initializing SD card..."); // Verifying SD Card.
      //  if (!SD.begin(SdCardPin)) {
      if (!SD.begin(10)) {
        Serial.println("Card failed, or not present"); // don't do anything more:
        while (1);
      }
      Serial.println("card initialized.");

      currentDay = 111;
    }

    void loop() {
      age = 0;

      DateTime now = rtc.now();
      tDy = now.day();
      tMth = now.month();
      tYr = now.year();
      Serial.println(tDy);
      Serial.println(currentDay);

      if (currentDay != tDy) {
        String fileName;
        String m = String(tMth);
        String d = String(tDy);

        if (tMth < 10) {
          String mm = m;
          m = "0" + mm;
        }
        if (tDy < 10) {
          String dd = d;
          d =  "0" + dd;
        }
        fileName = m + "-" + d + ".txt";

        //String fileName = "01-01.txt";
        Serial.println("opening: " + fileName);
        File f = SD.open(fileName);
        delay(3000);

        if (!f) {
          Serial.println("open failed");
        } else {
          while (f.available()) {
            String line = f.readStringUntil('\n');
            Serial.println(line);
            bYearStr = line.substring(0, 4);
            bName = line.substring(4);
            delay(1000);
            currentDay = tDy;
            break;
          }
          f.close();
        }

        Serial.print("bYearStr: ");
        Serial.println(bYearStr);
        Serial.print("bName: ");
        Serial.println(bName);
        int bYear = bYearStr.toInt();
        age = tYr - bYear;
        Serial.print("Age: ");
        Serial.println(age);

      } else { // Start current day equal
        display.setTextSize(1);
        display.setCursor(38, 10);
        display.print("Birthday!");
        display.println();

        display.setTextSize(1);
        display.setCursor(0, 30);
        display.print("Name: ");
        display.print(bName);
        display.setCursor(0, 40);
        display.print("Age: ");
        display.print(age );
        display.println();

        led = random(3, 6);
        dly = random(80, 250);
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(dly);              // wait
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      } // End current day

      display.display();

    } // End void Loop

title: Substring: What is causing my output to be truncated?

Answers: 1

body:
It *is* quite likely you're out of memory. To know, really you need to keep track of the stack pointer and heap structure. There's enough going on in your code, that I'm not reasonably going to be able to set up an identical scenario to prove it.

### Display Library ###
The greatest use of SRAM in your project comes from the Adafruit SSD1306 library.  It's [allocating a buffer for the entire frame][1], which is 128 * 64 == 8192 bits, or 1024 bytes, half your Nano's SRAM.  It will use more than that for other data, though probably not a lot more by percentage.

You may be able to mitigate this usage with a library like trades some SRAM usage for extra execution time or lower frame rates.  One is the [U8g2 library][2].  You can read about [how it can use half-buffer][3] in some documentation to the older version of the library; the concept carries over to the newer library.

### SD Library ###
The next largest usage is the [SD card libraries sector buffer][4], which is 512 bytes.

So between the two of them, there go 3/4 of your SRAM in just the two buffers, nevermind anything else.

You may be able to avoid this buffer by using a different library.  You could try [PetitFS][5].  The library it wraps [says it uses something like 44 bytes][6] plus whatever call stack is needed.

### String Literals ###

You have at least 206 bytes of string literals in your sketch alone, assuming the compiler can't determine that any of them are in fact unused.  There *may* be others in the libraries, though probably not many. So now we're down to at least 306 bytes or less SRAM.

|Size|String                                 |
|----|---------------------------------------|
|35  | `"RTC lost power, lets set the time!"`|
|28  | `"Card failed, or not present"`       |
|24  | `"Initializing SD card..."`           |
|18  | `"Couldn't find RTC"`                 |
|18  | `"card initialized."`                 |
|12  | `"open failed"`                       |
|11  | `"bYearStr: "`                        |
|10  | `"opening: "`                         |
|10  | `"Birthday!"`                         |
|10  | `"01-01.txt"`                         |
| 8  | `"bName: "`                           |
| 7  | `"Name: "`                            |
| 6  | `"Age: "`                             |
| 5  | `".txt"`                              |
| 2  | `"-" `                                |
| 2  | `"0"`                                 |
|206 | *Total*                               |

The `"0"` is only counted once in the above, even though you have two of them.  *Fun fact: the C and C++ languages allow identical string literals to be colocated or overlap.  I don't know whether or not avr-gcc will combine `"Name: "` into `"bName: "`, since you have bigger problems to worry about, I'm just pretending it won't without looking.*

Mitigation can include [use of the `F()` macro][7] to move some of these string literals into PROGMEM (flash).  You can't do this to every string literal, but the ones where you're involving them in a `String(F("we're trying to avoid these right?"))` constructor or in Serial (or other Stream/Print instances)'s `.print(F("Hello World"));`

The guts of the `F()` macro is another called `PSTR()`, which does the actual work of putting the string literal into PROGMEM.  `F()` tags the resulting pointer with a dummy type that is used in function overloading in Arduino libraries.  The only reason why I mention this is because below, you'll see me use `PSTR` to do the same thing, only with a function that belongs to avr-libc rather than Arduino.

Note when you're initializing a `String` object from a regular string literal, you're paying the SRAM cost twice for the lifetime of the `String` object.  One copy is in SRAM for the literal used to call the String constructor, the other copy is in the dynamic memory allocated to the String object.

String class
------------

This was pointed out in the comments; and it's true that it's better to avoid them.  Although, I think not actually the greatest problem in your case.

I see you've avoided unnecessarily adding them together for Serial output and instead are using separate `.print()` calls, so you're ahead of the game there.

For your filename, mitigation could be using fixed size local `char` array and `snprintf_P()` to cobble together your filename, something like:

```c++
char filename[sizeof "MM-DD.txt"];
snprintf_P(
    filename, sizeof filename,
    PSTR("u-u.txt"),
    tMth, tDy
);
```

or if you wanted to avoid pulling the beast of `printf` into your sketch, assuming it's not already there, you could do something like:

```c++
const char filename[] = {
    '0' + tMth / 10,
    '0' + tMth % 10,
    '-',
    '0' + tDy  / 10,
    '0' + tDy  % 10,
    '.',
    't',
    'x',
    't',
    '\0'
};
```

Serial
-----------
What `Serial`?  Yup, I mean, there's not a lot you can do about it, but I bring it up because the last conservative figure above was 306 bytes, and we didn't try to account for the what String is doing in the heap at all.  Well Serial takes 157 bytes according to a simple test here, which makes sense, because on the UNO it has two ring buffers for transmit and receive that are 64 bytes in size each, half a dozen pointers for configuring hardware registers to use, and head and tail indices for those buffers.  There's also another 12 bytes that are used for HardWareSerial's vtable.

So that puts you down to conservatively 137 bytes of SRAM for well, everything else.

### Everything Else ###

There's a lot not accounted for here. Your globals, the libraries globals, other vtables, the String data on the heap, and the stack.  Those are just the ones coming to mind.  I mean just the `millis()`/`micros()` counter variables and fract take 9 bytes.  If you really want to dig into the details here, besides looking at the stack pointer and heap structure, the `avr-nm` command run on your sketch's .elf file with its `-D`, `-S`, and `--size-sort` is helpful for locating global variable usage and similar things.

  [1]: https://github.com/adafruit/Adafruit_SSD1306/blob/2.4.4/Adafruit_SSD1306.cpp#L466
  [2]: https://github.com/olikraus/u8g2
  [3]: https://github.com/olikraus/u8glib/wiki/tpictureloop
  [4]: https://github.com/arduino-libraries/SD/blob/1.2.4/src/utility/SdFat.h#L465
  [5]: https://github.com/greiman/PetitFS
  [6]: http://elm-chan.org/fsw/ff/00index_p.html
  [7]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


body:
Can the ESP32 cam be used with no internet connection.

I have my newly acquired ESP32-CAM up and running as per this really great tutorial:

https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/

But I just realized the sketch has no HTML in it and must rely on internet access.

I need to stream video to my tablet when I don't have an internet connection.

Possible using the ESP32 Cam?

title: ESP32 cam offline

Answers: 0


body:
I used an HC-SR04 sensor and connected it to an Arduino board (BOARD1) with a 433 MHz transmitter, and the other board (BOARD2) is connected to the 433 MHz receiver. I don't know how to see the sensor value readings from the (BOARD1) in the serial monitor.

**HERE IS THE CODE OF THE TRANSMITTER**

    #include <RH_ASK.h>
    #include <SPI.h> // Not actually used but needed to compile

    RH_ASK driver;
    int echo=11;
    int trig=9; int sensorval;
    void setup() {
       Serial.begin(9600); // Debugging only
       driver.init();
    }

    void loop() {
       digitalWrite(trig,LOW);
       delayMicroseconds(10);
       digitalWrite(trig,HIGH);
       delayMicroseconds(10);
       digitalWrite(trig,LOW);
       delayMicroseconds(10);
       sensorval=pulseIn(echo,HIGH);
       const char *msg = sensorval;
       driver.send((uint8_t *)msg, strlen(msg));
       driver.waitPacketSent();
       delay(200);
    }

**HERE IS THE CODE OF THE RECEIVER**

    #include <RH_ASK.h>
    #include <SPI.h> // Not actually used but needed to compile

    RH_ASK driver;
    const int sensorval;
    void setup() {
        Serial.begin(9600); // Debugging only
        driver.init();
    }

    void loop() {
        uint8_t buf[4];
        uint8_t buflen = sizeof(buf);
        if (driver.recv(buf, &buflen)) // Non-blocking
        {
     Serial.print("message Received: ");
     Serial.println((char*)buf);
        }
    }

title: How do I get sensor values using transmitter and receiver?

Answers: 1

body:
**First: A short excourse about c-strings**

In C a string is an array of characters. Such an array is defined with

    char msg[10];

`10` being the size of the array. Every valid c-string needs to be terminated with the null character `\0`. This character is not printable, thus you don't see it normally. But the standard string functions (like `printf()`, `strlen()`, etc) use the null character to find the end of the string. So when handling strings as `char` arrays, you absolutely always need to terminate the string with the null character. The standard functions are incrementing through the array, until they find the null character. If it is missing, they don't stop at the end of the array.

Needing the null character also means, that the above `char` array can only hold 9 characters (since the 10th is the null character).

The standard functions for creating a string (like `printf()` and its siblings) already terminate the string correctly with the null character.

---

You are obviously trying to send an ASCII encoded string. But `sensorval` is not a string, it is of type `int` (a number). In C/C++ one does not simply implicitly convert a number to a string (please insert the image of boromir from Lord of the Rings here in your head). You actually have to say the compiler how to convert the number to a string. Also `sensorval` cannot itself hold that string (as it is an integer number). For that you need a `char` array (often called c-string) for saving all the characters of your string.

So first we need to define the `char` array to hold our string:

    char msg[10];

This creates a `char` array with 10 elements, each one can hold a character of your string. So you have space for 9 characters. If you need more, you can increase that number.

Now we need to build a string in `msg`, that represents the value of `sensorval`. For that we can use `sprintf()`, which lets us format a string out of data and save it in a `char` array.

    sprintf(msg, "%d", sensorval);

The first parameter is the `char` array to put the string in. The second parameter is called format-string. That is a string literal, that defines the format. `%d` represents an integer value; it is a placeholder for the actual data and describes, how it should be formatted (you can read about the different format options in the C++ documentation if you search for `printf()`). The following parameters (here only one) are the data values for the placeholders in the format string. Let's take an example: Assume `sensorval` is 1000. Then `msg` will be:

    1000\0

The `\0` being the null character.

So in your code you would replace

    const char *msg = sensorval;

with

    char msg[10];
    sprintf(msg, "%d", sensorval);

---

**What you have done in your code:**

This line

    const char *msg = sensorval;

will NOT create a string. You are defining `msg` as a pointer to a constant character (a pointer is a variable, that holds the address another variable in the memory, use google terms like "C pointers" for more info). And then you set the pointer to `sensorval`, which of course is not a valid pointer (valid meaning pointing to something reasonable here). It just points somewhere in the memory.

The example, that you got it from uses:

    const char *msg = "hello";

This works, because the compiler takes all string literals (the strings enclosed by the double quotes) and puts them fixed into the memory, somewhat like a variable without a name. So here the compiler instructs the microcontroller so save the string `"hello"` in the memory. With the above line we define a pointer to the place in the memory, where this string is saved.

So this works good for string literals, but not, if you first need to actually build the string.


body:
I'd successfully got my Nano 33 BLE Sense to read accelerometer data and subject to there being a difference between current and last readings, to send this via the EasyTransfer library to an XBee module over hardware serial that communicated with another module which published the readings to the AWS Cloud via a Nano IoT.  I then ambitiously decided I'd add more sensor data to the payload to include pressure, temperature and humidity.  I added these floats to my data structure (see code below) as well as Boolean flags to indicate if there had been an event (i.e. a reading over a threshold) and if any one of the flags was true, to transmit the payload.  The code compiles fine, uploads to complete but then the LED on the Nano flashes 3 times slowly and 5 times quickly in succession.  I had this last time because I'd forgotten a .begin() statement but adding this fixed the issue.  However, I've gone through my code and can't see what is causing the issue this time.  I have run smaller code units to check the sensors are working which they are. Help!!

    #include <EasyTransfer.h>
    #include <Arduino_LSM9DS1.h>
    #include <Arduino_LPS22HB.h>
    #include <Arduino_HTS221.h>

    #define TX_PIN 6
    #define RX_PIN 5

    const float MOTION_TOLERANCE = 0.01;
    const float PRESSURE_THRESHOLD = 1000.00;
    const float TEMPERATURE_THRESHOLD = 20.00;
    const float HUMIDITY_THRESHOLD = 50.00;

    UART XBeeTx(digitalPinToPinName(TX_PIN), digitalPinToPinName(RX_PIN), NC, NC);

    EasyTransfer ET;

    struct SEND_DATA_STRUCTURE {

      String sensorLocation;
      bool motionEvent;
      float xAcc;
      float yAcc;
      float zAcc;
      bool pressureEvent;
      float pressure;
      bool temperatureEvent;
      float temperature;
      bool humidityEvent;
      float humidity;

    };

    SEND_DATA_STRUCTURE myData;

    float xAccCurrent, yAccCurrent, zAccCurrent, xAccLast, yAccLast, zAccLast, pressureReading, temperatureReading, humidityReading;

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    void setup() {

    if(!IMU.begin()) {

      // Stop if IMU fails to initialise
      while(1);

    }

    if(!BARO.begin()) {

        // Stop if pressure sensor fails to initialise
      while(1);

    }
    if (!HTS.begin()) {

      // Stop if temp and humidity sensor fails to initialise
      while(1);

    }

     // Accelerometer code
       IMU.setAccelFS(3);
       IMU.setAccelODR(5);
       IMU.setAccelOffset(0.003955, -0.010136, -0.013462);
       IMU.setAccelSlope (0.997163, 1.000438, 0.995678);

    if (XBeeTx.available()) {

      XBeeTx.begin(9600);
      ET.begin(details(myData), &XBeeTx);

      }

       myData.sensorLocation = "Zone 1";

    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================

    void loop() {

    if (IMU.accelerationAvailable()) {

        IMU.readAcceleration(xAccCurrent, yAccCurrent, zAccCurrent);

      }

    if ((abs(xAccLast -xAccCurrent) > MOTION_TOLERANCE) || (abs(yAccLast -yAccCurrent) > MOTION_TOLERANCE) || (abs(zAccLast -zAccCurrent) > MOTION_TOLERANCE)) {

      myData.motionEvent = true;
      myData.xAcc = xAccCurrent;
      myData.yAcc = yAccCurrent;
      myData.zAcc = zAccCurrent;

      xAccLast = xAccCurrent;
      yAccLast = yAccCurrent;
      zAccLast = zAccCurrent;

    }

    pressureReading = BARO.readPressure(MILLIBAR);
    if (pressureReading > PRESSURE_THRESHOLD) {

      myData.pressureEvent = true;
      myData.pressure = pressureReading;

    }

    temperatureReading = HTS.readTemperature();
    if (temperatureReading > TEMPERATURE_THRESHOLD) {

      myData.temperatureEvent = true;
      myData.temperature = temperatureReading;

    }

    humidityReading = HTS.readHumidity();
    if (humidityReading > HUMIDITY_THRESHOLD) {

      myData.humidityEvent = true;
      myData.humidity = humidityReading;

    }

    if (myData.motionEvent || myData.pressureEvent || myData.temperatureEvent || myData.humidityEvent) {

     ET.sendData();

     delay(1000);

     myData.motionEvent = false;
     myData.pressureEvent =false;
     myData.temperatureEvent = false;
     myData.humidityEvent =false;

    }

    }

title: Nano 33 BLE Sense LED flashing 3/5 slow/fast after upload

Answers: 0


body:
I have a simple code that uses a tactile button and ESP8266.  I have one wire going from GND to one leg and one wire going from D3 to the other leg.  Works perfectly.  When I start it up, I have write statements in setup() which show that it is starting up and working.

I wanted to switch to a Touch Sensor.  I added a wire from one of the 3V3 to the VCC of the sensor.  If I do this while the program is running it seems to work... (it recognizes when I touch the sensor).  However, if I reset the ESP, then it no longer runs.  I see nothing in the serial window.

I tried to narrow the problem down and here's where I'm at...
1.  The ESP is connected via USB to the computer so I can look at the console window to track how it's running.
1.  I have a wire connected to D3 and GND (but the ends aren't connected to anything).  I reset the ESP and I see in the console window that it is printing out the expected print statements in setup().
2.  I add a wire to 3V3 (it is not connected to anything).  I reset the ESP and now no print statements are in the console window - so I believe it is not running.

Why?  I thought 3V3 was to connect to sensors to power them.  Not input to the ESP.  So what am I missing?

RESOLVED:  I randomly picked the wrong GPIO to use... I switched to D1 and it now works ok.

title: ESP8266 not running when connected to 3V3

Answers: 0


body:
https://infocenter.nordicsemi.com/pdf/nRF51822_PS_v3.4.pdf

The aim is to extract (output in serial monitor) the start up bits from  the SRAM of this microbit which is located at memory address 0x20000000, given by the datasheet above, all done in the arduino IDE.

After some searches I emerged on this code

    void setup()
    {
      uint8_t const * p;
      uint8_t i;

      Serial.begin( 115200 );

      p = 0;
      i = 0;

      do
      {
        Serial.print( *p, HEX );
        Serial.print( ' ' );

        ++i;
        ++p;

        if ( (i & 0xF) == 0 )
        {
          Serial.println();
        }
      }
      while ( i != 0 );
    }

    void loop()
    {
    }

From this link https://forum.arduino.cc/t/accessing-sram-on-arduino-uno/267777/6

However this pertains to an arduino uno and I'm not entirely sure how I would transfer it to my microbit.

title: Accessing start up bits of SRAM from MicroBit for PUF

Answers: 0


body:
I was watching Jeremy Blum's Arduino tutorial series, and he explained the need for debouncing in a simple circuit involving a pushbutton. Pressing the button once should mean the led *stays* on, and pushing the button again should mean the led should *stay* off, and so on.

He implemented hardware debouncing on this circuit: using an RC circuit along with an inverting Schmitt trigger.

https://www.youtube.com/watch?v=CRJUdf5TTQQ&list=PLA567CE235D39FA84&index=10 2:45-8:45.

However, the circuit isn't performing as expected, when I implemented the denbuncing. Its behaving as if the debouncing has no effect:-
[![enter image description here][1]][1]

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

If anyone wants to see the simulation:-
https://www.tinkercad.com/things/dniOQmnxJPY

Where exactly have I gone wrong? I have checked all the connections multiple times, it seems to be what Jeremy blum had in his video...

title: Basic hardware debouncing

Answers: 1

body:
You did not change the lastbutton, but you compared it to HIGH. Change your code to the one below.

You can more easily avoid such mistakes, if you put spaces around operators.

```
//sp is switchpin, lp is ledpin

int sp=2; //interrupt enabled pin (interrupt 0)
bool ledon=LOW;
bool lastbutton=LOW;
int lp=9;
void setup()
{
  Serial.begin(9600);
  pinMode(sp, INPUT);
  pinMode(lp,OUTPUT);
}

void loop()
{

   if (digitalRead(sp)==HIGH && lastbutton==LOW){
      ledon=!ledon;
      lastbutton = HIGH; // previously here was lastbutton==HIGH;
   }

   else {
     lastbutton=digitalRead(sp);
      }
   Serial.println(ledon);
   digitalWrite(lp,ledon);

     }
```


body:
 - I have tried so many things now that I am just confused.
 - I am not understanding the way *char arrays* work.
 - I can't get the date and names extracted.  And when I use just strings, I jam up the memory.

Below was my last attempt, before asking the question.

    while (f.available()) {
      String line = f.readStringUntil('\n');

      if (line.startsWith("04-23")) {
        currentDay = 1;
        int str_len = line.length() + 1;
        char char_array[str_len];
        line.toCharArray(char_array, str_len);
        Serial.println(char_array);                 // Everything works to here
        for (int j = 0; j < 2; j++) {
          b += char_array[j];
        }
        bMth = b.toInt (); // This should be an int of the birth month in this case: 04
      }
    }

    Var:
    format: MM-DD-YYYY,Name  // this is inside the file
    line = "04-23-2020,James"  // This is the output from - Serial.println(char_array);

**What I am trying to do is**
 - Extract the month/day so that I can compare it to today.
 - The year so I can calculate the age.
 - The name to display on OLED.
 - Everything else seems to work, but I can't get my head
   wrapped around the **char array** access.

To do this in PowerShell I would do:

    $line = "04-23-2020,James"

    $dob = ($line.Split(","))[0]
    $bMth = ($dob.Split("-"))[0] # This is not used in this example
    $bDy = ($dob.Split("-"))[1]  # This is not used in this example
    $bYr = ($dob.Split("-"))[2]

    $age = $(get-date -UFormat %Y) - $bYr

    Clear-Host
    Write-Host (@'
    Name: {0}
    Age:  {1}

    '@ -f $($line.Split(","))[1], $age)

In Python:

    import datetime as dt

    line = "04-23-2020,James"

    dob = (line.split(',')[0])
    bMth = (dob.split("-"))[0] # This is not used in this example
    bDy = (dob.split("-"))[1]  # This is not used in this example
    bYr = (dob.split("-"))[2]

    age = int(dt.datetime.now().year) - int(bYr)

    print('Name: ',(line.split(',')[1]))
    print('Age: ', age)

title: Would someone provide an example of extracting data from a char array?

Answers: 2

body:
You could try [sscanf][1] if your data format is fixed, something like this:

```c++
char line[] = "04-23-2020,James";
int day, month, year;
char name[100];
if (sscanf(line, "%d-%d-%d,%s", &month, &day, &year, name) == 4)
{
    // Process the four items.
}
```

  [1]: https://www.cplusplus.com/reference/cstdio/sscanf/

body:
When working with Arduino, [cplusplus.com][1] is your friend. Scroll down and look on the left side under **(string.h)**. Lot's of great `char` functions there. Other useful functions such as `iota()` - [cplusplus.com][2].

Here's one way to accomplish the parsing of the input data.

```
// Sketch uses 2064 bytes (6%) of program storage space.
// Global variables use 323 bytes (15%) of dynamic memory.
// Arduino IDE 1.8.9.
char line[] = "04-23-2020,James";
char Name[100];
unsigned int Month, Day, Year;

// Make an attempt to validate the input data.
byte Counter = 0;

void setup(){

  Serial.begin(9600);

  char * pch = strtok(line, "-,");

  while(pch != NULL){
    if(Counter == 0){Month = atoi(pch);}
    else if(Counter == 1){Day = atoi(pch);}
    else if(Counter == 2){Year = atoi(pch);}
    else if(Counter == 3){strcpy(Name, pch);}
    pch = strtok(NULL, "-,");
    Counter += 1;
  }

  // Print out the data.
  if(Counter == 4){
    Serial.println(Month);
    Serial.println(Day);
    Serial.println(Year);
    Serial.println(Name);
  }
  else{
    Serial.println("Error");
  }

}

void loop(){}
```

  [1]: https://www.cplusplus.com/reference/cstring/strcpy/
  [2]: https://www.cplusplus.com/reference/cstdlib/itoa/


body:
Have a set of Arduinos that need to swap data--for a model rocket launch controller!

How to send 24 bits of info (launch commands) from a "master" Arduino, 12 bits each to two "slave" Arduinos that are 15' to 150' away from the "master.

Each "slave" needs to send 12 bits of info (continuity statii) to the "master."

"Master" <--- 15' to 115' ---> "Slave 1" <--- 10' to 35' --> "Slave 2"

Seems too long for I2C?

title: Networking Multiple Arduinos -- Is It "Rocket Science?"

Answers: 2

body:
The best solution would be to use an RS485 adapter connected to each Arduino via serial port. This is a tried and true solution that is perfect for a setup like this and only costs a [few bucks of extra hardware][1] per node.

If you can't use additional hardware, you can also create a poor-man's current loop system like RS485 using normal Arduino pins since they are capable of sourcing and sinking 20mA.

With either of these solutions, you can send however much data as you want as long as you have some kind of minimal protocol to serialize it into a sequence of bits on the wire. To send 12 bits, you might just define a start condition as an idle "0" on the wire for a certain period of time, followed by a "1" start bit, followed by you 12 data bits, followed  maybe a parity bit or a checksum, and completed by a "1" stop bit.

Check out how, say RS232 or RS485 serialize bits to get an idea of how this works. If you end up using hardware that only supports sending data in 8 bit chunks, then you could, say, send two bytes per data "packet" where each byte has 6 bits of your data, plus one bit that indicates if ths byte is the first group of 6 bits or the second group, and then one bit of parity for error checking.

  [1]: https://amzn.to/3nAAou3

body:
I've got I2C to work reliability between Arduinos with different byte sizes. I have copied the test code below. Note that there is separate code for sending and receiving. It may need to be tweaked but contains the basic idea.

One (or more) Arduinos sends to main I2C controller:

**Sender Code:**
```
//sender test

#include <Wire.h>

#include <Wire.h>
#define NUMDATA 4

byte byteData[2 * NUMDATA]; //= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

//test

void setup()
{
  Wire.begin(3);                // join i2c bus with address #3
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
int aData;
  for(int i = 0; i < NUMDATA; i++){
    aData = analogRead(i);

    byteData[i*2 + 1] = ((aData >> 8)  & 0xFF);
    byteData[i*2] = (aData & 0xFF);

   // memcpy((void *)byteData[i*2], (void *) analogRead(i), sizeof(int));
  }

}

void requestEvent()
{
  Wire.write(byteData, 2 * NUMDATA);
}
```

**Receiving Code:**

```
#include <Wire.h>

void setup()
{
  Wire.begin();        // join i2c bus (address optional for main controller)
  Serial.begin(9600);  // start Serial for output
}

void loop()
{

  getSenderData();

  Serial.println("Hello");
  delay(500);
}

void getSenderData() {
//Gets sensor data for one grid

    //Byte Array to get raw bytes
    byte ICdataAsBytes[8];
    int i = 0;

    Wire.requestFrom(3,8);    // request 6 bytes from sending device #2

    while(Wire.available())    // sender may send less than requested
        ICdataAsBytes[i++] = Wire.read();

    int *tempData =(int*)&ICdataAsBytes;

    for( i = 0; i < 4; i++)
        Serial.println(tempData[i]);

}

```


body: When I interface LM35 temperature sensor and MQ-2 gas sensor with Arduino - my LM35 sensor gave incorrect values. From research I've found out that MQ-2 gas sensor dragging the AREF voltage down and causing the error due to its 31ohm heater that drawn 161mA current . What'll I do to solve this problem?

title: Interfacing LM35 and MQ2 with Arduino

Answers: 1

body:
A wiring diagram would help! But it sounds like you're powering your sensor from the Arduino's AREF pin. That is not the purpose of AREF; AREF is there for you to provide an accurate +5v or other reference voltage to the A/D convertor.

You need to power the sensor independently from your 5v supply (and not through the Arduino either, because of the sensors current draw); connect the sensor's Analog Out to one of the Arduino's A/D pins, sensor Ground to the supply ground. The digital out appears to be optional, if all you want is a go/no-go output that you adjust with the on-sensor potentiometer.


body:
Hello everyone I write my code and have some troubles.
When I write on in my serial monitor my buzzer condition wasn't changed.
Can you help me realize the reason. I wrote code with int type and it works with Serial.parseInt() function properly.

    String ask="Please enter buzzer condition";
    int buzzerPin=2;
    String state;
    void setup() {
      pinMode(buzzerPin,OUTPUT);
      Serial.begin(115200);

    }

    void loop() {
     Serial.println(ask);
     state=Serial.readString();
     Serial.println(state);
     while(Serial.available()==0){

     }
     if(state=="on"){
      digitalWrite(buzzerPin,HIGH);
     }
     if(state=="off"){
      digitalWrite(buzzerPin,LOW);
    }
    }

title: Arduino Serial.readString() trouble

Answers: 1

body:
You need to use `Serial.readStringUntil('\n')` instead of `Serial.readString` if you use the Arduino IDE's serial monitor (where a `\n` is added as termination character when you press enter).
Also remove that `while(Serial.available()==0)`. It will wait as long as there are any bytes in the serial buffer and as you don't `Serial.read()` within the loop, the buffer will not be emptied. So, if anything is received while `Serial.println(state)` is called or if you send two termination characters, the program will be stuck in that loop.


body:
I asked a question about this last time but I still couldn't make it work but it somehow gave me an overview about my project. Now I've created an another project that is similar to the last one, the only different thing is that I used a VirtualWire library. So I connected an HC-SR04 to an arduino board(BOARD1) with a transmitter; and a receiver to another board(BOARD2). I Followed a code in the internet similar to my project but he has an lcd display but I just want to make my sensor readings displayed in my Serial monitor what should I do?

**HERE IS THE CODE FOR THE TRANSMITTER**

    #include <VirtualWire.h>
    const int trig= 9;
    const int echo= A1;

    float sensorval;
    float distance;
    char msg[6];

    void setup() {
      vw_set_tx_pin(12);
      vw_setup(2000);
      pinMode(trig,OUTPUT);
      pinMode(echo,INPUT);
      Serial.begin(9600);

    }

    void loop() {
      digitalWrite(trig,LOW);
       delayMicroseconds(10);
       digitalWrite(trig,HIGH);
       delayMicroseconds(10);
       digitalWrite(trig,LOW);
       delayMicroseconds(10);
       sensorval=pulseIn(echo,HIGH);

       distance = (sensorval*.0343)/2;

       Serial.print("Distance: ");
       Serial.println(distance);
       dtostrf(distance, 6,2,msg);
       vw_send((uint8_t *)msg, strlen(msg));
       vw_wait_tx();
       delay(500);

    }

**AND HERE IS THE CODE FOR THE RECEIVER**

    #include<VirtualWire.h>
    #include <Wire.h>

    int i;
    void setup() {
      vw_set_rx_pin(12);
      vw_setup(2000);
      vw_rx_start();

    }

    void loop() {
      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;

      if (vw_get_message(buf, &buflen)){
        Serial.print("distance is: ");
       Serial.print((char *)buf);
          Serial.print(buf[i]);
        }

      }

title: What is wrong with my code? (HC-SR04 using 433 mhz module);

Answers: 0


body:
I have a problem with getting my buzzer to only do the tones I programmed in *once*. I know I have to add some sort of code but I'm relatively new to this so I don't really know. I want it to start playing the tones I have in the code once I press the button. After that it should immediately stop, without looping everything until I press the button again. Basically I have these LEDs that light up in a row with every time I press my button and once the last LED lights up, the buzzer should play its melody. After that, I can press my button again and the whole thing starts from the beginning. If anyone could help, I'd be more than grateful!

This is my code:

```
#define button 3

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3,INPUT);
  pinMode (11,OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

  buttonPoll = digitalRead (3);
  if (buttonPoll ==1) {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0) {
      state = old + 1;
    }
  }
  else {
    delay(100);

  }

  switch (state) {
    case 1:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 2:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 3:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 4:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 5:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 6:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 7:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 8:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 9:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 10:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, HIGH);
   old = state;

       tone (11,261);
      delay(250);

      tone(11, 330);
      delay(250);

      tone(11,391.99);
      delay(250);

      tone(11,440);
      delay(250);

      tone(11, 391.995);
      delay(250);

      tone(11, 330);
      delay(250);

        }

    break;

   default:
  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

    old = 0;

    break;

  }
}
```

title: How do I make my piezo buzzer only hum once without repetition?

Answers: 3

body:
Enshrine the first section of the `loop()` code inside a `while` loop.

    while (condition)
    {
        // this code executes continually until 'condition' is true
    }

In your case, the variable `state` changes when an active button press is recorded: use that as your `condition`.

    while (state == old)
    {
      buttonPoll = digitalRead (3);
      if (buttonPoll ==1)
      {
        delay (50);
        buttonPoll = digitalRead (3);
        if (buttonPoll == 0)
        {
          state = old + 1;
        }
      }
      else
      {
        delay(100);
      }
    }

So long as `state` stays the same, i.e. it equals `old`, the code within the `while` loop will execute indefinitely.
*NOTE:* Any code outside the `while` loop will effectively only run once. You may find, if you expand the code, most of it lives within the `while` loop. If that is the case there may be better approach to consider.

body: Once the LEDs & Piezo sequence finishes, your code doesn't wait for the button to be pressed again. If the button is not pressed, the code doesn't wait, it merely delays for 100ms, then repeats the sequence.

body:
Welcome to ASE :)

1. You have mapped the Tone function and the LED to the same Pins. So, you may have to find another pin for the buzzer (pin 0 )
2. I have taken code from @charlieHanson as well.
3. The braces for the switch statement were put in the wrong place. I have fixed it.

Have a try: The code is here

    #define button 3

    #define LED 1
    #define twoLED 2
    #define threeLED 4
    #define fourLED 5
    #define fiveLED 6
    #define sixLED 7
    #define sevenLED 8
    #define eightLED 9
    #define nineLED 10
    #define tenLED 11

    int state = 0;
    int old = 0;
    int buttonPoll = 0;

    void setup() {
      pinMode (3, INPUT_PULLUP);
      pinMode (11, OUTPUT);
      pinMode(LED, OUTPUT);
      pinMode(twoLED, OUTPUT);
      pinMode(threeLED, OUTPUT);
      pinMode(fourLED, OUTPUT);
      pinMode(fiveLED, OUTPUT);
      pinMode(sixLED, OUTPUT);
      pinMode(sevenLED, OUTPUT);
      pinMode(eightLED, OUTPUT);
      pinMode(nineLED, OUTPUT);
      pinMode(tenLED, OUTPUT);

      digitalWrite(LED, LOW);
      digitalWrite(twoLED, LOW);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);

    }

    void loop() {

      while (state == old)
      {
        buttonPoll = digitalRead (3);
        if (buttonPoll == 1)
        {
          delay (50);
          buttonPoll = digitalRead (3);
          if (buttonPoll == 0)
          {
            state = old + 1;
          }
        }
        else
        {
          delay(100);
        }
      }

      switch (state) {
        case 1:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, LOW);
          digitalWrite(threeLED, LOW);
          digitalWrite(fourLED, LOW);
          digitalWrite(fiveLED, LOW);
          digitalWrite(sixLED, LOW);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 2:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, LOW);
          digitalWrite(fourLED, LOW);
          digitalWrite(fiveLED, LOW);
          digitalWrite(sixLED, LOW);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 3:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, LOW);
          digitalWrite(fiveLED, LOW);
          digitalWrite(sixLED, LOW);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 4:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, LOW);
          digitalWrite(sixLED, LOW);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 5:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, HIGH);
          digitalWrite(sixLED, LOW);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 6:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, HIGH);
          digitalWrite(sixLED, HIGH);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 7:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, HIGH);
          digitalWrite(sixLED, HIGH);
          digitalWrite(sevenLED, HIGH);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 8:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, HIGH);
          digitalWrite(sixLED, HIGH);
          digitalWrite(sevenLED, HIGH);
          digitalWrite(eightLED, HIGH);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 9:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, HIGH);
          digitalWrite(sixLED, HIGH);
          digitalWrite(sevenLED, HIGH);
          digitalWrite(eightLED, HIGH);
          digitalWrite(nineLED, HIGH);
          digitalWrite(tenLED, LOW);
          old = state;
          break;

        case 10:
          digitalWrite(LED, HIGH);
          digitalWrite(twoLED, HIGH);
          digitalWrite(threeLED, HIGH);
          digitalWrite(fourLED, HIGH);
          digitalWrite(fiveLED, HIGH);
          digitalWrite(sixLED, HIGH);
          digitalWrite(sevenLED, HIGH);
          digitalWrite(eightLED, HIGH);
          digitalWrite(nineLED, HIGH);
          digitalWrite(tenLED, HIGH);
          old = 0;
          state = 0;

          tone (11, 261);
          delay(250);

          tone(11, 330);
          delay(250);

          tone(11, 391.99);
          delay(250);

          tone(11, 440);
          delay(250);

          tone(11, 391.995);
          delay(250);

          tone(11, 330);
          delay(250);
          noTone(11);

          break;

        default:
          digitalWrite(LED, LOW);
          digitalWrite(twoLED, LOW);
          digitalWrite(threeLED, LOW);
          digitalWrite(fourLED, LOW);
          digitalWrite(fiveLED, LOW);
          digitalWrite(sixLED, LOW);
          digitalWrite(sevenLED, LOW);
          digitalWrite(eightLED, LOW);
          digitalWrite(nineLED, LOW);
          digitalWrite(tenLED, LOW);

          old = 0;

          break;

      }
    }

Here is the preview :)
[![enter image description here][2]][2]

Here is the Arduino simulator link: [https://wokwi.com/arduino/projects/297098737606459913][1]

  [1]: https://wokwi.com/arduino/projects/297098737606459913
  [2]: https://i.stack.imgur.com/whbd9.gif


body:
Sometimes the built-in LED pulsates after an upload. It could be after a failed upload but I'm not entirely sure. What does this indicate? I haven't been able to find any information about it.

It doesn't blink like in the Bliky example. It pulsates.

The led is not controlled by a Sketch. Usually this happens after a failed upload, and the previous Sketch doesn't work anymore.

title: Why does the MKR WiFi 1010 LED_BUILTIN sometimes pulsate?

Answers: 0


body:
Each time I attempt to upload to the *MKR WiFi 1010* board the COM-port gets disconnected, usually at one of the following points:

 1. Either it disconnects just after compiling/verifying. In this case the `LED_BUILTIN` pulsates slowly, and the USB-cable needs to be reconnected in order to try again. The next attempt usually results in `2.`.

 2. Or, it disconnects after a successful upload. The next attempt to upload will always result in `1.` occurring. When this happens the COM-port is still visible in Windows Device Manager but it can't be found by a Serial Monitor.

Any ideas what could be causing this or what could be done to have it stay connected? With an *UNO* this doesn't happen.

title: MKR 1010 disconnects COM-port on each upload

Answers: 1

body: This was due to using a virtual machine (VMware) which apparently doesn't handle the MKR board COM-port so well. Moving the development environment to the host solved the problem. It still disconnects the COM-port after upload but then consistently reconnects to the same COM-port and that's good enough.


body:
**Prelude**

I haven't done a lot of work in programming chips. The ATTiny85 is the first chip I've programmed, and I have the hang of the basics I think, but I don't have an in-depth understanding of it's capabilities and how to perform complex circuits with it.

**The Issue**

I cannot get the following to work: utilize any combination of PWM Pins with 2 Servos, and ADC (Analog to Digital Converter) Pins connected to a Joystick to control the servos using an ATTiny85.

My code works fine with an Arduino Uno R3. Porting it over to the ATTiny85 only lets me control 1 servo with 1 axis of the joystick (x or y).

As far as I can see from [ATTiny85 Pinout][1], there are 3 PWM pins (PB0, PB1 and PB4) that I can use for the Servo data line, and 4 ADC Pins (PB2, PB3, PB4 and PB5) that I can use to send output from the joystick.

Swapping servos works fine - so I know they're not causing issues.
Swapping joystick axis works fine - so that's not it.

Running the code on the Arduino and viewing in the Serial Monitor shows that the joystick is writing correctly for both the X and Y axis - and is correctly mapping the coordinates to the serial output.

I can list out the different pins I've tried to use for the servos and the joystick - but at this point I think this is a capability issue of the ATTiny85 - and the latest pins I've tried are in the code.

I can give pictures/diagrams of my wiring for the servos and joysticks to the ATTiny85 if someone needs them, or of the wiring I use to program the ATTiny85 if it's useful.

I'm currently still debugging this issue and trying to find what's going wrong - but so far no luck. I haven't tried debugging the ATTiny85 with the serial monitor, but I've just been reprogramming it and trying different combinations of pins and code commented out. I will update the question as I discover more information.

**Something strange**

In my setup() code - the S1_.write(S1_Center) works, and the servo moves to the center of it's set limitations - but after that it is not responsive to the joystick. At least that tells me every time I run it that the servo is attached and able to receive a write() and so is functional - and leads me to believe that I have an issue with the Analog/Serial side of things, but I'm not sure.

**Questions**

Is it possible to control 2 servos with a joystick (X-axis for one servo, Y-axis for another - essentially 2 potentiometers in lieu of joystick) using an ATTiny85?

Am I using incorrect pins for the ATTiny85 to do this? ADC and PWM?

Is the issue with the code I'm using or is this a hardware constraint for the ATTiny85?

If anyone has any advice at the least it would be helpful. I know this question is to a somewhat specific scenario - but in doing my (apparently not very good) research I can only find very basic - non analog/serial ways people drive servos which I already know how to do.

Here is the code I've written that works standalone with Arduino but not with the ATTiny85.

    #include <Servo_ATTinyCore.h>

    Servo S1_;  // create servo object to control a servo
    Servo S2_;  // create servo object to control a servo

    //Joystick 1 inputs (Joystick -> Arduino)
    int J1_VRx = PIN_PB3; //Attiny85 PB3 (Physical pin 2) - as per SpenceKonde ATtinyCore Github 'You cannot use the Pxn notation (ie, PB2, PA1, etc) to refer to pins ... use PIN_Pxn (ex, PIN_PB2)'
    int J1_VRy = PIN_PB2; // Attiny85 PB4 (Physical pin 7)
    int J1_SW = PIN_PB4; // Attiny85 PB2 (Physical pin 3)

    //Joystick 1 variables
    int J1_xPosition = 0;
    int J1_yPosition = 0;
    int J1_SW_state = 0;
    boolean J1_SW_pressed = false;
    //int J1_SW_state_read = 0;
    //boolean buttonPressed
    int J1_mapX = 0;
    int J1_mapY = 0;

    //Servo output (Arduino -> Servo)
    int S1_Output = PIN_PB1;
    int S2_Output = PIN_PB0;

    //Servo Variables
    int S1_Limits[2] = {0,180};  // set limitations (min/max: 0->180)
    int S2_Limits[2] = {0,180};  // set limitations (min/max: 0->180)
    boolean refresh = false;  // toggle refresh on/off
    int S1_Degree = 0;
    int S2_Degree = 0;
    int S1_Speed = 0;
    int S2_Speed = 0;
    int S1_Speed_Limit = 2; //controls how quickly the servo can move
    int S2_Speed_Limit = 2; //controls how quickly the servo can move
    int speedModes[3] = {1,2,3}; //Define the speeds which can be toggled between
    int speedMode = 2; //Set initial speed mode (speedModes[1] if this value is 1)

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

      //Assign Joystick 1 pins
      pinMode(J1_VRx, INPUT);
      pinMode(J1_VRy, INPUT);
      pinMode(J1_SW, INPUT_PULLUP);

      //Assign Servo pin
      S1_.attach(S1_Output);
      S2_.attach(S2_Output);

      //Get center of Servo limitations
      int S1_Center = ((S1_Limits[0]/2) + (S1_Limits[1]/2));
      int S2_Center = ((S2_Limits[0]/2) + (S2_Limits[1]/2));

      //Send servos to center
      S1_.write(S1_Center);
      S2_.write(S2_Center);

      //Set servo current degrees as at center
      S1_Degree = S1_Center;
      S2_Degree = S2_Center;

      //Set servo initial speed limit
      S1_Speed_Limit = speedModes[speedMode - 1];
      S2_Speed_Limit = speedModes[speedMode - 1];

    }

    void loop() {

      //Reset servo direction speeds
      S1_Speed = 0;
      S2_Speed = 0;

      //Read Joystick 1 inputs
      J1_xPosition = analogRead(J1_VRx);
      J1_yPosition = analogRead(J1_VRy);
      J1_SW_state = digitalRead(J1_SW);
      J1_mapX = map(J1_xPosition, 0, 1023, -1024, 1024); //X-position of joystick
      J1_mapY = map(J1_yPosition, 0, 1023, -1024, 1024); //Y-position of joystick

      //Fix offsets for joysticks (custom fixes because these joysticks aren't perfect :/)
      J1_mapX += 6;
      J1_mapY += 20;

      delay(10);

      boolean J1_SW_toggled = false;
      //If the button is down
      if(J1_SW_state == 0) {
        J1_SW_pressed = true;
        //Joystick button pressed
      }
      //If the button was down and is now up
      if(J1_SW_pressed == true && J1_SW_state == 1) {
        J1_SW_pressed = false;
        J1_SW_toggled = true;
        //Joystick button released
      }

      //Cycle the speed mode for servos 1, 2 and 3
      if(J1_SW_toggled) {
        J1_SW_toggled = false;
        if (speedMode != speedModes[(sizeof(speedModes) / sizeof(int)) - 1]) { //This is how to get length of speedModes array of byte type int
          speedMode += 1;
        }
        else {
          speedMode = 1;
        }
        S1_Speed_Limit = speedModes[speedMode - 1];
        S2_Speed_Limit = speedModes[speedMode - 1];
      }

      int stutterSetting = 100; //+- buffer to keep servos from moving due to imperfect readouts from joysticks

      if(J1_mapY > stutterSetting || J1_mapY < -stutterSetting) {
        S1_Speed = map(J1_mapY, -512, 512, S1_Speed_Limit, -S1_Speed_Limit);
      }
      if(J1_mapX > stutterSetting || J1_mapX < -stutterSetting) {
        S2_Speed = map(J1_mapX, -512, 512, S2_Speed_Limit, -S2_Speed_Limit);
      }

      if(S1_Speed != 0) {
        if((S1_Degree + S1_Speed) < S1_Limits[1] && (S1_Degree + S1_Speed) > S1_Limits[0]) {
          S1_Degree += S1_Speed;
          S1_.write(S1_Degree);
          delay(10);
        }
      }

      if(S2_Speed != 0) {
        if((S2_Degree + S2_Speed) < S2_Limits[1] && (S2_Degree + S2_Speed) > S2_Limits[0]) {
          S2_Degree += S2_Speed;
          S2_.write(S2_Degree);
          delay(10);
        }
      }

    //  Serial.print("J1_X: ");
    //  Serial.print(J1_mapX);
    //  Serial.print(" | J1_Y: ");
    //  Serial.print(J1_mapY);
    //  Serial.print(" | S1_Speed: ");
    //  Serial.print(S1_Speed);
    //  Serial.print(" | S1_Degree: ");
    //  Serial.print(S1_Degree);
    //  Serial.print(" | S2_Speed: ");
    //  Serial.print(S2_Speed);
    //  Serial.print(" | S2_Degree: ");
    //  Serial.println(S2_Degree);
    }

  [1]: https://github.com/SpenceKonde/ATTinyCore#attiny254585

title: How can I control 2 servos separately using a joystick on an ATTiny85?

Answers: 0


body:
For some reason my motor moves a certain amount every time I open the serial port without giving it any other instructions. It will move further by the same amount if I close and reopen the serial port. Please could someone tell me how to avoid this? I haven't had this problem before.

I am using two stepper motors with a A4988 driver each.

Here is my code so far

    #include <AccelStepper.h>
    #include <MultiStepper.h>

    // Define pin connections
    const int dirPin1 = 2;
    const int stepPin1 = 3;
    const int dirPin2 = 4;
    const int stepPin2 = 5;

    String incomingByte; // for incoming serial data

    // Define motor interface type
    #define motorInterfaceType 1

    // Creates an instance
    AccelStepper stepper1(motorInterfaceType, stepPin1, dirPin1);
    AccelStepper stepper2(motorInterfaceType, stepPin2, dirPin2);

    MultiStepper steppers;

    void setup() {
      Serial.begin(9600);
      String excess1 = Serial.readString();
      // Configure each stepper
      stepper1.setCurrentPosition(0);
      stepper2.setCurrentPosition(0);
      stepper1.setMaxSpeed(100);
      stepper2.setMaxSpeed(100);
      stepper1.setAcceleration(10);
      stepper2.setAcceleration(10);
      // Then give them to MultiStepper to manage
      steppers.addStepper(stepper1);
      steppers.addStepper(stepper2);
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.readString();

        // say what you got:
        Serial.print("I received: ");
        //Serial.println(incomingByte, DEC);
        Serial.println(incomingByte);

        int x = incomingByte.toInt();

        long positions[2];

        positions[0] = x;
        positions[1] = 0;
        steppers.moveTo(positions);
        steppers.runSpeedToPosition();
      }
    }

title: Why does my stepper motor run when I open the Serial port?

Answers: 1

body:
When you open or reopen the Serial port, the Arduino resets (depending on how you open it; some programs don't send the signal on DTR or RTS, which result in the reset).

My guess is, that the stepper driver reacts to the Arduino configuring its pins for the stepper. Difficult to say, what exactly happens there. To mitigate that, you can add an external pulldown resistor (assuming you have an active high stepper driver. For active low use a pullup resistor). That should keep the step line of the driver low even when its not actively driven by the Arduino.


body:
I'm having an issue with Blynk.begin(auth, ssid, pass);
The problem is, when it fails to connect to the wifi, the rest of the program does not continue.

I'm using a Wemos D1 and it is also controlling some relays based on a temperature sensor.
But when there was a power outage and power comes back on, the programs should continue whether the wifi is working or not, so that relays can still be controlled by the temperature sensor reading.

What happens now is if there is a wifi issue when Wemos D1 is starting up again, the program simply stops in the void setup() at Blynk.begin(auth, ssid, pass); and the rest of the program cannot be executed.

Anyone knows how to avoid this?

Kind regards,
Peter

title: Blynk, but continue program if Blynk connection fails

Answers: 1

body:
You can try my [Blynk_WM](https://github.com/khoih-prog/Blynk_WM) or [Blynk_Async_WM](https://github.com/khoih-prog/Blynk_Async_WM) library with their Blynk.begin() functions are not blocking.

---

Check [Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features](https://github.com/khoih-prog/Blynk_WM#why-using-this-blynk_wifimanager-with-multiwifi-multiblynk-features)

### Why using this [Blynk_WiFiManager](https://github.com/khoih-prog/Blynk_WM) with MultiWiFi-MultiBlynk features

You can see that the system **automatically detects and connects to the best or avaiable WiFi APs and/or Blynk Servers**, whenever interruption happens. This feature is very useful for systems requiring high degree of reliability.

Moreover, this `Blynk.begin()` is **not a blocking call**, so you can use it for critical functions requiring in loop().

Anyway, this is better for projects using Blynk just for GUI (graphical user interface).

In operation, if WiFi or Blynk connection is lost, `Blynk.run()` will try reconnecting automatically. Therefore, `Blynk.run()` must be called in the `loop()` function. Don't use:

```cpp
void loop()
{
  if (Blynk.connected())
     Blynk.run();

  ...
}
```
just

```cpp
void loop()
{
  Blynk.run();
  ...
}
```

---

It's also beneficial to search in [Blynk Forum](https://community.blynk.cc) for more information and examples


body:
Can anyone please help me with this error?

```
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

Sketch uses 2964 bytes (9%) of program storage space. Maximum is 32256 bytes.

Global variables use 89 bytes (4%) of dynamic memory, leaving 1959 bytes for local variables. Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xcd

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xcd

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xcd

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

With enabled a in comment:
```
Arduino: 1.8.13 (Windows 10), Board: "Arduino Duemilanove or Diecimila, ATmega168"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries D:\Documents\Arduino\libraries -fqbn=arduino:avr:diecimila:cpu=atmega168 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\Mark\AppData\Local\Temp\arduino_build_293669 -warnings=none -build-cache C:\Users\Mark\AppData\Local\Temp\arduino_cache_250344 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose D:\Downloads Chrome\sketch_apr20a\sketch_apr20a.ino

C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries D:\Documents\Arduino\libraries -fqbn=arduino:avr:diecimila:cpu=atmega168 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\Mark\AppData\Local\Temp\arduino_build_293669 -warnings=none -build-cache C:\Users\Mark\AppData\Local\Temp\arduino_cache_250344 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose D:\Downloads Chrome\sketch_apr20a\sketch_apr20a.ino

Using board 'diecimila' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr

Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr

Detecting libraries used...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

Alternatives for Servo.h: [Servo@1.1.6 Servo@1.1.3]

ResolveLibrary(Servo.h)

  -> candidates: [Servo@1.1.6 Servo@1.1.3]

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "-ID:\\Documents\\Arduino\\libraries\\Servo\\src" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\avr\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\megaavr\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\nrf52\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\sam\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\samd\Servo.cpp

Using cached library dependencies for file: D:\Documents\Arduino\libraries\Servo\src\stm32f4\Servo.cpp

Generating function prototypes...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "-ID:\\Documents\\Arduino\\libraries\\Servo\\src" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE

"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\preproc\\ctags_target_for_gcc_minus_e.cpp"

Compiling sketch...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega168 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DUEMILANOVE -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "-ID:\\Documents\\Arduino\\libraries\\Servo\\src" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp" -o "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp.o"

Compiling libraries...

Compiling library "Servo"

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\avr\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\megaavr\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\nrf52\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\sam\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\samd\Servo.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\libraries\Servo\stm32f4\Servo.cpp.o

Compiling core...

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_pulse.S.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\hooks.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\WInterrupts.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_analog.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_shift.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_digital.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\wiring_pulse.c.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\CDC.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial1.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\PluggableUSB.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial3.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\IPAddress.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial2.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\HardwareSerial0.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\WMath.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\Print.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\WString.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\abi.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\Stream.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\Tone.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\new.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\USBCore.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\main.cpp.o

Using previously compiled file: C:\Users\Mark\AppData\Local\Temp\arduino_build_293669\core\core.a

Archiving built core (caching) in: C:\Users\Mark\AppData\Local\Temp\arduino_cache_250344\core\core_arduino_avr_diecimila_cpu_atmega168_0c812875ac70eb4a9b385d8fb077f54c.a

Linking everything together...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega168 -o "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\sketch\\sketch_apr20a.ino.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\avr\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\megaavr\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\nrf52\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\sam\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\samd\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669\\libraries\\Servo\\stm32f4\\Servo.cpp.o" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/core\\core.a" "-LC:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669" -lm

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.eep"

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf" "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.hex"

Multiple libraries were found for "Servo.h"

 Used: D:\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files (x86)\Arduino\libraries\Servo

Using library Servo at version 1.1.3 in folder: D:\Documents\Arduino\libraries\Servo

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\Mark\\AppData\\Local\\Temp\\arduino_build_293669/sketch_apr20a.ino.elf"

Sketch uses 2964 bytes (20%) of program storage space. Maximum is 14336 bytes.

Global variables use 89 bytes (8%) of dynamic memory, leaving 935 bytes for local variables. Maximum is 1024 bytes.

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega168 -carduino -PCOM4 -b19200 -D -Uflash:w:C:\Users\Mark\AppData\Local\Temp\arduino_build_293669/sketch_apr20a.ino.hex:i

avrdude: Version 6.3-20190619

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM4

         Using Programmer              : arduino

         Overriding Baud Rate          : 19200

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x62

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x62

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

'''
```

title: Arduino Uno Clone Error Compilig AVRDUDE

Answers: 0


body:
I’ve already searched through the internet but cannot find satisfactory answer.
Is there an easy way to get value of variable passed through an URL?
What I mean is I want to start a web server on my Arduino then call the URL like `10.0.0.1/?var1=x&var2=y` from my browser and read `var1` and `var2` to my program.
I could also use JSON format but how to send it to my Arduino and then read it?
I use Arduino Ethernet Shield W5100.
Any ideas?

title: Arduino web server-how to get values form URL

Answers: 0


body:
Good afternoon, I wonder if you could help me. I have the code but the data from the sensors is not correct. Perhaps there are some errors, could you fix them?

I apologise for my inaccurate statement. I have the task of displaying data from three sensors on the screen. I've written a sketch, but it doesn't work correctly. That is, the data from two sensors (ds18b20, yl-69) is not displayed correctly. I think the problem is with the sketch.
The data from sensor ds18b20 is constantly displayed differently, and partly depends on the data from sensor yl-69, although it should not. All sensors should work separately from each other, but give their data to the arduino

    #include <DallasTemperature.h>

    #include <OneWire.h>
    #include <DS18B20.h>

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    #include <DHT.h>

    const uint8_t ds1Pin{7};            // DS18b20 будем подключать к пину D7
    const uint32_t msRepTime {10000};   // DS18b20 будем опрашивать каждые 10 секунд (по факту каждые 11)
    uint32_t msTemp {msRepTime};        // Объявляем счетчик для опроса DS18b20 и инициализируем его значением для моментального начала процедуры
    const uint8_t simvol[8] = {B11100,B10100,B11100,B00000,B00000,B00000,B00000,B00000};
    uint8_t ds1Qty {1};                 // Количество датчиков DS18b20 на пине (не более 3-х). Если больше одного, значения будут усредняться
    int8_t  ds1Temp {0};                // Собственно, значение температуры по Цельсию от DS18b20
    uint8_t ds1DS[3][8];                // Адреса положу пока здесь. Если кому не лень, их нужно убрать из глобальной ОВ, как и количество датчиков

    const uint8_t DHTPin{8};            // DHT будем подключать к пину D8
    float dhtTemp {0};                  // DHT значение температуры
    float dhtHum {0};                   // DHT значение влажности
    const uint32_t msDhtTime {5017};    // DHT будем опрашивать каждые 5+ секунд. "Кривое" значение, чтобы не пересекаться по времени с опросом DS
    uint32_t msDht {msDhtTime};         // Объявляем счетчик для опроса DHT и инициализируем его значением для моментального начала процедуры

    const uint8_t ylPin{14};            // YL будем подключать к пину A0(14). ВНИМАНИЕ: подключение аналогового выхода датчика!
    uint16_t ylVal{0};                  // Переменная для показаний датчика влажности YL
    const uint32_t msYlTime {100};      // YL будем опрашивать каждые 0.1 секунд, чтобы МК хоть чем-то был занят в цикле))
    uint32_t msYl {0};                  // Объявляем счетчик для опроса YL-69

    const uint32_t msPageExpo {5000};   // Устанавливаем по 5 секунд на отображение каждой страницы
    uint32_t msPage {0};                // Объявили счетчик для экрана

    LiquidCrystal_I2C lcd(0x27, 16, 2);
    DHT dht(DHTPin, DHT11);
    OneWire oneWire(DS18B20);

    void setup() {
      Serial.begin(9600);     // Скорость должна соответствовать настройкам монитора порта
      lcd.init();
      lcd.backlight();
      dht.begin();
      searchSensors();          // Запускаем первоначальный поиск датчиков DS18b20 на пине
    }

    void loop() {

      if (millis() - msTemp > msRepTime)  updateTemp();       // Опрашиваем температуру DS18b20 с частотой msRepTime
      if (millis() - msDht > msDhtTime)   runDht();           // Опрашиваем DHT
      if (millis() - msYl > msYlTime)     runYl();            // Опрашиваем YL-69
      if (millis() - msPage > msPageExpo) updatePage();       // Листаем страницы

    }

    //**************  Секция экранчег  ****************************
    void updatePage(){                       // Листаем страницы на экранчике
      static uint8_t page {0};
    //  Первая страница
      if (page == 0){
        lcd.setCursor(0,0);
        lcd.print("temp water:    ");
        lcd.setCursor(0,1);
        lcd.print((int8_t)ds1Temp);
        lcd.setCursor(3,1);
        lcd.print("C   ");
        msPage = millis();
        page++;
        return;
      }
    //  Вторая страница
      if (page == 1){
        lcd.setCursor(0,0);
        lcd.print("temp air:         ");
        lcd.setCursor(0,1);
        lcd.print((int8_t)dhtTemp);
        lcd.setCursor(2,1);
        lcd.print("C   ");
        msPage = millis();
        page++;
        return;
      }
    //  Третья страница
      if (page == 2){
        lcd.setCursor(0,0);
        lcd.print("hum air:         ");
        lcd.setCursor(0,1);
        lcd.print((uint8_t)dhtHum);
        lcd.setCursor(2,1);
        lcd.print("%   ");
        msPage = millis();
        page++;
        return;
      }
    // Последняя страница
      if (page == 3){
        lcd.setCursor(0,0);
        lcd.print("hum earth:         ");
        lcd.setCursor(0,1);
        lcd.print((uint16_t)ylVal);
        lcd.setCursor(3,1);
        lcd.print("%   ");
        msPage = millis();
        page = 0;
        return;
      }
    }

    //**************  Секция YL-69  ****************************
    void runYl(void){
      ylVal = analogRead(ylPin);; //Измеряем влажность. Маппинг пишем сами, если надо
      msYl = millis();
    }

    //**************  Секция DHT  ****************************
    void runDht(void){
      dhtHum = dht.readHumidity();          //Измеряем влажность
      dhtTemp = dht.readTemperature();      //Измеряем температуру
      msDht = millis();
    }

    //**************  Секция DS18b20  ****************************
    void updateTemp(){                       // Основная процедура обновления температурных данных со всех датчиков
      static uint8_t stage {0};
    //  Первый этап. Отправка запросов на конвертацию
      if (stage == 0){
        if (ds1Qty) requestSensor(ds1Pin);
        stage++;
        msTemp = millis() - msRepTime + 800;    // 0.75 секунды требуется датчику для осуществления конвертации на максимальном разрешении
        return;
      }
    // Второй этап. Чтение показаний
      if (stage == 1){
        if (ds1Qty) readSensor(&ds1Temp, ds1Pin, ds1DS, ds1Qty);
        msTemp = millis();
        stage = 0;
        return;
      }
    }

    void readSensor(int8_t* t, uint8_t pin, void* buf, uint8_t qt){       // Чтение температуры с датчика ds18b20
      OneWire ds(pin);
      uint8_t addr[8];
      uint8_t data[9];
      float temp[3];
      uint8_t qty {0};
      for (uint8_t c {0}; c < qt; c++){
        for(uint8_t i {0}; i<8 ;i++) addr[i] = *((uint8_t*)buf+c*8+i);
        ds.reset(); ds.select(addr); ds.write(0xBE);
        for (uint8_t d {0}; d<9; d++) data[d] = ds.read();
        int16_t raw = (data[1] << 8) | data[0];
        raw = raw & ~1;
        temp[qty++] = raw / 16.0;
      }
      float tmp {0};
      for (uint8_t i {0}; i<qty; i++) tmp+= temp[i];
      *t = round(tmp/qty);
      Serial.print("Температура пин "); Serial.print(pin); Serial.print(" : "); Serial.println(*t);
    }

    void requestSensor(uint8_t pin){          // Отправка запроса на конвертацию ds18b20
      OneWire ds(pin);
      ds.reset();
      ds.skip();
      ds.write(0x44,0);
    }

    void searchSensors(){                          // Поиск датчиков на всех линиях
      ds1Qty =   src(ds1DS, ds1Pin);
    }

    uint8_t src(void * adr, uint8_t pin){      // Вспомогательная функция для поиска на одной шине. Возвращает количество найденных датчиков
      if (pin == 0) return 0;
      OneWire ds(pin);
      uint8_t newAddr[8]{0};
      uint8_t count {0};
      ds.reset_search();
      delay(5);
      while (ds.search(newAddr) && count <3){
        if (ds.crc8(newAddr, 7) == newAddr[7]){
           for (uint8_t i{0}; i<8; i++) *((uint8_t*)adr + count * 8 + i) = newAddr[i];
           count++;
        }
      }
      return count;
    }

title: Data output , ds18b20 , lcd1602 , yl-69, dht11

Answers: 0


body:
How come the following statement is true:
```cpp
int inputPin = A2;
```
I thought int variables can only hold integer numbers. Is the `A` just a representation of a number?

Thanks for any help

title: why can Arduino variables of int type contain a value such as A2

Answers: 2

body:
You are correct. `A2` is just a number (like everything in a microcontroller). We can look at the corresponding part in `pins_arduino.h` (a file defined in the variants folder of your used core and of your used board, for me: `~/arduino-1.8.9/hardware/arduino/avr/variants/standard/pins_arduino.h`):

    #define PIN_A0   (14)
    #define PIN_A1   (15)
    #define PIN_A2   (16)
    #define PIN_A3   (17)
    #define PIN_A4   (18)
    #define PIN_A5   (19)
    #define PIN_A6   (20)
    #define PIN_A7   (21)

    static const uint8_t A0 = PIN_A0;
    static const uint8_t A1 = PIN_A1;
    static const uint8_t A2 = PIN_A2;
    static const uint8_t A3 = PIN_A3;
    static const uint8_t A4 = PIN_A4;
    static const uint8_t A5 = PIN_A5;
    static const uint8_t A6 = PIN_A6;
    static const uint8_t A7 = PIN_A7;

So here the core first defines the macro `PIN_A2` as 16 (which is the pin number of that pin) and then it declares a static constant `A2` with `PIN_A2`. So `A2` is just the pin number of that pin, `16` in this case.

This is done to make the code more readable. The analog pins are marked with `A0` to `A7`, so it is good to also be able to refer to that with these names. If you wanted, you could also use the pin number directly. But that wouldn't be as easy to read.

body: The value of the symbol 'A2' *is* an integer - it is an Arduino pin number. For an Uno, it is equal to 16. Are you maybe confusing the pin number, A2, with the value read from A/D channel 2? That would be the value returned by `analogRead(A2)` or `analogRead(PIN_A2)` as it has been #define'd. And even then, that value is also an integer between 0 and 1023, which represents the voltage on the pin, 0 representing 0v or Ground, and 1024 representing the reference voltage (therefore, 1023 represents any voltage that is greater or equal to ((1023/1024) * Vref).


body:
If I can, which library to use (an example code will be great).
Here is the module:
[![PL2303 USB to TTL Serial Converter Module][1]][1]

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

title: Can i use PL2303 USB to TTL Serial Converter Module send keystrokes using Arduino nano?

Answers: 1

body:
No. That is serial. Just like every other USB to TTL Serial converter. The clue is in the name.

You need an Arduino with a dedicated native USB interface, like those based on the ATMega32U4 chip.

Or dedicated software on the PC that will read serial data and emulate keypresses (which is outside the scope of this website).


body:
I created a program that measures the pulses set out by the encoder (part of the dc motor with encoder inbuilt), and uses the ppr value (pulses per rotation) to calculate the rotations per minute (rpm)

However, the serial monitor continuously shows 0 for the variable "pulsecount", that maintains the total pulses sent.
[![enter image description here][1]][1]

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

code:

    float ppr=512.0;
    int encpin=3;
    volatile long pulsecount=0;
    float revs;
    float rps;
    float rpm;
    unsigned long time;

    void setup()
    {
      pinMode(encpin,INPUT);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(encpin),function,RISING); //when pulse is detected
                                               //interrupt triggered,
                                               //function callled
    }
    void function(){
      pulsecount+=1;
    }

    void loop()
    {
     revs= pulsecount/ppr ;
     time=millis()/1000;
     rps=revs/time ;
     rpm=revs*60;
     Serial.println(pulsecount);
    }

title: Basic doubt regarding encoders with Arduino

Answers: 2

body:
You code counts pulses just fine when tested here.

Fan/motor tachometer outputs and encoders frequently are set to switch your signal contact to ground, either with a transistor or mechanically.  When the ground contact is not being made, the signal connection is floating and not reliably HIGH.  So, you need a pullup resistor on the pin, just like you do for a typical push button switch configured to switch to ground.

My comment on the question:

> What happens if you use `INPUT_PULLUP` rather than `INPUT`?

was referring to doing this in your code:

```c++
pinMode(encpin, INPUT_PULLUP);
```

At higher frequencies, higher RPM, you may need to use an external resistor to get a lower resistance value than the 20k-50k of the internal pullup resistor that `INPUT_PULLUP` enables.

It is best to turn off interrupts when you retrieve your `volatile` pulse counter variable so that there's no tearing of the value where the ISR interrupts your code mid-read and updates the latter half of the value.

e.g.:

```c++
// Note I've switched your pulsecount variable
//  to unsigned long for this example.
unsigned long get_pulsecount() {
  noInterrupts();
  const auto r = pulsecount;
  interrupts();
  return r;
}
```

Note you can probably avoid `float` usage altogether, and should if you can.

body:
It is hard to find the error in these TinkerCad examples, because I do not know where to find the datasheet of the components used there and I am never sure, what am I debugging, the program or Tinkercad?

Anyhow, the encoder simulated there needs to be connected with a pull-up resistor. Arduino has a built-in pullup and you can activate via the `pinmode()` function:

```
void setup()
{
  pinMode(encpin,INPUT_PULLUP); //  before here was pinMode(encpin,INPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING); //when pulse is detected
                                           //interrupt triggered,
                                           //function callled
}
```

But notice: your types are all over the place and I expect that you get some bugs due to this. Avoid to divide float and int variables without converting, especially this can cause trouble, because you might divide by 0:

```
 time=millis()/1000;
 rps=revs/time ;
```
Also it is a long shot to have basic doubts regarding encoders and arduino, just because some code does not work. Many people are using encoders all the time and countless libraries of encoders have been published for arduino.