text:
Using Parallax VPN1513 GPS Smart Module with External Antenna and Ruggeduino
I am using a Ruggeduino for a project involving an autonomous vehicle, and I need GPS capability in it. I am using the "VPN1513 GPS Smart Module with External Antenna" from Parallax (https://www.parallax.com/product/28510), and the TinyGPS Library (http://arduiniana.org/libraries/tinygps/). I have it supplied with 5v, grounded, and with the SIG and EN wires going to ports 0 and 1 on the Ruggeduino. Everything that I have done so far has resulted in this example program from the library returning "****", which means it is getting invalid data. Does anyone know what I'm doing wrong? Thank's for the help in advance.
Here's the program:

#include <SoftwareSerial.h>
#include <TinyGPS.h>

TinyGPS gps;
SoftwareSerial nss(1, 0);

static void gpsdump(TinyGPS &gps);
static bool feedgps();
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

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

  Serial.print("Testing TinyGPS library v. ");
  Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
  Serial.println("Sats HDOP Latitude Longitude Fix  Date       Time       Date Alt     Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)    (deg)     Age                        Age  (m)     --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("--------------------------------------------------------------------------------------------------------------------------------------");
}

void loop()
{
  bool newdata = false;
  unsigned long start = millis();

  // Every second we print an update
  while (millis() - start < 1000)
  {
    if (feedgps())
      newdata = true;
  }

  gpsdump(gps);
}

static void gpsdump(TinyGPS &gps)
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 9, 5);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 10, 5);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);

  print_date(gps);

  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 8, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0UL : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : TinyGPS::course_to(flat, flon, 51.508131, -0.128002), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  Serial.println();
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  feedgps();
}

static void print_float(float val, float invalid, int len, int prec)
{
  char sz[32];
  if (val == invalid)
  {
    strcpy(sz, "*******");
    sz[len] = 0;
    if (len > 0)
      sz[len-1] = ' ';
    for (int i=7; i<len; ++i)
      sz[i] = ' ';
    Serial.print(sz);
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1);
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(" ");
  }
  feedgps();
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("*******    *******    ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d   ",
    month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  feedgps();
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  feedgps();
}

static bool feedgps()
{
  while (nss.available())
  {
    if (gps.encode(nss.read()))
      return true;
  }
  return false;
}


text:
Using MOSI and MISO pins for multiple devices
For the device I am creating, I am hooking up an apa102 led strip to pins 11 and 13 to control each LED. But I would also like to hookup my NRF receiver to the arduino, but I also use pins 11 and 13. My question is can i hookup both to the same pins and control the inputs and outputs through the MOSI amd MISO pins separately!

Read about SPI. You can connect all devices to SCK, MISO, MOSI bus and address individual devices via CS(or SS).

@OlegMazurov the APA102 however doesn't have a CS pin, so it can't share a SPI bus. You can implement SPI in software (i.e. bitbang SPI).

@Gerben but you can disable the clock signal to the strip with a transistor or buffer, and it doesn't use the MISO at all so that's not an issue.

source: Stack Exchange

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

sort: votes


text:
Spinning ESC Brushless Motor Slower
I am controlling a g-series 1000kv brushless motor with my arduino. Currently I have my setup as follows:

Now I used the code given to me in a tutorial which is also as seen below:
#include <Servo.h>
Servo ESC;     // create servo object to control the ESC
int potValue;  // value from the analog pin
void setup() {
  // Attach the ESC on pin 9
  ESC.attach(9,1000,2000); // (pin, min pulse width, max pulse width in
microseconds)
}
void loop() {
  potValue = analogRead(A0);   // reads the value of the potentiometer (value between 0 and 1023)
  potValue = map(potValue, 0, 1023, 0, 180);   // scale it to use it with the servo library (value between 0 and 180)
  ESC.write(potValue);    // Send the signal to the ESC
}

at any voltage (tested between 7.4v and 12v) i was not able to change the spin speed despite my knowledge being voltage x 1000 is the rpms. I want to run a piece of code that will spin the motor slowly but no solution is working.

So, does your motor spin at all? Did you carry out ESC's arming sequence? Also, are you powering your Arduino from the BEC built into the ESC?

Arduino is powered from the BEC but sometimes from computer so it is a little of both. And yes I carried out the arming sequence

And the motor does spin just starts off really fast

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


text:
I just downloaded the Arduino IDE and it doesn't compile any code
FQBN: arduino:avr:uno
Using board 'uno' from platform in folder: C:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6
Using core 'arduino' from platform in folder: C:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6

Detecting libraries used...
C:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7/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=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\cores\arduino -IC:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\variants\standard C:\Users\Kareem\AppData\Local\Temp\arduino\sketches\249E86D7CFF632627E003BB52C94264B\sketch\Blink.ino.cpp -o nul
Generating function prototypes...
C:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7/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=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\cores\arduino -IC:\Users\Kareem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\variants\standard C:\Users\Kareem\AppData\Local\Temp\arduino\sketches\249E86D7CFF632627E003BB52C94264B\sketch\Blink.ino.cpp -o C:\Users\Kareem\AppData\Local\Temp\43183129\sketch_merged.cpp
C:\Users\Kareem\AppData\Local\Arduino15\packages\builtin\tools\ctags\5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives C:\Users\Kareem\AppData\Local\Temp\43183129\sketch_merged.cpp
Compiling sketch...
"C:\\Users\\Kareem\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/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=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Users\\Kareem\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.6\\cores\\arduino" "-IC:\\Users\\Kareem\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.6\\variants\\standard" "C:\\Users\\Kareem\\AppData\\Local\\Temp\\arduino\\sketches\\249E86D7CFF632627E003BB52C94264B\\sketch\\Blink.ino.cpp" -o "C:\\Users\\Kareem\\AppData\\Local\\Temp\\arduino\\sketches\\249E86D7CFF632627E003BB52C94264B\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\Kareem\AppData\Local\Temp\arduino\cores\arduino_avr_uno_06fe87695d748aefc72866d7f296b9a5\core.a
Linking everything together...
"C:\\Users\\Kareem\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\Kareem\\AppData\\Local\\Temp\\arduino\\sketches\\249E86D7CFF632627E003BB52C94264B/Blink.ino.elf" "C:\\Users\\Kareem\\AppData\\Local\\Temp\\arduino\\sketches\\249E86D7CFF632627E003BB52C94264B\\sketch\\Blink.ino.cpp.o" "C:\\Users\\Kareem\\AppData\\Local\\Temp\\arduino\\sketches\\249E86D7CFF632627E003BB52C94264B/..\\..\\cores\\arduino_avr_uno_06fe87695d748aefc72866d7f296b9a5\\core.a" "-LC:\\Users\\Kareem\\AppData\\Local\\Temp\\arduino\\sketches\\249E86D7CFF632627E003BB52C94264B" -lm
c:/users/kareem/appdata/local/arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/../lib/gcc/avr/7.3.0/../../../../avr/lib/avr5/crtatmega328p.o:(.init9+0x0): undefined reference to `main'
collect2.exe: error: ld returned 1 exit status

exit status 1

Compilation error: exit status 1

Looks like precompiled core doesn't contain main or something...

delete C:\Users\Kareem\AppData\Local\Temp\arduino\cores\arduino_avr_uno_06fe87695d748aefc72866d7f296b9a5\core.a and try again

@hcheung .cpp.ino is created by the Arduino builder

I have same problem. I can find "main.cpp.o" in core.a. it's confused


text:
Problem with char* variable malloc/free. Empty contents on recipient variable after using free
I am working on a custom SD card data logger using the following function and struct:
char *filenameCreator(const char *prefix, const char *num, bool addExtension)
{
    char *filename = (char *)malloc(13 * sizeof(char));
    const char *uScore = "_";
    strcpy(filename, prefix);
    strcat(filename, uScore);
    strcat(filename, num);
    if (addExtension)
    {
        const char *ext = LOGFILE_EXTENSION;
        strcat(filename, ext);
    }
    delete[] num;
    return filename;
}

where the output will be saved on a variable of the following type:
struct FileInfo
{
    const char *fileName;
    double fileSize;
};

with FileInfo fileToDelete;
and a global variable
char* createdFilename = nullptr; to temporarily store the function's output.
The issue is that when using the functions as follows, fileToDelete.fileName is EMPTY:
createdFilename= filenameCreator("FILE", numericConverter(receivedIndexSATCOM), true);
fileToDelete.fileName = createdFilename;

free(createdFilename);    // seems to clear the contents of the variable where the filename was stored, namely, fileToDelete.fileName
createdFilename = nullptr;

I am trying to stick to the rules of freeing up memory used by malloc'd variables.
Please note that if I DON'T USE free(createdFilename), the code works fine and the fileName is created correctly. However, I am concerned about undefined behaviour or erratic responses.
Here is an example of a filename successfully created when NOT using free():

Do I invariably need to free the pointer after each use? Why the contents are empty even after assigning the contents to another variable?
EDIT:
Please, instead of downvoting my question, comment on what is wrong with my questions and I will try to improve it. Be mature.

See the accepted answer here.  https://stackoverflow.com/questions/37514873/clarify-dangling-pointer-in-c-c

dont't use dynamic memory allocation. pass a buffer on stack to the function

You might want to read about the reasons to vote down. In your case your question shows no effort of research on your issue, neither in the web nor on this site. However, you are supposed to do this before asking. (Disclaimer: I did not vote down.)

@Juraj As a general advice, I don't agree. There are good reasons for dynamic memory allocation, even on an Arduino. It depends on the software design.

@thebusybee. I meant for the filename here. no good reason here

@thebusybee with all due respect, how can you or anyone else for that matter tell for sure that "I am not showing effort". Posting at nearly 2:30 am UK time after coding for 8 consecutive hours is mentally draining. How can I "show effort" without bloating my post? Thanks in any case

We just looked at your question, that's it. We cannot see what you do else, and so it does not matter to us. Your post does not show any reference how you tried to solve your issue yourself and why you failed. If you think this bloats your question, well, it helps. Otherwise you'll receive irrelevant or misleading answers, which waste more of your and our time.

What you have is called a "Dangling Pointer".  You are trying to use a pointer that is pointing to memory that has been freed and doesn't contain what you think it does anymore.
This line of code in the filenameCreator function:
char *filename = (char *)malloc(13 * sizeof(char));
allocates a block of memory in the heap and saves a pointer to it.  Later in the function you return that pointer.
return filename;
When you call this function:
createdFilename= filenameCreator("FILE", numericConverter(receivedIndexSATCOM), true);
You assign that pointer value to a new pointer.  Now createdFilename points to this block of memory that you allocated in the function.
When you get to this line:
free(createdFilename);
That frees the block of memory that is being pointed to.  This means that its contents can be destroyed, or left there, or used for something else.  You've said with this line of code that you won't use it anymore.
If you try to use createdFilename later, it will still point to the same place in memory.  But the stuff you had stored there has been freed.  It is no longer there.
If it is your intention to keep using that file name, then don't free the memory until you are done using it.  Sometimes that means the life of the program and you never call free.
It is important to free memory that you allocated, but only when you are done using it.

Thank you for your detailed and professional response. It makes absolute sense to me now. This "issue" is part of a massive project that has been mentally draining me and I am not thinking clearly. As it seems, not freeing up the pointer shouldn't be a problem then.

@DanielMelendrez If you are allocating pointer, you have to free it when it's no longer needed. Problem in your code isn't not freeing it as it's been already freed and pointer in fileToDelete.fileName is invalid


text:
Blinking LEDs in sequence with a class
I am trying to make a program that accepts four digit password using a 3*4 keypad.
The program should start with flashing LED1 and when password 1 is entered it switches this LED and blinks LED2. If password 2 is entered it switches to LED3 and so on.
Here is the code:
#include <Keypad.h>
#include <TimedBlink.h>

#define Password_Length 5

TimedBlink led1(14);
TimedBlink led2(15);
TimedBlink led3(16);
TimedBlink led4(17);

const unsigned long PERIOD1 = 1000;
char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

byte data_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  led1.blink(150, 50); // On for 150ms, off for 50ms
  led2.blink(150, 50);
  led3.blink(150, 50); // On for 150ms, off for 50ms
  led4.blink(150, 50);
  Serial.begin(9600);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  led1.blink();
  led2.blink();
  led3.blink();
  led4.blink();
  customKey = customKeypad.getKey();
  if (customKey) {
  // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) { //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) { //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          led1.blinkOff();
          break;
        case 1:
          led2.blinkOff();
          break;
        case 2:
          led3.blinkOff();
          break;
        case 3:
          led4.blinkOff();
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

void BlinkLed (int led, int interval, int arry) {
  //(long) can be omitted if you dont plan to blink led for very long time I think
  if (((long)millis() - previousMillis[arry]) >= interval) {
    previousMillis[arry] = millis(); //stores the millis value in the selected array
    digitalWrite(led, !digitalRead(led)); //changes led state
  }
}

Now I can make the program, but all LEDs start blinking and switch off after the password is entered and I got stuck at this point.
Here is a link to the TimedBlink Library.
I have tried the millis() function to be used to blink LEDs in the next code:
#include <Keypad.h>
#include <Wire.h>

#define buzzer 13
#define greenled 20
#define redled 21
#define Password_Length 5

unsigned long previousMillisLED14 = 0;
unsigned long previousMillisLED15 = 0;
unsigned long previousMillisLED16 = 0;
unsigned long previousMillisLED17 = 0;
// different intervals for each LED
int intervalLED14 = 500;
int intervalLED15 = 600;
int intervalLED16 = 700;
int intervalLED17 = 800;
// each LED gets a state varaible
boolean LED14state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED15state = false;     // need to seed the light to be OFF
boolean LED16state = false;     // need to seed the light to be OFF
boolean LED17state = false;     // need to seed the light to be OFF
const unsigned long PERIOD1 = 1000;
char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
byte i, x, y;
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7
byte data_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  unsigned long currentMillis = millis();
  if ((unsigned long)(currentMillis - previousMillisLED14) >= intervalLED14) {
    LED14state = !LED14state;
    digitalWrite(14, LED14state);
    // save current time to pin 12's previousMillis
    previousMillisLED14 = currentMillis;
  }
  customKey = customKeypad.getKey();
  if (customKey) {
    // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) {
      //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) {
        //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED15) >= intervalLED15) {
            LED15state = !LED15state;
            digitalWrite(15, LED15state);
            // save current time to pin 12's previousMillis
            previousMillisLED15 = currentMillis;
          }
          break;
        case 1:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(17, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED16) >= intervalLED16) {
            LED16state = !LED16state;
            digitalWrite(16, LED15state);
            // save current time to pin 12's previousMillis
            previousMillisLED16 = currentMillis;
          }
          break;
        case 2:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED17) >= intervalLED17) {
            LED17state = !LED17state;
            digitalWrite(17, LED17state);
            // save current time to pin 12's previousMillis
            previousMillisLED17 = currentMillis;
          }
          break;
        case 3:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

But it blinks the first LED only, then each of the following LEDs according to the condition got permanent on.
I have tried the solution that Adafruit suggested, to use a class in code but unfortunately I got the same result as the previous code.
Here is the code:
#include <Keypad.h>
#include <Wire.h>

class Flasher {
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time
    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    // Constructor - creates a Flasher
    // and initializes the member variables and state
  public:
    Flasher(int pin, long on, long off) {
      ledPin = pin;
      pinMode(ledPin, OUTPUT);
      OnTime = on;
      OffTime = off;
      ledState = LOW;
      previousMillis = 0;
    }
    void Update() {
      // check to see if it's time to change the state of the LED
      unsigned long currentMillis = millis();
      if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime)) {
        ledState = LOW;  // Turn it off
        previousMillis = currentMillis;  // Remember the time
        digitalWrite(ledPin, ledState);  // Update the actual LED
      } else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime)) {
        ledState = HIGH;  // turn it on
        previousMillis = currentMillis;   // Remember the time
        digitalWrite(ledPin, ledState);   // Update the actual LED
      }
    }
};

Flasher led1(14, 100, 400);
Flasher led2(15, 350, 350);
Flasher led3(16, 100, 400);
Flasher led4(17, 350, 350);

#define buzzer 13
#define greenled 20
#define redled 21
#define Password_Length 5

char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
byte i, x, y;
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

byte data_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  led1.Update();
  customKey = customKeypad.getKey();
  if (customKey) {
    // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) {
      //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) {
        //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          led2.Update();
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
        case 1:
          led3.Update();
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(17, LOW);
          break;
        case 2:
          led4.Update();
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          break;
        case 3:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

Any idea why is this happening?

why don't you try to determine  why all the LEDs start flashing when the program starts

actually ia m trying to get help cz totally stuck after this step

look at the first command in the loop() block .....  think about its function

dear i understand what u r meaning,but when i tried to put led.blink function in the switch cases i did not get any reults ,though they r supposed to work there

Put a link to the TimedBlink library you are using In your question, not in a reply to an answer. You need to provide enough information for the people reading your question to be able to understand your problem.

EDIT
Now that you added a link to the TimedBlink library I was able to go look at it. That is not a very well written library, and its documentation is horrible.
It seems that blink(int,int) starts a TimedBlink LED blinking, and blinkOff stops it. So you should not call LEDx.blink(150,50) on any of your LEDs until you want them to start blinking.
You need to refactor your code to only call LEDx.blink(150,50) on one LED at a time. You probably want your switch statement to call LEDx.blink(150,50) on the LED that you want to blink and ledOff() on the others.

thank u 4 ur reply,
this is the link for the timed blink
link,
i have tried the suggested way in  ur answer but it did not work ,the leds remain off

See the edit to my answer. You need to edit your question and provide the link to the library in the question, not buried in a comment to my answer. Other people reading this thread will want the same information and they should not have to hunt for it. When you are getting ready to post a question, stop and think: “What information will the readers of my question need in order to understand my question? Have I provided everything?”

i have tried that but unfortunately no result


text:
Change format preferences for Arduino IDE in Linux
How can I change Arduino IDE preferences for formatting? I found the preferences file: <user>/.arduino15/preferences.txt, but there are no lines that control IDE formatting. In Windows there is a special file for formatting: <ArduinoIDE_folder>/lib/formatter.conf.

same place <ArduinoIDE_folder>/lib/formatter.conf

@Juraj , as <ArduinoIDE_folder> do u mean <user>/.arduino15?

no, .arduino15 is on Windows C:\Users\User\AppData\Local\Arduino15. I installed Arduino IDE on linux into /home/user/arduino-1.8.5

I have my custom formatter.conf in /home//.arduino15

It happened, that my formatter.conf was in /usr/share/arduino/lib/. So I copied it to /home/<user>/.arduino15/ folder and made changes that I needed. And also:

Copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE.

That is correct.  However, when upgrading, I often the remove the .arduino15 folder as well to make a fresh start. Recently I had to remove the .arduino15 folder without upgrading to a new version. The arduino ide was sometimes slow and had troubles when installing new libraries.

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


text:
Building a VU meter
I am building a VU meter with two 5v neopixel rings, two potentiometers, a headphone jack and an Arduino nano. Will 5 volts 1 amp cut it, or do I need more power? FYI I'll be powering it via a DC jack once I get it working.

How many LEDs are in each of the Neopixel rings?

It should be enough if you avoid white and use single-color zoned metering.

they each have 24 led's on each ring and what is single-color zoned metering?

Normally the maximum amount of current a typical LED can withstand is 20 mA. This means per color and per LED.
So if you have 60 LEDs, than you get 60 (leds) * 3 (R/G/B colors) * 20 mA = 3,600 mA.
To give some headroom I would use a 4A or 5A adapter.
However, note that probably 5 mA or 10 mA per LED would be enough to be very good visible, unless you want it to be as bright as possible.

4A or 5A at 5V?

4A will give 10% 'headroom', 5A even more. In electronics it is better to be safe, probably 4A will be ok, if you want to be sure/safer, use 5A. You could do some tests when switching all LEDs on, under different temperatures, and find out the worst case. If you don't want to do such testing, use 5A.

so i would need 5A if i want to power the nano off of the same supply?

@taran i don't know how much the nano used, but i think it's not much... Add it up to the LEDs per usage and use some headroom.

total A with per io pin 3,640 so i would need a 5v 4a power supply, correct?

yes, but if you want to be sure, use an oscilloscope or multimeter and round up.


text:
ESP8266 seems to be bricked , how to recover?
In a part of my sketch I put by mistake
pinMode(7,INPUT_PULLUP);
Which is dedicated pin for external flash chip (gpio7/SDIO_DATA_0/SPI_MISO) that not supposed to use for sketch. after uploading sketch now ESP is not responding to any further programming.
Could be Flash chip got corrupted due to the above mistakes?. Is it possible to recover?
I already bricked two of my modules with same sketch before identifying above mistake.
Sketch where working normal on Modules without above code.
When I connect to module with baud-rate 74880 chip returns

ets Jan  8 2013,rst cause:2, boot mode:(3,7)

Please check what happens when I try to upload the code upload error

No, you have not bricked your ESP8266 by turning on GPIO7's pullup.  All that will do is provide a weak pullup on the MISO line of the flash chip, which itself will have no effect - the flash chip's SPI Data Out pin will be able to easily override that weak pullup.
You can remove the flash chip and replace it with a completely blank brand new flash chip with nothing on it and still upload new code. There is nothing in the flash chip that the ESP8266 relies on to operate.
The boot sequence of the ESP8266 is as follows:
- Start executing the bootloader from the built-in ROM
  - Read the GPIO pins to determine code execution source
  - If flash is selected then initialize flash chip and read from address 0
    - Code on flash examines partition table to find code entry point
    - Jump to code entry point
  - If UART is selected then initialize UART
    - Wait for commands over the UART and respond accordingly

The startup code (boot stage 0) is in ROM. It's impossible to "brick" that.  All that is in the flash is the code that tells the ESP8266 how to find the user's code, and that gets flashed to the chip every time you reprogram it.
You can think of it like BIOS boot on a PC.  In the ROM is the BIOS that tells the CPU how to read from the hard drive. Then at the start of the hard drive is the code that tells the CPU how to load the operating system.  The hard drive doesn't come with that code on it - you install that along with the operating system. But the motherboard has the BIOS built into ROM which tells it how to get going and read that boot sector.
However it is possible to destroy an ESP8266 by connecting the wrong things up to it in the wrong way.  It is also possible to destroy some USB chips (the CH340G in particular) by wiring things up wrong.
So chances are that if you have bricked your ESP8266 it has nothing to do with your program and everything to do with what you have wired to it.

@sim son and Majenko Thanks for your efforts to address my issue. Now it is clear for me that unless I damage the chip itself it will be recoverable even some thing goes wrong and corrupted the flash.
Yesterday night as a further attempt I restarted my PC hoping that the serial driver or hardware did something faulty, now I'm able to flash my modules again !!. I'm still puzzled and looking into what did the problem actually.

No, your sketch can not brick the device in that way. It's the bootloader that decides after a reset/power-up whether the esp has to accept a firmware (flash button is pressed) or has to run the uploaded sketch. At that point, nothing of your sketch has yet been executed and gpios have their default configuration, which is input anyway.
Also, when a pullup is in charge, one can still apply a logic level to the respective pin. The gpio then won't see any effect from the pullup.

On your first paragraph it is clear that bootloader will decide about pin status during process of sketch upload. But what happens once it has been downloaded and the sketch executed which in turn manipulates the flash memory control gpio and corrupts the bootloader on flash memory like some memory area written with '1' (eg: 1111 1111).
I have no other clue since I bricked my second Lolin board also with the same sketch before identifying the above mistake (gpio7 as input)

@saif The bootloader is in ROM, not flash. You cannot corrupt it. It is that ROM bootloader that looks at the IO pins and decides where to "boot" from (one option of which is "Through the UART for programming").  It is possible to remove the flash chip and replace it with a brand new completely blank one and still program it. There must be something else fundamentally wrong with what you are doing.


text:
Arduino Obstacle Avoiding Shield controlor motor L293D
I am a beginner with Arduino. I wanted to make an Arduino obstacle avoiding. So I ordered last week an L293D Shield Motor Driver and I don't know if what I receive is a good item. The first picture is how it looks on the site and the second picture is what I got.

I saw that if you search for this motor you get results for both motors, but they are not the same. And I saw in this tutorial, this person using a motor like mine https://www.youtube.com/watch?v=ydDvoknlJ9M and then he switched to the motor in the first picture.
Questions: Are these motors the same? Should I request a return? If they are the same, how can I add the pins (as shown in the third picture?

Again, I am a beginner and I would appreciate if someone can help me.

Looks exactly the same, except for that some pin headers are missing. You could buy and solder them yourself.

Thank you so much ! I find this pins from a old kit that I commanded , but they didn't mentioned that it comes without and in the image pins appear .

do you actually need those pins?

Yes , I want to make a obstacle avoiding robot and I saw that more people use them

To complete @chrisl answer: Yes you need these pins to make the same robot as in the video. You can order them online and solder them (if you know how to solder and if you have the soldering material). Be careful with soldering ;)
For your information, the pins you circled in red are used to communicate with the Arduino pins A0 to A5, and provide +5V and GND. In the video, they are connected to the ultrasound sensor.
And please clarify what is your motor??? Do you mean the Shield motor driver? It is not the same. A shield is an eletronic board that you plug to your Arduino to do a specific task (control a motor, connect to wifi...). A motor driver is the electronic to control the motor. On your pictures, they are mainly the 3 components with 16 legs each.

Thanks ! It's a shield motor driver

@AnaNiorba - if this worked for you then you should tick it to indicate that it was the correct answer.


text:
How to extract fingerprint template from Arduino Fingerprint Sensor
How to extract fingerprint template from Arduino Fingerprint Sensor and store it to SD card module using adafruit library and then search/import it from SD card module when tapping the fingerprint?
Can anyone give me hope to this project I am starting to feel stressed and depressed.
I'm using Arduino R307 and AS601 fingerprint modules.
here is the code:
    #include <SPI.h>
    #include <SD.h>
    #include <SoftwareSerial.h>
    #include <Adafruit_Fingerprint.h>

    SoftwareSerial mySerial(2, 3);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    uint8_t id;
    String userName;
    uint8_t isProfessor;
    char *myFileName = "acct.txt";
    File myFile;

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

      Serial.print("Initializing SD card...");
      if (!SD.begin(4)) {
        Serial.print("initialization failed!");
        while (1);
      }
      Serial.print("initialization done.");

      // set the data rate for the sensor serial port
      finger.begin(57600);

      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) {
          delay(1);
        }
      }
    }

    uint8_t readnumber(void) {
      uint8_t num = 0;

      while (num == 0) {
        while (! Serial.available());
        num = Serial.parseInt();
      }
      return num;
    }

    void loop()                     // run over and over again
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
      id = readnumber();
      if (id == 0) {// ID #0 not allowed, try again!
        return;
      }
      Serial.print("Enrolling ID #");
      Serial.println(id);

      while (!getFingerprintEnroll() );
    }

    void writeReadSDCard(){

        delay(2000);
        // open the file. note that only one file can be open at a time,
        // so you have to close this one before opening another.
        myFile = SD.open(myFileName, FILE_WRITE);
        // if the file opened okay, write to it:
        if (myFile) { //if myFile is open, you can write
          Serial.print("Writing to "); Serial.println(myFileName);
          //myFile.print(id); myFile.print(","); myFile.print(userName); myFile.print(","); myFile.println("Professor");
          myFile.print(id); myFile.print(","); myFile.println(userName);
          // close the file:
          myFile.close();
          Serial.println("done.");
        } else {
          // if the file didn't open, print an error:
          Serial.print("error opening when writing on "); Serial.println(myFileName);
        }

        delay(2000);

        // re-open the file for reading:
        myFile = SD.open(myFileName);
        if (myFile) {
          Serial.print("Reading SD Card file named "); Serial.println(myFileName);

          // read from the file until there's nothing else in it:
          while (myFile.available()) {
            Serial.write(myFile.read());
          }
          // close the file:
          myFile.close();
          Serial.flush(); // wait for last transmitted data to be sent

        } else {
          // if the file didn't open, print an error:
          Serial.println("error opening for reading");   Serial.print(myFileName);
        }
    }

    uint8_t getFingerprintEnroll() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
          case FINGERPRINT_OK:
            Serial.println("Image taken");
            break;
          case FINGERPRINT_NOFINGER:
            Serial.println(".");
            break;
          case FINGERPRINT_PACKETRECIEVEERR:
            Serial.println("Communication error");
            break;
          case FINGERPRINT_IMAGEFAIL:
            Serial.println("Imaging error");
            break;
          default:
            Serial.println("Unknown error");
            break;
        }
      }

      // OK success!

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

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
          case FINGERPRINT_OK:
            Serial.println("Image taken");
            break;
          case FINGERPRINT_NOFINGER:
            Serial.print(".");
            break;
          case FINGERPRINT_PACKETRECIEVEERR:
            Serial.println("Communication error");
            break;
          case FINGERPRINT_IMAGEFAIL:
            Serial.println("Imaging error");
            break;
          default:
            Serial.println("Unknown error");
            break;
        }
      }

      // OK success!

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

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");

        delay(10000);

          userName = Serial.readString();// read the incoming data as string
          Serial.println(userName);

          writeReadSDCard();

      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }

Here is the result:

I hope someone can answer my question.

Directly related to this question

I don't think, that the library allows you to extract the template or model of a fingerprint. I even haven't seen such a function in the manual of the Adafruit Sensor. Only functions for getting the read image. So I guess you technically cannot get the template

what should I do?

What I wrote in my answer to your other question. Yes, that is no easy solution, but when you cannot find a library, that already implements the needed feature, you need to write that yourself. Or you need to rethink your project, so that you don't need this feature.


text:
SCLK pulses not seen when using SPI on ESP32
I am using the following code in my esp32 using Arduino IDE for spi communication which is an example code -
    #include <SPI.h>

    static const int spiClk = 1000000; // 1 MHz

    //uninitalised pointers to SPI objects
    SPIClass * vspi = NULL;
    SPIClass * hspi = NULL;

    void setup() {
      //initialise two instances of the SPIClass attached to VSPI and HSPI respectively
      vspi = new SPIClass(VSPI);
      hspi = new SPIClass(HSPI);

      //clock miso mosi ss

      //initialise vspi with default pins
      //SCLK = 18, MISO = 19, MOSI = 23, SS = 5
      vspi->begin();
      //alternatively route through GPIO pins of your choice
      //hspi->begin(0, 2, 4, 33); //SCLK, MISO, MOSI, SS

      //initialise hspi with default pins
      //SCLK = 14, MISO = 12, MOSI = 13, SS = 15
      hspi->begin();
      //alternatively route through GPIO pins
      //hspi->begin(25, 26, 27, 32); //SCLK, MISO, MOSI, SS

      //set up slave select pins as outputs as the Arduino API
      //doesn't handle automatically pulling SS low
      pinMode(5, OUTPUT); //VSPI SS
      pinMode(15, OUTPUT); //HSPI SS

    }

    // the loop function runs over and over again until power down or reset
    void loop() {
      //use the SPI buses
      vspiCommand();
      hspiCommand();
      delay(100);
    }

    void vspiCommand() {
      byte data = 0b01010101; // junk data to illustrate usage

      //use it as you would the regular arduino SPI API
      vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(5, LOW); //pull SS slow to prep other end for transfer
      vspi->transfer(data);
      delay(500);
      digitalWrite(5, HIGH); //pull ss high to signify end of data transfer
      vspi->endTransaction();
    }

    void hspiCommand() {
      byte stuff = 0b11001100;

      hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(15, LOW);
      hspi->transfer(stuff);
      delay(500);
      digitalWrite(15, HIGH);
      hspi->endTransaction();
    }

I am able to see the toggling of the SS pin, but the SCLK pin does not show any pulses on the oscilloscope. It is a constant low. Should the pulses be given from an external source? If so, what is the purpose of this line - static const int spiClk = 1000000; // 1 MHz?

What device are you using? Some board vendors print the GPIOnum (which is different from the pin num) to the silk screen, some times a vendor uses a different layout than the reference design so you have to look up in the circuit diagram (if you get/have it) - I know the "search" for the SCLK pin and other mappings ;-)

I'm using esp32 wroom. Yes, I know that gpio 5  (pin 29)is chip shredder, gpio 18(pin 30) is clock pulses etc using vspi.i am getting those toggling pulses on gpio5 but am not able to see any transfer of data. I.e clock pulses on gpio18 or pin 30

Try to set the pins explicitly to Output
EDITDifferent issues with the test programs indicate that acc. to espressif the pin has to explicitly set to high which is not done by the libs begin method (as of core 1.04)
  digitalWrite(30, HIGH); // turn on pullup resistors
  digitalWrite(xxx, HIGH); // turn on pullup resistors
  pinMode(30, OUTPUT); //VSPI SLCK
  pinMode(XX, OUTPUT); //HSPI SCLK

The ESP32 docs say:

gpio18 will output low level(because gpio18 is input mode by default).
  If you don’t want this behavior, you should configure gpio18 as output
  mode and set it to hight level before calling

As this is not the issue - the Wroom32 modules v1-3 have a problem with SPI when flashed in certain modes with 80Mhz So try flashing with 40Mhz. I check for my test program in the meantime.
So here is a working test routine:
/* SPI Test routine for Wroom32
Connect the MISO with  the MOSI pin*/
#include<SPI.h>       //Library for SPI

#define SPI_SCK 18 // Serial Clock (Master Output)
#define SPI_MOSI 23 // Master Output,Slave Input
#define SPI_MISO 19 // Master Input, Slave Output
#define SPI_CS 5 // Chip Select, Slave Transmit Enable (active low, Master Output)
#define SS 5

char returnStr[40] = {'\0'};
char returnChr;

void setup () {
  Serial.begin(115200); // Set baud rate to 115200 for usart
  pinMode(SPI_CS, OUTPUT);
  pinMode(SPI_SCK, OUTPUT);
  pinMode(SPI_MOSI, OUTPUT);
  pinMode(SPI_MISO, INPUT);

  digitalWrite(SS, HIGH); // disable Slave Select
  SPI.begin (SPI_SCK, SPI_MISO, SPI_MOSI);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV8); // divide the clock by 8=2 MHz @ESP32
}

void loop () {
  char c;
  digitalWrite(SS, LOW); // enable Slave Select
  /* Send test string in a loop */
  for (const char *p = "SPI TEST! We are online over SPI\n\r" ; (c = *p); p++)  {
    returnChr = SPI.transfer (c);
    Serial.print(c);
    Serial.print(returnChr); // MOSI MISO Link sends echo back
  }
  digitalWrite(SS, HIGH); // disable Slave Select
  delay(500);
}

To measure the signals you have to trigger to the falling edge of SS/CS and set the resolution to 2µs per grid field (round about). I tested on an AIThinker module (ESP32) and everything worked with that sketch.

tried the same, but it did not work. I even changed the syntax to pinMode(18, OUTPUT) as pin 30 gpio 18. If you do have an ESP32, can you try it too?

thanks - ive tried changing clock speeds too with no luck. Were you able to  try it?


text:
How to handle class initialization when using brace-enclosed initializer lists
I'm working with a custom C++ library, CPSTL, for Arduino, which includes a cpstd::vector class that is designed to work with cpstd::initializer_list, cpstd::initializer_list is supposed to mimic std::initializer_list.
However, I'm having trouble initializing a cpstd::vector using brace-enclosed initializer lists.
I've looked up many sources online, and it seems there is not a lot of information in the topic, but came up to things such as FastArduino: initializer list, and Arduino STL: Initializer list. Giving me hopes that it is actually possible. (I can't use those libraries, because they lack the build system generation tools on the library I am developing, they also lack on customizability, and also as a good learning experience)
I've tried various approaches, but I keep getting the error:

could not convert '{0, 1, 2, 3, 4}' from 'brace-enclosed initializer list' to 'cpstd::vector'.

Here's an example of the code that's causing the issue:
    cpstd::vector<unsigned char> myVector = {0, 1, 2, 3, 4};

I have already implemented a custom cpstd::initializer_list and constructor that should handle this, but the issue persists. Is there something specific to the Arduino environment that could be causing this issue?
Additional Information:

I have verified that the cpstd::initializer_list is correctly defined and included in my code.

The cpstd::vector class is included and accessible.

I have reviewed my cpstd::vector class, and the constructor for cpstd::initializer_list is correctly implemented.

While reading the error log, I noticed that std::initializer_list constructor has two parameters, a pointer to the data, and also a variable telling the length of the braced enclosed list, however I noticed that the list ends up casting to a single parameter, hence having no possible constructor to call

What could be causing this issue, and how can I resolve it to initialize cpstd::vector using brace-enclosed initializer lists in the Arduino environment? I think the main issue is with boards that have no STL support. (i.e. AVR based boards)
I've came to the conclusion that it will not be possible to create such constructors/operators due to compiler limitations, I think I've tried anything that came to mind. But I don't want to give up on this without knowing if there is a workaround.
edit (removed previous code snippets for clarity, added minimal code example reproducing the error) :
minimal sketch reproducing the error:
#include <Arduino.h>
#include <stddef.h>

namespace cpstd {

  template<typename T>
  class initializer_list {
  public:
    using value_type = T;
    using reference = const T&;
    using const_reference = const T&;
    using size_type = size_t;
    using const_iterator = const T*;

  private:
    const_iterator _M_array;
    size_type _M_len;

    constexpr initializer_list(const T* array, size_type size) noexcept
      : _M_array(array), _M_len(size) {}

  public:
    constexpr initializer_list() noexcept
      : _M_array(nullptr), _M_len(0) {}

    constexpr size_type size() const noexcept {
      return _M_len;
    }
    constexpr const_iterator begin() const noexcept {
      return _M_array;
    }
    constexpr const_iterator end() const noexcept {
      return _M_array + _M_len;
    }
  };
}

template<typename T>
class exampleClass{
  protected:
    T buffer[10];
    size_t len;

  public:
    exampleClass(): len(0) {}
    exampleClass(cpstd::initializer_list<T> il){
      len = il.size();
      for(size_t i = 0; i < len; i++){
        buffer[i] = *(il.begin()+i);
      }
    }

    exampleClass& operator=(cpstd::initializer_list<T> il){
      len = il.size();
      for(auto i = il.begin(); i < il.end(); i++){
        buffer[i] = *i;
      }
    }

    size_t size() const {return len;}
    T data(size_t x) const {return buffer[x];}
};

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

  exampleClass<uint8_t> myObject = {0,1,2,3};

  Serial.println(myObject.size());
  Serial.println(myObject.data(0));
  Serial.println(myObject.data(1));
  Serial.println(myObject.data(2));
  Serial.println(myObject.data(3));

}

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

}

To the close voters because "off-topic": Since the Arduino build system does magic under the hood, it can well be the "culprit." Therefore, I see this question as on-topic.

The underlying compiler system is a common GCC, therefore I don't think that the compiler is limited. However, my current situation does not allow me to investigate by reproducing the issue. -- In the meantime, would you mind to [edit] your question and extend the provided source to a minimal, complete, and reproducible example, please? You don't want each of us to invest that time,do you?

@thebusybee my bad, I'll sure add a complete, and reproducible example

Just a random thought: does it work if you initialize the vector with cpstd::vector<unsigned char> myVector{0, 1, 2, 3, 4}; (without the =)?

@EdgarBonet I did try, but the same happens, since the problem is that the compiler wont convert {x, x, x} to a cpstd::initializer_list

So I have been messing around with the minimal example code and found a working solution, I'll post the solution just in case someone finds themselves having the same issue on the future, the only downside is that it feels a bit hacky to my taste, I still wonder if there is a better solution. And would gratly appreciate any feedback.
I found out that the compiler does not ackowledges the initializer_list class for braced enclosed initializers if the class is not under the namespace std.
The way I came arround this problem lies on using the preprocessor directive below:
#if __has_include(<initializer_list>)

With this line conditional compilation takes place, and we can specify what to do whenever std::initializer_list is present or not.

If std::initializer_list is not present an implementation is provided.
cpstd::intitlizer_list is only a template alias of std::intitializer_list

minimal sketch with the solution:
#include <Arduino.h>
#include <stddef.h>

namespace std {

  template<typename T>
  class initializer_list {
  public:
    using value_type = T;
    using reference = const T&;
    using const_reference = const T&;
    using size_type = size_t;
    using const_iterator = const T*;

  private:
    const_iterator _M_array;
    size_type _M_len;

    constexpr initializer_list(const T* array, size_type size) noexcept
      : _M_array(array), _M_len(size) {}

  public:
    constexpr initializer_list() noexcept
      : _M_array(nullptr), _M_len(0) {}

    constexpr size_type size() const noexcept {
      return _M_len;
    }
    constexpr const_iterator begin() const noexcept {
      return _M_array;
    }
    constexpr const_iterator end() const noexcept {
      return _M_array + _M_len;
    }
  };
}

namespace cpstd {
  template<class T>
  using initializer_list = std::initializer_list<T>;
}

template<typename T>
class exampleClass{
  protected:
    T buffer[10];
    size_t len;

  public:
    exampleClass(): len(0) {}
    exampleClass(cpstd::initializer_list<T> il){
      len = il.size();
      for(size_t i = 0; i < len; i++){
        buffer[i] = *(il.begin()+i);
      }
    }

    exampleClass& operator=(cpstd::initializer_list<T> il){
      len = il.size();
      for(auto i = il.begin(); i < il.end(); i++){
        buffer[i] = *i;
      }
    }

    size_t size() const {return len;}
    T data(size_t x) const {return buffer[x];}
};

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

  exampleClass<uint8_t> myObject = {0,1,2,3};

  Serial.println(myObject.size());
  Serial.println(myObject.data(0));
  Serial.println(myObject.data(1));
  Serial.println(myObject.data(2));
  Serial.println(myObject.data(3));

}

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

}

Well done! Unfortunately answer should not contain follow-up questions, and the one about the keyword looks as non-Arduino specific, too. I suggest to post this one separately on [so].

I added the questions in my answer in case someone else wanted to add another answer, I think those are arduino specific questions because it implies using the arduino toolchain to reproduce the problems, I did not have this issues when compiling on other systems

As I commented, the underlying compiler is a common GCC. There is apparently nothing Arduino specific. However, this second question is a different issue, and as such needs its own question. You might want to link back to here. Please note that this is not a forum.

@thebusybee, you're right, im removing the questions from the answer


text:
How to measure electrical conductivity using Arduino?
I want to measure TSS (Total soluble salt) in the soil. I have found in some literature that, through measuring of electrical conductivity, it is much easier to measure TSS. So, I thought, If I can measure electrical conductivity, it might be possible to find out TSS.
Logic behind the TSS is that, pure water is poor conductor of electric, increasing of soluble salt in water proportionately lift up the conductivity. So are there any sensors that readily measure conductivity? A point I also want to mention, can a voltmeter be useful for that?

imho, you would want to use RC timings over analogRead, which tends to be more precise. micros() is high-res and reliable, built-in ADCs are not.

Whats parameters or values change for get it working with esp32

That should be possible  ... connect +5V to one end, an analog input pin on the other, don't forget a resistor which is high enough not to get more current than allowed. Than measure on the analog input pin the conductivity (value) and act on it.
Afaik the max amperage for an analog pin is 20 mA if I remember correctly. Thus a resistor of V = I * R <=> 5 = 0.02 * R <=> R = 5 / 0.02 = 250 ohm should be ok. This will only occur if the conductivity is 100%. If you get a very low conductivity than you will get very low numbers when reading the analog pin. When you get too less values, you have to lower the resistor value, but you risk of burning a pin when too much current gets across.

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


text:
Communicating via Serial Monitor but not able to get comms via Terminal outside of Arduino IDE
I am using Arduino Nano 33 BLE. I am able to communicate via Serial Monitor within Arduino IDE, but not able to communicate via Terminal, outside of Arduino IDE. I am using Teraterm, do I need to do any additional setting?
No error messages. It does work on the Serial Monitor of Arduino IDE at 115200 baud rate with the default settings ("SERIAL_8N1"). The serial port Setup on Teraterm is the following:
Speed: 115200 Data: 8 bit Parity: none. Stop bits: 1 bit. Flow control: none
The thing is that it does what it has to do writing one command that is one letter, I mean, in my Arduino sketch if you write "$" on Serial Monitor it does a reset, and through Teraterm if you write "$" It does a reset as well,.. but on Teraterm if I type a command longer than one letter It doesn't even show what I type on Teraterm and doesn't recognize.

do you get some error message? (add it to the question)

What are the serial port settings on the Arduino sketch? On the serial monitor? On Teraterm?

not able to communicate is a similar description to not feeling well ... it provides no useful information about the problem

Are you saying that you don't see what you type? That would be the default for many terminal programs. You need to turn on "local echo" to see what you are typing.

Got a sketch you can show us?

In TeraTerm the local echo is off by default. So you won't see anything while you type something. Here are the settings:

First connect to the serial port.

Then go to Setup->Terminal.

Based on your code select what you are expecting to receive at the end of a transmission from Arduino and what you need to send at the end of your command to Arduino to tell it is the end of the command. Usually, it can be Carriage Return (CR: 0x0D) or Line Feed (LF: 0x13), or both.

Also, check Local echo. That will print whatever you are typing on the terminal.

Then Setup->Serial port....

And configure your serial port accordingly.

What you call a “terminal” is actually a terminal emulator, i.e. a
computer program intended to emulate an old school computer
terminal. CRT-based terminals were in turn designed to emulate still
older “hard-copy terminals”, like the venerable ASR-33. A hard-copy
terminal (also called “teletypewriter”) is basically a typewriter fitted
with a serial port. Whatever you type is sent along the wire. Keystrokes
are sent immediately: these devices did not have memory (which was
hugely expensive at the time) and could not buffer your input. The
Teraterm program you are using inherits from this history: like a
teletypewriter, it sends your keystrokes immediately.
The Arduino serial monitor, in contrast, does not transmit as you type.
Instead, you type a line of text and, when you hit “Send”, the whole
line is sent at once, at the full speed of the serial port.
This makes a significant difference in terms of transmission timing.
With Teraterm, the Arduino program sees long pauses (which depend on
your typing speed) between successive characters. With the serial
monitor, successive characters are spaced by roughly 87 µs. If your
Arduino code properly buffers its input until it receives an
end-of-line, then it will work equally well with Teraterm and with the
serial monitor. If, on the other hand, your code gets impatient and
times out while you are typing, then it will not get multi-character
commands you type on Teraterm.
Note that, if you want your Arduino program to be friendly to terminal
users, you may want to echo the characters you receive, as local echo on
the terminal is usually not on by default. More importantly, you may
want to handle the backspace key (which can send either ASCII BS or
ASCII DEL) to let the user fix their typos. See how this is done in this
very simple command-line interpreter.


text:
How do I code my arduino to return a throttle servo to idle?
I have an Arduino powering a small 180 degree Parallax servo that is used to control the throttle link for a small engine. I have code right now that will allow me to open/close the throttle (in either 1/4 or 1/5 increments) using the keyboard of my computer. This is well and fine but I really want to get it working so that when I press (hold) the hot key "t" the throttle will open but when I release the hot key I want the servo to cycle back to its original position (where the engine idles). If you have suggestions I would really appreciate them.
I am using Putty (Putty.org) to interface with the serial monitor so the arduino knows when 't' is pressed.
My Arduino code is just below this bit of wording (55 deg and 0 deg are the bounds of my throttle link, 55 is closed throttle (idle) and 0 is open throttle):
#include <Servo.h>

Servo servo;

int pos = 55;  // Stores the position (angle) of the servo. Range is [0, 180].

void setup()
{
  Serial.begin(9600);
  servo.attach(9);  // Attaches the servo on pin 9 to the servo object.
  servo.write(55);  // Resets the position.
}

void loop()
{
  if (Serial.available())   // Returns true if there is serial input.
{
    char ch = Serial.read();

    if (ch == 't')

      {if (pos <= 55)
        {pos -= 11.25 ;}}

     else

      {if (pos >= 0)
        {pos += 11.25 ;}}

    // Now ask the servo to move to that position.
    servo.write(pos);
    // Mechnical limitation to the frequency of commands given.
    delay(15);
}

}

If your terminal program uses key-repeat, then let each 't' operate the throttle for just slightly longer than the repeat period (slightly longer than twice the period, if you want to tolerate single dropped characters). After that period without another 't', close the throttle. One implementation would be to (re-)start a countdown timer every time you see a 't', and close the throttle when the timer goes to zero.
No auto-repeat? You'll have to simulate it with your finger (and code for a somewhat longer repeat interval, of course).


text:
Transistor Switching
I'm hoping that someone will be able to help me. I'm looking to produce a power interrupt for testing. I'm looking to have 28V DC input flowing to an output which I can hook up to a load and then switch on and off using an Arduino. I'm thinking of using an NPN high current transistor, I have built the box and code which runs fine. The issue I am having is the pin output on pin 13 doesn't have enough current to switch the transistor, can anyone recommend a transistor that would be able to take the high current and be switched by the Arduino? If you would like a schematic to help you understand it I can provide one!
Thanks for reading,
Lewis

Define "high current" - also how is the transistor wired?

Around 4A, see photo above for wiring of transistor

For high side switch I would use PNP not NPN, and switch it using an NPN. To be more specific I would use a P-channel MOSFET and switch it using an N-channel MOSFET or NPN transistor. Google "MOSFET High Side Switch" and you will find many circuits.

Here is one example: http://electronics.stackexchange.com/questions/42030/p-channel-mosfet-high-side-switch

Your current circuit will only apply around 4.3v to the load (assuming a 5v Arduino PSU). Can you switch the ground side rather than the 28v side? Circuitry will be far simpler.

If you did manage to switch the transistor on, It would only output 4.3V, the rest would be dissipated in the transistor. If you managed to switch 4A this would dissipate 96W - and the transistor would melt.
A MOSFET would be a better option and could be easily switched by the Arduino. (I regularly switch 10A using a MOSFET and Arduino.)
This assumes you can put the MOSFET in the negative lead. If not you should use a P-Channel MOSFET, but you need a more complex circuit to drive it.
Have you considered using a relay module?

Thanks for the answer! So I'd be able to use the MOSFET in this configuration and get the Arduino to switch it. I did look at using a relay but I didn't think that the Arduino would be able to switch it, this would be a simpler solution though, any relays that you could recommend ?

Could I use this relay ?  http://uk.rs-online.com/web/p/solid-state-relays/6996632/

Or this transistor? http://uk.rs-online.com/web/p/mosfet-transistors/5411720/

@Lewis, that SSR is rated at 4 A max.  Look for an 8 to 10 A rated SSR or electromechanical relay to handle your 4 A load.   The P mosfet is ok except its V_GS is limited to ±20 V, hence the gate must be above 8 V if the source or drain is at 28 V.  Anyhow, to definitely turn the P mosfet off, you need to have the gate above 26 V, and to  definitely turn it on, below 24 V (assuming V+ = 28 V).   The Arduino's pin 13 is  (Vcc+0.5 V) max, too low to drive the P mosfet's gate without using an intermediate N-fet or NPN or some diode network.

Thanks for all your help guys, my knowledge is still getting there, thanks for being patient. So this relay would be able to be controlled by the Arduino due to its low control voltage? @jwpat7

http://uk.rs-online.com/web/p/solid-state-relays/2448987/

@Lewis, yes, that would work.   But so would some less-expensive RS items, as long as switching type is DC or AC/DC, and Minimum Control Voltage is somewhere under 5 V.  Also on ebay you might be able to buy a batch of 5 or 10 ea. 25A SSRs for a lower cost than that one RS 6A SSR.


text:
Execute function until called again?
I am building a simple security system with my Arduino Uno. I have an alarm() function:
void alarm() {
  tone(8, 3300, 200);
  delay(200);
  tone(8, 3000, 200);
  delay(200);
}

When I call it in the loop() function like so:
void loop() {
  alarm();
}

the alarm sounds fine. I just want to be able to stop it. What I mean is, I want it to start the alarm (if it is off) when I call the alarm() function, then stop it when I call the alarm() function again. How can I do this?
P.S. Can someone with over 150 reputation please make the tone tag? I can't believe it's not here!
Edit: I tried the following code, but the alarm just kept going:
bool alarmOn;
void setup() {
  pinMode(8, OUTPUT);
  alarm(true);
  delay(5000);
  alarm(false);
}

void loop() {
}

void alarm(boolean call) {
  if (call) {
    alarmOn = true;
  } else {
    alarmOn = false;
  }
  while (alarmOn) {
    tone(8, 3300, 200);
    delay(200);
    tone(8, 3000, 200);
    delay(200);
  }
}

There is nothing in the while (alarmOn) loop that can unset alarmOn: if alarmOn is initially true you have an infinite loop.

You can just have a variable that remembers whether the alarm is
supposed to be on or off. Let's call it alarm_on. Then:
bool alarm_on;
static void start_alarm() { alarm_on = true; }
static void  stop_alarm() { noTone(); alarm_on = false; }

void loop()
{
    if (alarm_on) alarm();
    if (some_condition()) start_alarm();
    if (some_other_condition()) stop_alarm();
}

For a better approach that allows you to sound the alarm without
blocking the whole program, see the Blink Without Delay Arduino
tutorial.
Edit: I just wrote (but did not test) a non-blocking version of this
alarm, based on a state machine and the timing technique from the Blink
Without Delay tutorial. Here it is, as a class:
class TwoToneAlarm {
public:
    static const uint16_t HIGH_FREQ = 3300;
    static const uint16_t LOW_FREQ  = 3000;
    static const uint16_t TONE_DURATION = 200;

    TwoToneAlarm(uint8_t output_pin)
    : state(OFF), pin(output_pin) {}

    // Start the alarm.
    void start()
    {
        tone(pin, HIGH_FREQ);
        state = HIGH_TONE;
        last_tone_change = millis();
    }

    // Stop the alarm.
    void stop()
    {
        noTone(pin);
        state = OFF;
    }

    // Call this periodically to handle the tone changes.
    void update()
    {
        if (state == OFF) return;
        if (millis() - last_tone_change >= TONE_DURATION) {
            switch (state) {
                case HIGH_TONE:
                    tone(pin, LOW_FREQ);
                    state = LOW_TONE;
                    break;
                case LOW_TONE:
                    tone(pin, HIGH_FREQ);
                    state = HIGH_TONE;
                    break;
                default:
                    break;
            }
            last_tone_change += TONE_DURATION;
        }
    }

private:
    enum { OFF, HIGH_TONE, LOW_TONE } state;
    uint16_t last_tone_change;
    uint8_t pin;
};

It could be used like this:
TwoToneAlarm alarm(8);

void loop()
{
    if (some_scary_condition()) alarm.start();
    if (some_other_condition()) alarm.stop();
    alarm.update();
}

Note that the whole program must be non-blocking (delay()-free),
otherwise the tone changes will not be done on time.
Edit: more about being non-blocking.
There is normally no reason for you to use delay() at all in your
program. The only reason for this function to exist is to help complete
beginners write their first blink-the-LED program. As soon as you start
writing anything non trivial, you should ban it from your vocabulary.
The Blink Without Delay tutorial is here precisely to teach you how to
get rid of delay() by using millis().
In this particular case, however, the drawback of delay() may not be
too severe: if the alarm is sounding and you delay a tone change, you
may hear it as a glitch that breaks the rhythm of the sound. If the
delay is short enough, maybe up to 10 ms or so, you are unlikely to
notice it. Longer delays will be noticeable, and it's up to you to
decide whether you find them annoying or not.
It is possible to ensure a very steady rhythm despite the delays by
using interrupts, but this will cost you your 16-bit timer. Or you could
write your own implementation of tone() that does both the pin
toggling and the tone changes using a single timer. Any such option will
require you to learn about low-level timer
programming, which is significantly
more demanding than learning to use millis().

Your code inspired me to do something different. See my edited answer above. About making the tone tag...

That's perfect! Still, is there any way I can use delay() in the body? It is a security system and it needs to be user-friendly.

How can I use this as an Arduino library?

@CelloGuy: 1) There is no incompatibility between being delay()-free and being user friendly, but see the amended answer. 2) Making a piece of code into a library is a different question, unrelated to this one.


text:
ATTINY85 with RGB LED
I'm trying to DIY about a dozen BlinkSticks (discontinued, Adafruit) pictured here

I'm thinking to use a Digispark ATTINY85 to control a single RGB LED to show the status of some program running under Linux. Here is the proto board I have my eye on:

I could either use a single individually addressable RGB LED with a built-in WS281X controller

or a plain RGB LED with each color pin connected to a GPIO pin on the TINY85.

This is my first Arduino project, so I'm not familiar with the best way to approach this project. I'm trying to keep the part count low as well so the serial data approach is appealing too. Has anyone done this before and can explain their setup?

Prior work I've found for the simple control approach:

The blinkstick schematics are available: https://www.blinkstick.com/help/schematics

A plain rgb led needs resistors and with the same resistors one color is brighter than an other color. So you have to tune the resistors or the pwm in the code. A rgb led with built-in controller is easier to get a certain color, and the controller has often more than 8 bits so very dim values are no problem. However, you need a library which uses flash and ram which is very limited for a attiny85. The best option is a atmega328p with a rgb led with built-in controller. Everything else is looking for trouble.

The newest blinkstick uses an addressable led, while the Adafruit kit appears to use a regular 4 pin RGB led. These are easier to get.
The digispark and the blinkstick are almost identical, but they use different pins for the USB connection. So to use the firmware for the blinkstick on the digispark, you need to change the pin numbers in usbconfig.h
#define USB_CFG_DMINUS_BIT      3
#define USB_CFG_DPLUS_BIT       2

PS. the pin numbers in usbconfig.h don't seem to match the schematic, so I'm not sure what's going on

This is a good observation. Thanks for taking the time. I'll assemble the project with the ATTINY85 board I've found and the WS2812 LED plus the capacitor, then adjust the firmware as you indicated and report back how it works. Thanks again.

I don't think you need the capacitor. Best of luck.


text:
Arduino due + mcp2551
I am currently using an atmega328 along with the mcp 2515 and the 2551 for CAN communication in my systems.
However, I've now decided to upgrade to the arduino due for my operations. Can anybody tell me if the arduino due along with it's inbuilt CAN controller be used with the mcp2551 transciever to operate CAN successfully.
If not, can somebody also tell me if there are other alternatives I should look into. Thanks :)

The biggest trouble you are going to find is the voltage levels. The MCP2551 works at 5V and your MCU is 3.3V. I personally don't have experience with this MCUs, but some STM32 MCUs are 5V tolerant on some pins, including the CAN_TX and Can_RX and it's fine to use a 5V Transceiver like the MCP2551.
Anyway, you still can replace the CAN Transceiver with one that has a built in level shifter,  like one of the following:

MCP2562
ATA6561
SN65HVD256
NCV7351D13

I've used all the above, except the TI one, and they all talk nicely between each other. Some have different features, like silence or advanced sleeping modes.
Cheers

The Arduino Due is definitely not 5V tolerant. From https://www.arduino.cc/en/Main/ArduinoBoardDue: "The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board."


text:
Can only upload certain programs to standalone Arduino
I can't upload a program that uses digitalRead, analogRead, and Serial.print on my standalone Arduino, because I get this error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xbf

However, I have no trouble uploading the blink program to it, which only uses digitalWrite, so it has to do something with the methods mentioned at the start of this post.
You can see the diagram below.

I added a connection between digital pin 9 and ground with an led

I uploaded the blink program, changed the dgital pin to 9 in the program, uploaded it and connected an led from digital pin 9 to ground. Then I can see the led is blinking every 1 second.

change the blink rate to 1/2 second

It can do that. Now it turns on/off every 500 ms.

ok, this is pretty weird. ... i originally thought that maybe you missed the download fail with the blink program, and the Arduino already had a blink program loaded. ... i have to think on this one

Please post (edit your question) the code that does not upload.

I do not see any decoupling capacitors between Vcc and AVcc and ground, which are absolutely required.

Also, remove the Aref connection to 5V. Aref should only have a 0.1uF cap to Gnd.
Won't affect programming, but could damage the internal ADC mux or other ADC circuits.


text:
What's the newest way to use C++ stdlibs in Arduino 1.8.2?
(My Arduino version is 1.8.2.)
For example,if I want to #include <vector> or <string>, <iostream>, <memory> etc, the compiler always complains that such libs are not found.
So what's the newest/most efficient way to use C++ libs in Arduino 1.8.2?

It would be nice but with the available memory resources (Arduino Uno, 2KB SRAM) makes it difficult to implement and use this. The 2KB has to hold all data, stack and heap; https://www.nongnu.org/avr-libc/user-manual/malloc.html

Most Arduino Core don't include the Standard C++ Library, that's why headers like <vector> and <string> are missing.
This decision makes a lot of sense because the STL relies heavily on heap allocation, which would ruin the little RAM of the microcontroller.
If you're looking for an alternative to the STL, you might check out the ETL, the Embedded Template Library.. However, the code will not be the same because all the containers of the ETL have a fixed capacity. Here is a string for example:
etl::string<32> s = "hello world";

In practice, I never saw a project using the ETL. Most projects use the standard Arduino classes (String, Stream, Print...) and learn to live with their flaws. Since there are no generic container classes in the Arduino core, the common usage is to use plain old C arrays.


text:
Connecting CAT5 robustly between portable Arduino and more portable sensors
Newbie wiring question. I’m building a lightwand of some sort, involving an RGB LED and a few pushbuttons that I want to wave around (the “remote”), while staying connected over ~0.5 - 3m to an Uno (the “head”).
In a portable incarnation, the remote might be on your finger and the battery-operated head in your backpack. I’m hoping to use stranded CAT5 for the connection between them (“the bridge”) — it’s the right number of conductors, good flexibility, I have lots of it.
My question is: how should I best mate the CAT5 to both ends — pins on the Arduino at the head, and pins or bare wire off my LED and switches at the remote?
At the head, I like the idea of an RJ45 jack (“NOT ETHERNET”), both for modularity and as I’m a bit worried about strain on the cable pulling wires out of Arduino pins. (The jack basically gives me a good interface at the enclosure level.) I could get an RJ45-to-wiring-terminal-block, and then run solid jumpers from the block to the pins, but they’re expensive. I could try a keystone jack and just try using solid jumpers rather than more CAT5 going between the jack’s wire-breakout and the Arduino board — but I worry the jumpers won’t be the right “size” for the jack, and I’m worried about flimsiness. (If the entire head enclosure is in your backpack, it’s going to get jostled. I want something durable.)
I see some examples of an RJ45 jack soldered directly to a board. What sort of RJ45 is that, and could I do that and solder straight to the board pins on a cheap shield, with relatively novice soldering skills? Or is this at risk when people yank the cable inadvertently?
As I said: I’m a newbie, don’t know what’s reasonable, and keep coming up with overcomplicated architectures where the CAT5e connects to a jack to a block to jumpers to pins,  etc. etc.
At the remote, I think I’m better off. Things need to be as small/portable as possible, so I think I bring the bare stranded wire out of the CAT5e onto a tiny bit of board, and just solder the strands directly to the leads coming off my buttons and LED, and wrap some tape around it, then attach the whole thing to a glove or a bracelet to keep it relatively immobile at the end of the cable. Ok or terrible?
Thanks for suggestions, directions, and other help. I’ve looked around and don’t see questions at this level of ignorance. One of the answers to this mentions that “people wire a RJ45 sock directly to an Arduino” (my head problem) but doesn't say exactly how.  How can I attach sensors without a shield for a wearable project? is doing what I want, but also underspecified...

Certainly go for RJ45 sockets.  Not only does it help protect the wire, but it gives you a really easy way of swapping the wire for different lengths should you want to.
You can't solder an RJ45 socket directly to a normal prototyping board. The pins aren't in the right pattern.  So, you could go for something like this

That can then either be soldered to wires or, since the pins are now in a normal 0.1" pitch, solder the whole module to a prototype board or shield.
Be sure you get a vanilla RJ45 socket, not a "MagJack", which contains extra Ethernet-specific electronics inside it.
If you do want to solder the wires directly to a PCB simply drill a couple of holes just in from one edge of the PCB, run the cable between them, and strap a cable tie around it.  Here's an example:

That PCB has specially shaped slots designed into it for the cable tie.
Also, for soldering, you want a good quality cable. A cheap one from eBay will most likely be made of aluminium with a thin plating (if you're lucky) of copper. A better quality one will be made entirely of copper. Aluminium cables don't solder well. Fine for crimping to an RJ45 plug, but rubbish for soldering.

Thanks @Majenko, esp. for the clarification re MagJack. I can use both of your suggestions on different ends of my cable: breakout board soldered to Arduino shield at the head end, cable tie to local support deck at the remote end.


text:
What is the max output rating of the pins on the Arduino Mega?
I have conflicting information on the max output rating for the Arduino Mega.  Some say 200 mA and others say 800 mA like the Uno board.  I am running 8 model railroad signal devices that have (3) 3mm LEDs (Red, Yellow, and Green) in each signal.  Of the 24 LEDs, only 8 are energized at any point in time.  8*.020 = 160 mA.  I believe I am good, but confused as to why the Uno board with 13 digital output pins can handle 800 mA and the Mega board with 40 or so output pins (not including all the TX RX IO pins) can only handle 200 mA.  Lots of forum discussion on this, but most go over my head without answering the question! LOL
Simply, how many mA can all of the digital pins combined provide?

Well theory (math) is nice, and a good starting point, but reality is better.
The signals I am talking about are (model) railroad trackside warning signal devices that have a red, yellow and green light, and depending on which light is lit, tells the train's Engineer if it is safe to continue down the track.

Each of these signals are 2.1/2" in height and the LEDs use 30 gauge wires and a 1K resistor.
I connected the red LED on all 8 signal devices to my variable power supply, turned it on and lit all 8 red LEDs with 5 volts, and wow, all 8 only used .023 amps total.
I then disconnected 7 of them and a single red LED only used .002 - .003 amps.  I connected the rest of the signals one at a time, and 2 signals used .006 amps, 3 signals used .009 amps, 4 signals used .011 amps, 5 signals used .014 amps, 6 signals used .017 amps, 7 signals used .020 amps and all 8 signals again only used .023 amps.
If this is the case, that is less than the max output from a single pin.
So, my plan is to connect the signals to the Arduino Mega 2560 on at a time, monitor the total current the Arduino in using after connecting each signal, and see just how much these signals are using.

Where does it say the Uno can handle 800 mA? Link please.

Are you using resistors between the output pins and the LEDs? If not, you should be. By choosing an appropriate value resistor you can limit the current to any figure. There is an LED calculator web site to help you do that.

Sticking to your original point, please explain where you read about the Uno and 800 mA. If you want to make additional explanations please edit the question - don't make an answer.

It's possible your signals come with inbuilt resistors - looking at the datasheet for them may help.

Ah, I see you mentioned a 1k resistor. That's why they don't draw a lot of current. Based on Ohm's law, if you have a 5V supply, and a 1.8V voltage drop (approximately normal for a red LED) and a 1K resistor, then you expect to draw (5 - 1.8)/1000 amps, which is 3.2 mA.

The 1k resistor is meant to help the LED survive 12V or even slightly more. If the devices are bright enough you've got the solution: Calculate with 3 mA per led and you're fine.
If you notice they look nicer when fed by 12V I'd rather add a little transistor and 4k7 base resistor (5-0.7 / 4700 = 1mA Arduino current) to switch 12V, than exchange the 1k led resistor by a smaller one.

The answers are right there in the datasheet.
The datasheet of the ATMega2560 (and 1280 etc.), page 355, states an absolute maximum current of 200 mA for the ATMega package and 40 mA per I/O pin.
In addition (thank you for the comment, @NickGammon), there are some further restrictions that are described from page 356 of the linked datasheet:

The sum of current which can be sunk from various ports cannot exceed 100 mA, and from others, 200 mA.
The same is true for the amount of current that can be sourced from various ports.

For example, for ports A0-A7 you cannot source a total of more than 100 mA (under steady conditions) and not 40 mA * 8 like you might expect.
So, if you had 8 LEDs on at once, continuously, you would only have 12.5 mA available for each of those ports (for a total of 8 x 12.5 mA = 100 mA).
That means that the 160 mA mentioned in the question could easily be out of spec.
It's not recommended to stay at or near the Absolute Maximum values mentioned in the datasheet for an extended amount of time. It's better to design your solution so that these abolute maximum values are never approached.
For your particular situation I would look into external (TTL) buffers between your Mega and your LEDs.
Alternatively, you could reduce the amount of current through the LEDs to make sure the total amount of current will always stay well below 200 mA or the other limitations mentioned above.

You might want to mention further restrictions, from page 356 of the linked datasheet. The sum of current which can be sunk from various ports cannot exceed 100 mA, and from others, 200 mA. Ditto for the amount of current that can be sourced from various ports. So for example, for ports A0-A7 you cannot source a total of more than 100 mA (under steady conditions) not 40 mA * 8. So if you had 8 LEDs on at once, continuously, you are down to 12.5 mA each, for those ports. So, the 160 mA mentioned in the question could easily be out of spec.

Thank you, @NickGammon, I've added that information to the answer.


text:
Using file.seek() with arduino ide
I have in my code in c, this function:
    fseek(file, 0, SEEK_SET);

I need to use the same function with Arduino ide. Is this correct?
    file.seek(file.size());

Or what is the alternative function in Arduino ide?

https://www.arduino.cc/reference/en/libraries/sd/seek/

Just try it and see what happens.  That will be way faster than asking.

It can be faster to look up the documentation than wait hours for someone to answer.

OT, to clarify technical terms: The Arduino IDE is just that, an integrated development environment. It does not provide functions or classes, it just recognizes the names and therefore give you some support. The real thing you mean are the Arduino libraries, the reference of which you should bookmark in your browser. However, an installation puts all of this on your computer. (There is more, for example the compiler system...) You can use each without the other.

According to https://www.arduino.cc/reference/en/libraries/sd/seek/ :
SD - seek()
Seek to a new position in the file, which must be between 0 and the size of the file (inclusive).
Syntax
file.seek(pos)

Parameters

file: an instance of the File class (returned by SD.open()).
pos: the position to which to seek (unsigned long).

If you want to seek to the start of the file, therefore you should seek to zero, not file.size(). Using file.size() would seek to the end of the file.