text:
Splitting String from Serial
I am currently working on a program for an Arduino uno and want to, in the program, when it receives a 16 digit number from a serial transmition, it will split the 16 digit number into 4 separate 4 digit numbers.
For Example:
The computer sends the Arduino the number 1100115011001150 and I want the Arduino to break the number so that "Avalue" would equal 1100, "Bvalue" would equal 1150, "Cvalue" would equal 1100 and so on...
Thanks for any help you can provide!

Have you tried indexing the array in loops?

How does that work and what does that do?

@Buncey are you not familiar with for and while loops?

What is your actual question?

char ArrayBuffer[][4] = {};         // holds four characters, must be

declared as global to loop()
in
loop()
{
byte Index = 0;                    // initialize array index
if(Serial.available())             // have data in Serial buffer
{
byte Count = Serial.readBytes(ArrayBuffer[Index],4); // read       //4             //characters     into array buffer , returns actual number //of        characters //read and times out if less than 4 characters are //currently in Serial buffer
 Serial.println(ArrayBuffer[Index]); // print buffer to monitor
}while(++Index != 4);              // read 4 by 4 characters from incoming stream
}

...
continue with loop - process ArrayBuffer as required
}
This is one way to get the incoming stream from Serial buffer into for individual buffers, however, it is better, less chance of misdirecting the data into wrong buffer (index)  to read the entire buffer at once instead of using he readBytes four times.
Just my opinion, your mileage will vary.
PS what is the trick to format the code and text correctly ?
This is a mess.
I cannot get the code block to indent, I can get only the first ( four spaces line.

while (Serial.available() < 16);   // wait for 16 chars to come          easiest way to do this
for (int i = 0; i < 4; i++){      // for each number
    for (int j = 0; j < 4; j++){    // for each digit in the number
        nums[i] *= 10;
        nums[i] += Serial.read() - '0';

Where did my last post - comment on this code went?
It was suppose to wait for "peers" approval, per note I got after I posted it.
This is not the best way to use "available()", beside what will happen if 16 characters never arrive?

I do see your other answer, you probably had to wait a little.
You can now edit your old answer and delete this one.

int nums[] = {0, 0, 0, 0};   // must be always reset to zero if you will repeat this process
while (Serial.available() < 16);   // wait for 16 chars to come in; easiest way to do this
for (int i = 0; i < 4; i++){      // for each number
    for (int j = 0; j < 4; j++){    // for each digit in the number
        nums[i] *= 10;
        nums[i] += Serial.read() - '0';

//while (Serial.available() == 0);
//Serial.read();  // in case you use an extra character to separate numbers

A = nums[0];
B = nums[1];
C = nums[2];
D = nums[3];

If you are using a character or characters to delimit the 16-digit numbers being received, make sure to read off those extra characters before running the while loop again.

Not tested but should work.
int nums[] = {0, 0, 0, 0};
String inString = "";
while (Serial.available() >= 16) {
  for (int k =0;k<4;k++) {
    for (int i =0;i<4;i++) {
      int inChar = Serial.read();
      if (isDigit(inChar)) {
        inString += (char)inChar;
      }
    }
    nums[k]=inString.toInt();
    inString = "";
  }
  Serial.println(nums[0]);
  Serial.println(nums[1]);
  Serial.println(nums[2]);
  Serial.println(nums[3]);
}


text:
Adafruit Trinket 3v with LED matrix backpack producing error
I have been wanting to create a Arduino watch. I built the circuit with an Adafruit Trinket 3v and an Adafruit LED matrix backpack (8*8). When I try to upload this example code:
/***************************************************
  This is a library for our I2C LED Backpacks

  Designed specifically to work with the Adafruit LED Matrix backpacks
  ----> http://www.adafruit.com/products/872
  ----> http://www.adafruit.com/products/871
  ----> http://www.adafruit.com/products/870

  These displays use I2C to communicate, 2 pins are required to
  interface. There are multiple selectable I2C addresses. For backpacks
  with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks
  with 3 Address Select pins: 0x70 thru 0x77

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

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

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

Adafruit_8x8matrix matrix = Adafruit_8x8matrix();

void setup() {
  // Serial.begin(9600);
  // Serial.println("8x8 LED Matrix Test");

  matrix.begin(0x70);  // pass in the address
}

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 };

void loop() {
  matrix.clear();
  matrix.drawBitmap(0, 0, smile_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();
  matrix.drawBitmap(0, 0, neutral_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();
  matrix.drawBitmap(0, 0, frown_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();      // clear display
  matrix.drawPixel(0, 0, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawLine(0,0, 7,7, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawRect(0,0, 8,8, LED_ON);
  matrix.fillRect(2,2, 4,4, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawCircle(3,3, 3, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.setTextSize(1);
  matrix.setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
  matrix.setTextColor(LED_ON);
  for (int8_t x=0; x>=-36; x--) {
    matrix.clear();
    matrix.setCursor(x,0);
    matrix.print("Hello");
    matrix.writeDisplay();
    delay(100);
  }
  matrix.setRotation(3);
  for (int8_t x=7; x>=-36; x--) {
    matrix.clear();
    matrix.setCursor(x,0);
    matrix.print("World");
    matrix.writeDisplay();
    delay(100);
  }
  matrix.setRotation(0);
}

I get this error:
Build options changed, rebuilding all
In file included from matrix8x8.ino:23:0:
C:\Users\My_Username\Documents\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:30:24: fatal error: TinyWireM.h: No such file or directory
  #include <TinyWireM.h>
                        ^
compilation terminated.
Error compiling.

I have installed TinyWireM, Adafruit_GFX, and Adafruit_LEDBackpack. Why would I get this error?

Because the TinyWireM library isn't properly installed.

How would I properly install it? What could have gone wrong?

How did you install it? You must have done something wrong...

I got the .zip from github.com/adafruit/TinyWireM and then put the folder inside Documents\Arduino\libraries.

What is the name of "the folder"?

Remember to remove the "-master" from the library folder name.

The name of the folder is TinyWireM.

source: Stack Exchange

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

sort: votes


text:
Send AND Receive through i2c / set Arduino as master AND slave
For a project I'm using 2 Arduino Uno's, where Arduino#1 (master) sends raw data to Arduino#2 (slave). The slave should receive and encrypt the data and afterwards send the encrypted data back to the master. I'm building my project from the sketch found at arduino.cc.
How can I make the slave send back data, if he's the only one listening on incoming data, should both arduinos be listening to each other, and how to achieve this?

The I2C protocol is both read and write. Master/Slave depends on who initiates the communication. Typically the master will issue a read command to the slave to retrieve the results.
Cheers!

As the master I can use beginTransmission() and write() to send, and requestFrom() to receive, am I right? and on the slave side I use 2 eventhandlers for this, right?

Yes that is correct! All transmissions are initiated by the master with write() to send to the slave, and requestFrom() to read.

Thanks, that works now, only challenge now is to predict how long the return message is going to be. i.e. I use requestFrom(8,50) and the return message is 40 chars long instead of 50 then it gets filled with strange chars.

Typically you would have a number of "commands" or "registers" that you would issue or read from. One might be "Get buffer length" which returns the number of bytes in the "message" that are available for reading. Then you use that to get the right number of bytes.  So it's "Get Buffer Length => 40 => Get Buffer(40) => 40 chars"

I think the transmission size is limited to 32 bytes in the Arduino AVR Wire I2C driver implementation. Obviously there is no such limitation in Cosa :).

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


text:
help with an outlaw pinewood derby car
So I am trying to create a code for an outlaw pinewood derby car. It is using a brushless esc with reverse for a ducted fan. The car has a push button on the front along with headlight and brake light LED's.
My goal is to push the front button 5 times to activate the car, then place it against the gate (which will press the front button once again and keep it pressed until the gate falls and the race begins). Once the button is released I want the fan to turn on and push the car down the track. once a certain amount of time passes (enough time to cross the finish line, I will get this info once I get a chance to do some test runs, but for now let's say 1.5 secs) it will reverse the fan (to act as a brake) for another certain amount of time, as well as activate the brake lights. then turn off the fan completely.
A buddy and I have been trying to write a code for it but are at a loss.
Any suggestion or input would be greatly appreciated.
#include <Servo.h>                    //Use the Servo library for generating PWM
Servo ESC;                            //name the servo object, here ESC
int headLightLED = 7;                 // White LED headlights
int brakeLightLED = 15;               // Red LED tailights
int throttle = analogRead(A0);        //Read the voltage from POT
int DigitalPot = 6;                   //Digital potentiometer used to map ESC
int potValue = A0;                    // value from the analog pin
int MicroSwitch = 9;                  // Front momentary push button

void setup()
{
pinMode (headLightLED, OUTPUT);       // set headlights to output
pinMode (brakeLightLED, OUTPUT);      // set tailights to output
pinMode (DigitalPot, OUTPUT);         // Set digital potentiometer to output
pinMode (MicroSwitch, INPUT);         // set front switch to input
ESC.attach(10,1000,2000);             // Generate PWM in pin 10 of Arduino
delay (100);
ESC.write(10);                        // Activate ESC
delay(3000);                          // Wait for ESC to boot

throttle = map(throttle, 0, 1023, 0, 180); //Map the values of 0-1023 from pot to 0-180 bcs servo works only from 0-180

     delay(1000);
    digitalWrite(DigitalPot, LOW);       //Send mininum signal to A0
    analogRead (potValue);
    delay(1000);
    digitalWrite(DigitalPot, HIGH);    // Send Maximum signal to A0
    analogRead (potValue);
    delay(1000);
    digitalWrite(DigitalPot, LOW);       //  Return to zero throttle
    analogRead (potValue);
    delay(1000);
}

void loop()
{
    if (MicroSwitch == HIGH){
      int timeLapsed = millis();
    }else(MicroSwitch == LOW);
ESC.write(throttle);                   // based on the value of throttle generate PWM signal
 digitalWrite(throttle, 180);               // Full Speed
 delay(1500);
  digitalWrite(throttle, 0);                 // Full Reverse
  digitalWrite (brakeLightLED, HIGH);        // activate brake lights
  delay(1500);
  digitalWrite (throttle, 90);               // STOP
}

Welcome to Arduino:SE. You might find this post on our Meta site helpful: How to ask a good question for Arduino Stack Exchange.

are we supposed to guess what works and what does not work as intended?

You need to state what's wrong with your code/what you are struggling with. You also need to edit your question and find your indentation. As it is the code is just about impossible to follow.

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


text:
Increasing ADC resolution
At this moment I am using oversampling to increase my analogread resolution.
This in combination with increasing the frequency of the ADC.
Is someone able to take a look at it?
#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int value[100];   // variable to store the value coming from the sensor
int i=0;

void setup()
{
  Serial.begin(9600) ;
 int start ;
 int i ;

#if FASTADC
 // set prescale to 16 (1MHz)
 sbi(ADCSRA,ADPS2) ;
 cbi(ADCSRA,ADPS1) ;
 cbi(ADCSRA,ADPS0) ;
#endif
}

void loop()
  {
  for (i=0;i<100;i++)
  {
   value[i]=Read12bit(0);
  }
  for (i=0;i<100;i++)
  {
   Serial.println(value[i]);
  }
  Serial.println();//Some blanks between values
  Serial.println();
  delay(5000);

}

int Read12bit(uint8_t pin){
      int Result = 0;
      analogRead(pin);                      //Switch ADC
      for(int i = 0;i < 16; i++) {          //Read 16 times
        Result = Result + analogRead(pin);  //Sum results
      }
      Result = (int)Result/4;               //Divide by 4 for 12 bit value
      return(Result);
    }

At this moment the resolution of this oversampled analogread is 12-bits. With a little calculation the time to read will take 0,208milliseconds. If I want to increase my resolution more i.e. 13-bit. This will take the measurement 0,832 milliseconds. This seems rather big, so my question is can I do this in another way?
EDIT
Why?
I am trying to position multiple linear actuator using multiple arduino's connected via CAN-bus (the arduino's will not communicate with eachother unless an error occures) THe positioning has to be precise (<0.1mm on a 30 cm rod).
Why is 12 or 13 bit accuracy and/or resolution needed?
12 is probably enough. But I just like to find out the boundaries of the equipment :)
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Probably none 13-bit resolution is probably too high for my application anyways.
Other reason why I like a higher resolution
First couple of voltages I cannot use. My sensor gives a 4 to 20mA signal which i convert with resistor to ground.

Telling us the desired resolution and maximum allowed sampling time would help. Telling us why would help more. ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified. || You cannot usually extend ADC bits indefinitely by oversampling with any great  expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold ....

What desired max sampling time at say 12 bits?

as low as possible, I do not want my loop time over 10 ms (with some safety milliseconds build in). More then a millisec for a measurement is too much.

Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.
I often use the MCP3553 which allows 60sps at 22-bit.

Thanks for the tip. This wouldn't do the trick, the sample rate is too low (16 ms/sample)

Still considerably faster than your 208ms

Think you misread :p, 0,208ms @ 12-bit resolution. But every bit of precisionmore it will take 4 times as long.

As opposed to 16ms at 22bit resolution...

In my tests, the Arduino ADC starts to suffer from accuracy issues when you push it to 500kHz for oversampling, but 250kHz does not suffer from this problem. Also you need some kind of dither/noise, or the oversampling does not really work. I found that pulsing a digital pin with a resistor connected to ground gave me enough noise for the techinque:
https://edwardmallon.wordpress.com/2017/02/27/enhancing-arduinos-adc-resolution-by-dithering-oversampling/

I found that two factors really mattered when I am taking voltage measurements.  First was a 100 uF cap across the analog pin and GND, and second was to make sure my voltage divider was set up to provide a sample voltage right in the middle of the ADC's range.  Never did try to adjust frequency, but I did definitely notice that it wasn't accurate at all until it had taken a few readings (with short delays in between on the order of a few seconds) before starting the 1-minute-per-reading loop.

This is in response to the question.
It is an answer to the extent that it says that

The current method may not work (several reasons given),
There may be better ways to do it, and
Is it necessary?

Addressing these points, or knowing that they have been addressed, is an essential part of arriving at a good solution .
If we knew the desired conversion time and actual desired resolution it would allow better answers.
If we knew what you were trying to do it might help immensely.
ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified.
Apart from the statistical sampling considerations that you are addressing, you cannot usually extend ADC bits indefinitely by oversampling with any great  expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold and acquisition gating and more work.
As you try to squeeze more bits out of the ADC the assumptions become less likely to be consistently valid.
Also, implementation of the analog input circuitry initially becomes important and then immensely important as bits of ADC resolution increase (whether achieved by over sampling or other means).
12 bits  = 0.0244% per step (as you know)
or 1.22 mV steps in a 5V reference system
or 0.81 mV/bit in a 3.3V reference system.
Getting your overall system working to that level of accuracy is possible but usually not achieved.
Any reference you are using will be natively much less accurate than that and those sort of accuracies will require calibration both initially and possibly ongoingly.
Ratiometric systems, where eg the excitation voltage of a bridge also serves as a reference, allow reference accuracy to notionally be perfect (as readings and excitation are the same and move together.
However, ensuring that the voltage at the controllers Aref pin wrt controller Agnd, and the bridge's excitation pin wrt the bridge's ground input are the same  within usefully under 1.22 mV in a 5V 12 bit system (0.6 mV in a 13 bit system, and that the bridge and controller grounds are the same within say a few hundred uV, are an obvious necessity if the 13 bits of resolution are to be meaningful - but unlikely to be achieved without the most exquisite attention to both design & implementation. (Ask me how I know :-).)
Generally, it will be much easier to obtain and maintain ADC resolutions of as many bits as are needed by the use of purpose designed conversion ICs operating as close to the signal source as is reasonably possible. (Or using instrumentation amplifiers to acquire the signals and reliably "convey" them elsewhere.) Knowing desired conversion times and resolutions is a necessary first step.
BUT
Why?
Why is 12 or 13 bit accuracy and/or resolution needed?
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Such requirements - and much more accurate again, certainly do exist.
But knowing what the actual application is may help with decisions of how to meet it.

Thank you for your detailed answer! questions answered in my original post

you squeezing run time, I wonder, how much time you may save,
if instead of looping to measure you do 16 times +=
and >>2 instead /4
an another optimization to make  an own analog read function, it would be pretty simple based on original, so in additional you save time to call read function 16 times with all CPU overhead for each call.
lastly, in your own read function run the ADC in free run mode and accumulate a significant amount of data samples for oversampling.

Please improve your post by checking your grammar and semantics. I tried to edit it, but I don't get what you want to express.


text:
Using embedXcode with Adafruit Trinket
I'm trying to get set up to develop for the Adafruit Trinket on a Mac running the OS X El Capitan beta (10.11.2 beta) with Xcode and embedXcode. I've got the Arduino IDE downloaded from arduino.cc installed as /Applications/ArduinoCC.app. I'm able to build and run the Blink example using the Arduino IDE and Xcode appears to also work (it knows about the Trinket, and claims to successfully load the code) but it does not blink. The red LED on pin 1 just continues to pulse at about 10 Hz as if it was waiting to for code to be loaded.
Any ideas what could be going on or how I can troubleshoot further?
Updates:

I've made the changes to avrdude.conf suggested by the folks at Adafruit to accommodate the erase timing requirements of the Trinket.
I got a response on the Adafruit forum that suggested going back to 1.6.5 as many people have been reporting problems with 1.6.6 breaking things. However, I can program the board using 1.6.6.

Maybe F_CPU is set incorrect. Try increasing the delay between turning the led on and off, and see if the led blinks slower.


text:
Update code over Ethernet?
I've got an Arduino faithfully monitoring our sewer lift pump. It talks to the world over Ethernet (with PoE). I'm wondering if there is any way to load new code over the Ethernet as well. Any ideas if this could be done?
I imagine that using the boot loader might be out of the question, but perhaps it would be possible to upload a new system image – perhaps onto an SD card – and then use a modified boot loader to discover the new image and copy it into place.

You can update it in any way you can figure out how to write in the bootloader.

Do you know of any documentation (or descriptions) of how the boot loader works – short of reading the code?

It works exactly as described in Atmel's datasheets and application notes.

See http://forum.arduino.cc/index.php?topic=16812.msg122380#msg122380 or even better https://github.com/LowPowerLab/DualOptiboot.

A bootloader to network-boot might be too large to leave enough code space for your application. Your second suggestion sounds more workable - to collect & verify the entire new image in secondary storage first, then call a storage-to-flash boot loader. You really don't want to start loading an image that then suffers damage in transit, or to have the link go down mid-download. The likely only way out of that is a site-visit. Saving first lets you confirm the integrity of the new image before you start over-writing any of the old one.


text:
help with arduino programming
my project involves:
1 ultrasonic sensor.
1 servo motor.
3 leds.
when a person comes in range of ultrasonic sensor (7 to 20),servo turns by 150 degree.
then ultrasonic sensor check again if the person is in range, if yes then led1 turns on for 10sec n turns off, still if the person in in range then led2 turns on for 10sec and turns off, still if the person is in range then led3 turns on for 10sec and this keep on repeating for the leds(led1, led2, led3 but servo is still in 150)
once detected and the person is not detected the leds should not glow and servo should return to 0
code:
if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 {
  if ((distance2>7)&&(distance2 <= 20))
   {
   digitalWrite(led1,HIGH);
   delay(1000);
   digitalWrite(led1,LOW);
   }
  if ((distance1>7)&&(distance1 <= 20))
   {
   digitalWrite(led2,HIGH);
   delay(1000);
   digitalWrite(led2,LOW);
   }
   if ((distance1>7)&&(distance1 <= 20))
   {
   digitalWrite(led3,HIGH);
   delay(1000);
   digitalWrite(led3,LOW);
   }
else
{
 myservo1.write(0);
  }

but this code does not work the way i want.
it blink the leds even when there is no person in range.
need help in programing so that the leds blink only when ultrasonic detects the person in range and stops when person is not detected.
thank u in advance

The code indentation looks odd, check if the curly braces are balanced the way you intend. especially line 6 opens a new block that is unconditional. The else in line 25 belongs to the if in line 19.

Your indenting doesn't match your code.
Right after the very first if (without an else), you have a new open brace ({). This looks wrong:
if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 { // <<<< What is this?

The very very final else matches the very very final if - certainly not the first if!
Also, what is the difference between distance1 and distance2? You only have one ultrasonic sensor - there is only one distance!
EDIT:
I think what you need to do is use loop() more effectively. At the moment, you're pausing in the middle of your code, rather than letting the rest of the code work and using millis(). That function returns the number of milliseconds since the program started - which you can use for your problem (with a little mathematics):
EDIT 2:
I've added a little extra code to play different tunes depending on the current state. It uses the library at http://www.rhydolabz.com/other-widgets-c-205_124/mini-mp3-player-module-p-2159.html
static unsigned lastMilli = 0;
static byte lastLED = 0;
static const byte LEDs[] = { led1, led2, led3 };

distance1 = // Whatever you call to get the distance...
if (distance1>7) && (distance1<=20)) { // Too close?
   if (lastMilli==0) {       // Is this new???
       lastMilli = millis(); // Yes! Record that...
       mysero.write(150);    // ...and set servo.
   } // if
   unsigned delay = millis() - lastMilli; // Get how long it's been
   byte which = delay / 10000 % 3;        // Which LED / tune?
   byte LED = LEDs[which];                // Which LED?
   if (LED != lastLED) {                  // Has LED changed?
       if (lastLED!=0) {
           digitalWrite(lastLED, LOW);    // Yes! Stop that one
       } // if
       mp3_single_loop(true);             // Play forever!
       mp3_single_play(which+1);          // Play "mp3/000#.mp3"
       lastLED = LED;
       digitalWrite(LED, HIGH);           // And start the new one
   } // if
} // if
else if (lastMillis!=0) { // They're gone!
    digitalWrite(lastLED, LOW); // No LED
    myservo.write(0);           // No servo
    lastMilli = 0;              // So start again
    lastLED = 0;
    mp3_stop();
} // else

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


text:
character on 16X2 LCD is not visible properly
i am using 16x2 LCD with arduino nano for my project.
when i connect arduino nano with usb power supply from pc or any mobile changer adapter then all the character on LCD is visible properly. But when i connect it with 5V regulated power to arduino nano than character on LCD is not visible properly (characters are visible and project is running fine but pixel which needs to be hidden are also little darker so it characters aren’t visible properly)
i have connected Vee pin of LCD with ground for maximum brightness.

Disconnect Vee from GND and wire it up properly with a potentiometer. It doesn't set the brightness - it sets the bias point for displaying the different pixels in the matrix.

then how it is working fine when i connect USB as power supply.

Different voltages.


text:
How to sync multiple arduinos?
I'm making a posture control experiment in which a series of images (stimuli) are presented to a person and I'm trying to measure the displacement of this person as a result of these stimuli. To do so I'm planning to use 3 Arduinos:
1) "Arduino Tx 1": an Arduino nano with an Xbee shield and an MPU unit attached for sensing displacement. This implementation has to be wireless because the subject must be able to move freely.
2) "Arduino Tx 2": an arduino uno for reading an analog signal that indicates when an image (stimulus) is presented to the person
3) "Arduino Rx": an arduino uno connected to a computer and reading data from both "Arduino Tx 1" and "Arduino Tx 2"
I want to make sure that signals coming from "Arduino Tx 1" and "Arduino Tx 2" are synchronised. That is: if an image is presented at t=t0 (signal sensed by "Arduino Tx 2") then I want to be able to tell that the displacement sensed by "Arduino Tx 1" at t=t0+dt corresponds to this stimulus.
My question is: is it possible to ensure that signals coming from "Arduino Tx 1" and "Arduino Tx 2" are synchronised when read by "Arduino Rx"?

What do you mean "are synchronized"? If you get signals that arrive at the same moment, that would be synchronized wouldn't it?

What level of accuracy are we talking about? What is the reaction time? 1-10 ms would imply with 1% error 10-100 us. I would suggest broadcasting a start message, measuring and then fetching the results.

Why is the image indication analog?
You should get a digital pulse (with interrupt) to time when the picture is shown. And you can then, from that point measure the displacement.

Even though one is wireless and hence will be using a battery: can't the Arduinos simply send continuously?

Have TX2 also emit an infrared pulse that initiates the timing reported by TX1.  TX1 should report dt rather than t_tx1.
The common real-time clocks for for Arduino report at 1 second resolution, which does not sound as if it is accurate enough for your needs.

Most RTC devices also have a 32,768kHz output which should be more than precise enough.

IMHO the delays are negligible if you are detecting times in the range of milliseconds. Just give us some more info (e.g. what is the maximum error you can tolerate).
In any case you can implement a round-trip-time estimator. For instance

RX sends a packet (or even just a single byte) to one TX to set it in "RTT measuring mode".
TX reads the packet and sends an ack. This is required for avoiding errors when the TX is busy doing something else.
When the ACK is received, the RX sends a message and starts measuring the time.
When TX receives the message, immediately sends back a reply
When RX receives the reply, stops the timer. The communication delay is half the time measured

Just repeat this procedure for both TX1 and TX2; this way you will have an estimate on how long it takes to receive a message from each of them. Then, when you receive a packet, you know how much time passed since it was transmitted (and so you can synchronize them)


text:
Problems powering standalone arduino with USB powerbank
I've successfully migrated and ATMEL328P-UP microcontroller from the Arduino Uno Board to a breaboard, following these instructions: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. Everything is OK, the bootloader worked and code is already uploaded an running.
The ATMEL is connected to a pair of sensors, and all the system works using 3.3V. And here comes the problem: I'm using a 5V USB power bank to power up everything. When I make this connection:
USB Power Bank @ 5V -> Arduino Uno board (without the microcontroller) -> 3.3 V Output from the board -> ATMEL/Sensors on the breadboard
everything works just fine! Now I decided to replace the Arduino uno board with an LM317 voltage regulator which gives me the 3.3V needed. The connection is this:
USB Power Bank @ 5V -> LM317 with 3.3 V output -> ATMEL/Sensors on the breadboard
and nothing happens! Is as if there wasn't enough current to feed the ATMEL nor the sensors. I've checked the Vcc/GND pins of the sensors and the ATMEL and they're all getting the required 3.3 V, but for some reason the system seems to be OFF.
What could be happening? I'm sure the USB power bank is at full charge, so it should be able to supply enough current. Any suggestions?
Thanks guys!

Can you show the actual LM317 circuit?

How have you connected ground through the board and breadboard?

@MikaelPatel: I'm not going through the board in the second case (it's been replaced by the voltage regulator).

@Majenko The LM317 circuit is as the one shown here. In my case R2 = 1.6K and R1 = 1K to ensure that Vout = 1.25(1+1.6/1) = 3.25 V* . Connections are as follows: +5 V Power Bank -> Vin LM317; Vout LM317 -> Vcc ATMEL (pin 7)

According to the datasheet, the LM317 needs an input voltage 3v higher than the output. Since 6.3<5, there's not enough margin for the LM317.
You can use an AMS117 LDO @3.3, which only needs an input of 3.9v to operate. I find these modules very handy. If the MCU has some tolerances, you can likely get away with using a diode or two in series with the 5v rail to drop it down; the actual forward voltage fluctuates slightly on load, but it will likely stay in the acceptable range for your MCU.
you can also use a switch-mode regulator, commonly sold as "buck converters" on ebay, to more efficiently reduce the voltage. This is the way to go over linear regulator like the 317 if you power your project from batteries or have concerns about heat. I go through a lot of these style converters, and they seem to work very well.

Indeed! According to the datasheet, 5V are not enough for the LM317; so even if the LM317 delivers the required 3.3 V it might be an issue with the current?... I'll give the AMS117 a go and let you know!

your current would be fine, if it weren't the LM317 would be hot. It's the voltage drop from the 317's darlington pair transistors that cause the problem. The AMS117 uses only a single pnp transistor and thus drop less voltage.


text:
How to set 60 min beeper?
I am trying to make a device that will register latency and number of shocks for passive avoidance behavior in drosophila. My device has two buttons green and red. I press green when I put a fruit fly into the test tube. When drosophila enters the shock compartment I press the red button to give electric shock through Grass stimulator. My Arduino registers latencies or elapsed time from pressing green button and subsequent presses red button and the number of shocks (presses of the red button). This part works just fine, however, I want to have a 60 sec beeper as the test runs only 1 min. This part does not work. The beeper counts 60 seconds from the starting of the device,  not from the press of the green button.  I am not sure what I am doing wrong.
Here is the code:

#include <LiquidCrystal.h>

/*
  Super-basic stopwatch using millis();
*/

unsigned long start, finished, elapsed;
unsigned long startTime;
unsigned long endTime;
unsigned long duration;
byte timerRunning;
int switchPin = 3;              // switch is connected to pin 3
int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int buttonPresses = 0;          // how many times the button has been pressed
const int buz = 13;
unsigned long delayStart = 0; // the time the delay started
//bool timerRunning = false; // true if still waiting for delay to finish
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd (9, 8, 7, 6, 5, 4);

void setup()
{
  lcd.begin(16, 2);
  //lcd.setCursor (0,0);
  //lcd.print("resetting");
  lcd.setCursor (3,1);
  lcd.print("resseting");
  delay(3000);
  lcd.clear();
  lcd.setCursor (0,0);
  lcd.print ("Latency= ");
lcd.setCursor (0,1);
lcd.print ("Shocks= ");
  Serial.begin(9600);
  pinMode(2, INPUT); // start button
  pinMode (2, INPUT_PULLUP);
  pinMode (buz,OUTPUT);
  pinMode(switchPin, INPUT);    // Set the switch pin as input
  digitalWrite(buz, LOW); // turn buz off
  delayStart = millis();   // start delay
  //delayRunning = true; // not finished yet
  buttonState = digitalRead(switchPin);   // read the initial state
  Serial.println("Press 'Green' for Start/Reset, 'Red' for Shocks");
}

void displayResult()
{
  float h,m,s,ms;
  unsigned long over;
  elapsed=finished-start;
  h=int(elapsed/3600000);
  over=elapsed%3600000;
  m=int(over/60000);
  over=over%60000;
  s=int(over/1000);
  ms=over%1000;
  Serial.print("Elapsed time: ");
  Serial.println(elapsed);
  Serial.print("Latency: ");
  Serial.print(m,0);
  Serial.print("m ");
  Serial.print(s,0);
  Serial.print("s ");
  Serial.print(ms,0);
  Serial.println("ms");
  Serial.print("Shocks: ");
  Serial.print(buttonPresses);
  Serial.println(" time(s)");
  lcd.setCursor (8,0);
  lcd.print(m,0);
  lcd.print("m");
  lcd.print(s,0);
  lcd.print("s");
  lcd.print(ms,0);
  lcd.setCursor (7,1);
  lcd.print(buttonPresses);

}

void loop()

    {float h,m,s,ms;

  if (digitalRead(2) == HIGH);{ // button pressed & timer not running already
  start=millis();
  lcd.setCursor (7,1);
  lcd.print("           ");
  buttonPresses=0;
  lcd.print(buttonPresses);
    Serial.println("Started");
    lcd.setCursor (8,0);
    lcd.print("           ");
    lcd.print("Start...");
  lcd.print(buttonPresses);
  lcd.setCursor (8,0);
    lcd.noBlink();

  delay(300);

  // Turn on the blinking cursor:

  lcd.blink();
    delay(200); // for debounce

  }

  if (digitalRead(3)==HIGH)
  { lcd.noBlink();
  lcd.setCursor (9,0);
   lcd.print("        ");
    finished=millis();
    delay(200); // for debounce
    buttonPresses++;
    displayResult();
    delay(200);}

    if (timerRunning && ((millis() - delayStart) >= 60000)) {
    //timerRunning = false; // // prevent this code being run more then once
    digitalWrite(buz, HIGH); // turn buz on
   // tone(buz, 1000); // Send 1KHz sound signal...
  delay(1000);        // ...for 1 sec
  noTone(buz);     // Stop sound...
  delay(1000);        // ...for 1sec
    Serial.println("Turned buz on");
    lcd.setCursor (10,1);
    lcd.print("1min");
  }}

Check the blink without delay example. Set a variable when you start the test, and check against the current time (minus 60 seconds) to start the beeper.

your code is really badly formatted, which can easily lead to errors ... for example, you should not have two braces }} next to each other

The best place to start, is with the BlinkWithoutDelay example in the IDE.
Once you master that concept, you may be tempted to start several different timers. With enough timers, your code will start to look like a bowl of spaghetti.
Next, you could build a generic function which would help to reduce the "spaghetti code".
I would favour an OOP approach.
// Sketch uses 910 bytes (2%) of program storage space.
// Global variables use 18 bytes (0%) of dynamic memory.
// Arduino Uno, IDE 1.8.9
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds){
      m_timerActive = 0;
      m_previousMillis = 0;
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

};

// Make a copy of the object to work with.
MillisTimer SixtySecondTimer(60000);

void setup(){

  // Call this function from a button click
  // to start the 60 second timer.
  SixtySecondTimer.Start();

  // Timer complete indicator.
  pinMode(LED_BUILTIN, OUTPUT);

}

void loop(){

  // Call the update function as fast as possible.
  if(SixtySecondTimer.Update()){
    digitalWrite(LED_BUILTIN, HIGH);
    SixtySecondTimer.Stop();
  }

}

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


text:
I need help with my final year project
I am building a project using bluetooth control as well as an ir sensor. The logic behind my program is when I press a key I want my robot to execute a series of program and while the program is executing if an obstacle is detected I need the motors to stop and then continue from the same point after the obstacle is removed. I am uploading my code for ref.
#include <Servo.h>
#include <AFMotor.h>
#include <Servo.h>
int obstaclePin = 12;
int obstacle = LOW;
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);
Servo myservo1;
Servo myservo2;
int pos = 0;

char bt='S';
void setup()
{
  Serial.begin(9600);
  pinMode(obstaclePin,INPUT);
  myservo1.attach(10);
  myservo2.attach(9);
  motor1.setSpeed(100);
  motor2.setSpeed(100);
  motor3.setSpeed(100);
  motor4.setSpeed(100);
  Stop();
}

void loop() {
 bt=Serial.read();
  if(bt=='F')
{
  forward();
  delay(2000);
  backward();
  delay(2000);
  left();
  delay(2000);
  right();
  delay(2000);
  Stop();
}

if(bt=='B')
{
forward();
 delay(8000);
 left();
 delay(1500);
 ServoControl();
 delay(500);
 backward();
 delay(1000);
 right();
 delay(3000);
 forward();
 delay(8000);
 Stop();
}

if(bt=='L')
{
 forward();
 delay(10000);
 left();
 delay(1500);
 ServoControl();
 delay(500);
 backward();
 delay(1000);
 right();
 delay(3000);
 forward();
 delay(10000);
 Stop();
}

if(bt=='R')
{
 forward();
 delay(12000);
 left();
 delay(1500);
 ServoControl();
 delay(500);
 backward();
 delay(1000);
 right();
 delay(3000);
 forward();
 delay(12000);
 Stop();
}

if(bt=='S')
{
 Stop();
}
if(bt=='O')
{
  servoOpen();
}
if(bt=='C')
{
  servoCLose();

}

}
void forward()
{
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

void backward()
{
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
}
void left()
{
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
}
void right()
{
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}
void Stop()
{
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
}
void servoOpen()
{
  for (pos = 0; pos <= 100; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo1.write(pos);
    myservo2.write(pos);
  }
}

void servoCLose()
{

  for (pos = 100; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo1.write(pos);
    myservo2.write(pos);
  }
}
void ServoControl()
{
  for (pos = 0; pos <= 100; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo1.write(pos);
    myservo2.write(pos);
    delay(40);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 100; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo1.write(pos);
    myservo2.write(pos);
    delay(40);                       // waits 15ms for the servo to reach the position
  }
}
void obstacleD()
{
  obstacle = digitalRead(obstaclePin);
   if(obstacle == HIGH)
  {
    Stop();
  }
}

I don't know where to add the obstacle detection so it would work like an interrupt. the main problem I was experiencing was that whenever I tried running the code on my Arduino it would completely change the logic and noting would work even if I put the command in the serial monitor until an obstacle was detected. I'm a newbie at programming and using Arduino.

You need to learn about Finite State Machines. delay() is your enemy.

"Work like an interrupt" can mean two different things: one is that obstacle detection (OD) can be an actual interrupt, the other is that instead of blocking with delay we can use other timing mechanisms. The problem with delay is that if OD is an actual interrupt after the ISR runs you'll drop right back into delay, which when you're running into a wall, not cool. That's why the comment regarding FSMs and looking in to other ways to "do something for awhile" w/o using delay.

Your main problem is, that you are using many blocking calls, especially delay(). During that the Arduino cannot do anything else. You need to use a non-blocking coding style, doing multiple things one after another in fast succession. Here the style from the BlinkWithoutDelay example using millis() is very useful. There are lots of tutorials about that online (on this site or many others), so I will not go into detail, how that works.

Quick fix: If you just need a quick fix and the code structure of your project is not relevant for your grade, you can do the following:
Replace the obstacleD() function with one, that will also wait for a specific time and also check the IR sensor during that time. Something like this:
void obstacleD(unsigned long wait, void (*function)(void)){
    unsigned long start_time = millis();
    unsigned long already_waited = 0;
    while(millis()-start_time < wait-already_waited){
        if(digitalRead(obstaclePin)){
            already_waited += millis()-start_time;
            Stop();
            while(digitalRead(obstaclePin));
            start_time = millis();
            function();
        }
    }
}

Then in the rest of your code instead of delay(1000) (or similar) you are calling
obstacleD(1000, forward);

The first parameter is the waiting time, the second one is the function, that was lastly called (since we need to recall it, if an obstacle is found and then removed). We are noting the start time of the function into start_time. The first while loop will loop, until we waited as long as provided (difference between current time and start time will then be greater than the wait time minus the time we already waited). In that loop we are checking the IR sensor pin. If it reads HIGH, we add the elapsed time to our already_waited variable, stop and then loop while the IR sensor pin stays high. When the pin goes LOW again we leave this inner while loop, update to our new start_time and again execute the function to start the motors again. The code should continue the path like without an obstacle, even if multiple time an obstacle is placed during one path element.
Note, that the above code is not tested in any way. You might need to make minor changes.

Interrupt quick fix: You could implement the stopping on obstacle with an actual interrupt. Something like this:
void obstacle_detected(){
    while(digitalRead(obstaclePin));
}

void setup(){
    ...
    attachInterrupt(obstaclePin, obstacle_detected, RISING);
}

Though this is also not a good solution, since you totally block any other code, until the obstacle is removed, including receiving serial data (one byte is received by the hardware, but that has to be read by an interrupt. If another byte is send before that, the original byte is lost). Normally you would only set a flag in the ISR (interrupt service routine), but your main code isn't ready for using that flag correctly.

The good-structured-code way: To get the desired behavior with a good structured code, you need to completely restructure/rewrite your current code. As mentioned above you need to create a code, that does not block for long times, but only does things, if they need to be done at that time, and otherwise execute other code. You need to learn the usage of millis().
Also your code would greatly benefit from a Finite State Machine (FSM), as Majenko already wrote in a comment. Here you first draw a diagram with your complete behavior structure, divided up into states, that do exactly one thing. The states are connected by state transitions (arrows from one state to another) (and we can even repeat a state by drawing an arrow from a state back to itself). Then you can convert that into a code structure using a state variable (integer or enum) and a switch statement, where each case has the code for one state. You can look at my answer to this question for more information. Or you can search for the term "finite state machine" or "FSM" on this site or google (for google you maybe should add "arduino" to the search query to get relevant results).
All in all you would create a code, that handles the wanted behavior without any hardware interrupts (not really needed here) and which is easily extendable, without getting problems with the program flow.

Note:
The for loop in servoCLose() is totally unnecessary. You don't have any delay to slow it down, so it will go to the end position in way less time, than the motor needs to even start moving. Just use Servo.write() one single time there with the desired angle. That is enough, unless you want it to move slowly. Then you would need a way to delay between the writes (either delay() or with millis(), depending on your then overall approach).

(I'd pedantically point out that delay doesn't disable interrupts, the issue being that once the ISR is done it just goes back to delaying :)

@DaveNewton Though the proposed interrupt solution involves staying in the interrupt, until the obstacle was removed. That might be very long, thus not that good. I mentioned the point of maybe not graded code structure.


text:
ESP8266 Wemos D1 Mini Pro v2.0 - Load sharing and battery
I have a simple question regarding the new version of Wemos D1 Mini Pro v2.0 and specifically about its load sharing circuitry. Schematic is here :
https://www.wemos.cc/en/latest/_static/files/sch_d1_mini_pro_v2.0.0.pdf
Battery charger is TP4054 and there's a load sharing configuration based on P-MOSFET CJ2301.
My question is what happens if you do NOT connect any battery.
It seems that the charging LED faintly flashes, and positive voltage appears in positive battery terminal. Moreover, voltage appears in A0 and ADC input (provided that SJ1 is connected), while someone would expect a zero voltage there, since there's no battery.
Am I missing something here? Is there any way to fix this issue?

If you are not using battery, the SJ1 should be cut off so that A0 can be used as the input source to the ADC.

I have test it and you are right. When you plug power into the USB connector with no battery connected to the Wemos D1 mini Pro v2.0.0 (provided BAT-A0 is connected) and I have got 1023, the maximum read into A0, when it should be 0.
I think a related problem is that when you are running with battery and you connect a charger into the USB port you can not read the battery voltage, you are getting always 1023, like if the battery was fully charged. So, you can use A0 to monitor battery voltage when discharging, but not when charging.


text:
Can a KCPI-3101 be replaced with an Arduino?
I'm planning to use a KPCI-3101 Keithley with a computer to creat a DAS with a sensor to show the data on computer
can i replace the Card and computer with an Arduino?

can you elaborate more? what sensor are you trying to use? If you planing to only do trivial computations and sensor readings it may be good.

Geosig-ve53 is the seismic sensor

An Arduino's ADC cannot sample fast enough to sustain 225ksps over 16 channels. That equates to a total of 3.6Msps.  The Arduino can manage something like 120ksps in total.
That's not to say there aren't microcontrollers that can't do that kind of speed - there are.  The PIC32MZ, for instance, can run at 15Msps (although it's somewhat buggy still) and there are many other microcontrollers.
The main bottleneck though is in the communication between the microcontroller and the computer.  Regardless of the sampling speed of an Arduino the serial interface is too slow for high speed sampling. Even at its practical maximum of around 2Mbps it gives you 200000 bytes per second, which with 2 bytes per sample would be 100ksps maximum throughput, not taking into account any protocol overheads.
So that's where having a PCI card is a big advantage. A 32-bit (or even 64-bit on PCI64) 66MHz direct channel to the CPU means you can shift considerably more data. And having the computer perform DMA access means that smooth data transfers without the CPU needing to be involved can be performed.

You can't replace the KPCI-3101 Keithley's 16 channels of 12 bit 225kS/s with an Arduino.


text:
When does the pulsein() function start counting?
I have an Arduino Pro mini 3.3V, 8 mHz and I want to use the pulsein() function for a low-going pulse. My question: Does the timer start when the function senses a LOW on the input pin, or when the function senses a high-to-low transition, or either?
Code snippet:
pinMode(3,INPUT); // Signal input to Arduino from pin 2 on LM339  - D3
int pwindow = 6000; // Maximum timeout value for pulsewidth
long pcounterA = 0; // Unfiltered Pulse Width of Channel 1
pcounterA = pulseIn(3,LOW,pwindow);
Serial.print(pcounterA);

Thanks for any help.
JT

Slight nitpick: mHz is millihertz; MHz is megahertz.  That's a difference of 9 orders of magnitude.

According the official Arduino Reference: PulseIn
Fragment:

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. Gives up and returns 0 if no pulse starts
  within a specified time out.

Further, from that same page, **Please also note that if the pin is already high when the function is called, it will wait for the pin to go LOW and then HIGH before it starts counting. **


text:
serial communication between arduino to 89c51 with gsm
I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.

Use I2C, SPI or any other protocol?

There is always software serial.

The Arduino Uno only has one (hardware) serial port. Since you need two, you have in principle two solutions:

Use a software serial, this will work only for low speed transmissions. You can download this as a library.
Use an Arduino (or other microcontroller) which has more than one hardware serial port, like the Arduino Mega which has 4.


text:
One time execution of a variable incrementation
As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand.
Any tips or help will be greatly appreciated!
PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.
      void playMan (int ncycles, int mSpeed) {

        switch (selectMel) {
        case 1:
          if (ncycles > 0) {
            tone(12, NOTE_B7, mSpeed);
            delay(100);
            tone(12, NOTE_B5, mSpeed);
            delay(100);
            tone(12, NOTE_B3, mSpeed);
            delay(100);
            tone(12, NOTE_B1, mSpeed);
            delay(100);
            ncycles--;
            break;
          case 2:
            if (millis() % 100 == 0) {
              if (switchVar == 1) {
                ncycles += 5;
                switchVar = 0;
              }
              Serial << ncycles << endl;
            }
            break;
          default:
            break;
          }
        }
      }

See http://www.gammon.com.au/switches.
Basically you need to detect the transition between the switch not being pressed before, and now being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.

Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?

To clarify, you increment once on a transition, note when you did this (eg, by calling millis() ) and then ignore any further transitions for, say 10 ms.

Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ? From what I understand debouncing is only helpful as a means of toggling from one state to another without the "noise" of outside factors, or is there something I am missing entirely?

I have just found a solution to my own question, albeit not without your kind help Mr. Gammon, thank you!


text:
How to hook up an LED strip to an Arduino
I want to add 6 LEDs  under my Arduino case and have the Arduino Uno pulsate the colors. How do I do this?

What have you tried so far? Which part of your code is not working? Can you post your code and a schematic? Thanks.

i dont have a code or schematic that is my problem

https://learn.adafruit.com/rgb-led-strips/usage

Depends on what they are and how much you don't know :-)
I'd suggest starting off by looking at the tutorials for NeoPixels and DotStars on Adafruit's site – that should give you a general idea of how things work. Then take a look at the FastLED library, it supports a large number of LED strips and has some decent examples.
The FastLED examples that will show up in the Arduino IDE after you have installed the library.
Once you've gotten as far as identifying the strip you have and reading some of the basic tutorials and trying out some of the examples you'll either know how to do it or have some much more specific questions to ask.
OK, after looking at the info on Amazon and looking more closely at the strip (and the price). I don't think these are individually addressable LEDs. More likely the RGB lines are grounds. So what you would do is to provide a +12V supply on the 12V line and ground one or more the RGB lines to turn on that LED. You could probably control brightness with PWM (pulse width modulation, turning them on and off quickly). The catch here is that the current draw will be more than the Arduino can sink and it's at 12V – two quick ways to kill your board in one tidy package.
You'll need to do more research on this to get the details right, but I think you could use a transistor to do the switching (to protect your Arduino for the 12 V and from the current necessary to drive the LEDs). You would connect an Arduino pin to the base of the transistor to control it. You'd need to select a transistor that can handle the current of all of the LEDs of that color. As a guess I'd figure 60 mA per LED at full brightness (for each color) – this is based on NeoPixels running at 5 V so I could be way off.
If I'm right that these are not individually addressable then the programming would be relatively easy – just turn on the output to turn on the color.
I'd start off by cutting off a strip of the LEDs to experiment with. Use the 12V supply that came with them and see what happens when you connect 12 V to the 12V line and ground one of the color lines. It doesn't look like there is a resistor to limit current, so you should add one to hold the current down. I think the LEDs would be wired in parallel, so you'd be looking at needing to supply 6 times the individual LED current. To be safe you could start at around 20 mA and use a 100Ω 1W resistor – you can find an LED resistor calculator here, be sure to select the parallel calculation and use a low current to start with to be safe.
Once you know that the strip works the way you think it does, try adding a transistor to control each color. Then when you've got that working, hook up to the Arduino. Just remember that you will also need to respect the Arduino's current and voltage limits on the digital pins.

what do you mean identifying the strip?

http://www.amazon.com/gp/product/B00MA397GI?psc=1&redirect=true&ref_=oh_aui_detailpage_o06_s00

@laxus There are two ways to control your strip. a) You somehow make the Arduino behave as the controller or b) You send the Infrared commands with your arduino to emulate the remote.


text:
Upload already compiled code on Linux CLI without arduino-cli
I have a sketch for an Arduino Nano. I'm compiling it on my build server and get these 3 files:

project.bin.elf
project.bin.hex
project.bin.with_bootloader.hex

Now I need to be able to upload/flash them onto the board (connected via a serial interface) without arduino-cli. Mainly because I can't install it via apt-get which means I'd have to start jumping through loops to be able to use it (stuff like keeping it up to date, installing, etc. on hundreds of devices).
So I was wondering if there are any tools in the debian repositories I can use to upload the compiled sketch and if so how.
I've been looking for a solution and came across several answers and topic but strangely enough all either use arduino-cli, other specialized tools or link to dead pages or pages that no longer contain the answer.
Examples:

How to compile, upload and monitor via the Linux command line?
Compiling sketch vi command line

avrdude is your friend.

upload Blink to Nano from IDE and then copy the avrdude command from IDE console and modify it to upload the project.bin.hex file

@Juraj do I see this command on the Windows version too? Alternatively could I get arduino-cli to output the command? Because I have test boards available I can install anything on. (I just can't get it on every board)

turn on verbose mode

Use avrdude.
The command format is simple, assuming you have installed it from the Linux repositories:
avrdude -carduino -patmega328p -P/dev/ttyUSB0 -b115200 -Uflash:w:/path/to/project.bin.hex:i

Depending on what bootloader is installed in your nano you may need to change the  baud rate (-b115200) to 57600. Also, of course, the USB device should be set to what your board actually identifies as.
The breakdown of the command is:
-c<programmer type>
-p<part name>
-P<port>
-b<baud rate>
-U<instruction>

The programmer type, part name and baud rate can all be gleaned from the boards.txt file in the AVR core files.  For example, for the Nano:
nano.upload.protocol=arduino
nano.menu.cpu.atmega328.upload.speed=115200
nano.menu.cpu.atmega328.build.mcu=atmega328p

relate to -c -b and -p respectively.  The instruction will always be the same, and means "Write to flash the following file in IHEX8 format".  "flash" is the destination memory, "w" is the write command, and ":i" at the end defines the expected file format.
On a Linux computer with avrdude installed you can find much more information with man avrdude.

That answers my question, but since SE is meant as an enciclopedia of sorts, I think it would be beneficial to explain how you figure out that command line call for other boards. (And also because I managed to find a similar call after some playing around and watching the processes in htop while trying to flash with arduino-cli)

@BrainStone Like that?

Excellent. Thank you very much

if you are unsure of the settings that you should use, then you can use the Arduino IDE to determine them .... in settings, turn on show verbose output during upload .... then upload any sketch .... in the status panel in the Arduino IDE you will see the correct avrdude command line .... something like E:\arduino-nightly\hardware\tools\avr/bin/avrdude -CE:\arduino-nightly\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\xxxxx\AppData\Local\Temp\build3bb8345d83cedc585b1cb6c2216554cb3.tmp/BasicSerial.ino.hex:i


text:
How do I write and read .pem certs from SPIFFS?
I'm trying to construct a program for an ESP32 Dev Board that writes my AWS cert files [(https://medium.com/@flynam/securing-your-iot-device-using-ssl-4643110ab901)][1] to SPIFFS so that I can later read them from another program that's loaded via an OTA (over the air) updater.
However, it looks like something is being lost during the read & write process.  The certs will work if hardcoded, but error out when loaded from SPIFFS.
Hardcoding to a variable like the one in Secrets.h works:
static const char AWS_CERT_CA[] PROGMEM
But when writing that to a file and printing via Serial.println I'm missing things like R"EOF( and )EOF" which I'm assuming are hidden characters.
Does this have to do with writing as a .txt file or perhaps storing in the wrong kind of variable?
The code below is missing some functions, but the relevant portions are below.
I should also mention I am very much a C++ beginner so there's probably some things off with my code above and beyond my initial question.
main.ino
// ...
#include "Secrets.h" // contains cert files info
#include <WiFiClientSecure.h>
#include <MQTTClient.h>
#include <ArduinoJson.h>
#include "Esp.h"
#include "SPIFFS.h"
// ...

// Where I'm wanting to store my cert files
static char AWS_CERT_CA_FILEPATH[] = "/AWS_CERT_CA.txt";
static char AWS_CERT_CRT_FILEPATH[] = "/AWS_CERT_CRT.txt";
static char AWS_CERT_PRIVATE_FILEPATH[] = "/AWS_CERT_PRIVATE.txt";

// Save a file to the designated location
void saveFile(const char* filePath, const char* contents){
  if(!SPIFFS.exists(filePath)) {
      File writeLog = SPIFFS.open(filePath, FILE_WRITE);
      if(!writeLog) {
          Serial.print("Couldn't open ");
          Serial.println(filePath);
      } else {
        writeLog.print(contents);
        delay(50);
        Serial.print(contents);
        Serial.print(" written to file system");
        Serial.println(filePath);
        delay(50);
        writeLog.close();
      }
      delay(50);

  } else {
    Serial.print(filePath);
    Serial.print(" already exists.  Call remove() first.");
  }
}

// Remove files if they are there already, then save anew
void saveCerts(){

  SPIFFS.remove(AWS_CERT_CA_FILEPATH);
  SPIFFS.remove(AWS_CERT_CRT_FILEPATH);
  SPIFFS.remove(AWS_CERT_PRIVATE_FILEPATH);

  saveFile(AWS_CERT_CA_FILEPATH, AWS_CERT_CA);
  saveFile(AWS_CERT_CRT_FILEPATH, AWS_CERT_CRT);
  saveFile(AWS_CERT_PRIVATE_FILEPATH, AWS_CERT_PRIVATE);
}

// Load the file into char* ...
// Loads, but perhaps not into the correct format?
bool loadFile(const char* filePath, char* buffer){
    File f = SPIFFS.open(filePath, "r");
    if (f && f.size()) {

      Serial.print("Reading ");
      Serial.print(f.size());
      Serial.print(" bytes from file ");
      Serial.println(filePath);

      int pos = 0;
      while (f.available()) {
        buffer[pos] = f.read();
        pos++;
      }

      buffer[pos] = 0;

      f.close();
      return true;

    } else {
      Serial.print("No contents available for ");
      Serial.println(filePath);
      return false;
    }
}

// Allows for creation of correctly size char arrays
int getFileSize(const char* filePath){
    File f = SPIFFS.open(filePath, "r");
    if (f && f.size()) {
      return (int)f.size();

    } else {
      return 0;
    }
}

void connectAWS()
{
  // Need to save these to file
  char AWS_CERT_CA_LOADED[getFileSize(AWS_CERT_CA_FILEPATH)];
  char AWS_CERT_CRT_LOADED[getFileSize(AWS_CERT_CRT_FILEPATH)];
  char AWS_CERT_PRIVATE_LOADED[getFileSize(AWS_CERT_PRIVATE_FILEPATH)];

  loadFile(AWS_CERT_CA_FILEPATH, AWS_CERT_CA_LOADED);
  loadFile(AWS_CERT_CRT_FILEPATH, AWS_CERT_CRT_LOADED);
  loadFile(AWS_CERT_PRIVATE_FILEPATH, AWS_CERT_PRIVATE_LOADED);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  // From here on out is code from tutorials and works when
  // certs are hardcoded

  Serial.println("Connecting to Wi-Fi");

  // TODO Put in some code when auth fails
  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }

  // Configure WiFiClientSecure to use the AWS IoT device credentials
  net.setCACert(AWS_CERT_CA_LOADED);
  net.setCertificate(AWS_CERT_CRT_LOADED);
  net.setPrivateKey(AWS_CERT_PRIVATE_LOADED);

  // Connect to the MQTT broker on the AWS endpoint we defined earlier
  client.begin(AWS_IOT_ENDPOINT, 8883, net);

  // Create a message handler
  client.onMessage(messageHandler);

  Serial.print("Connecting to AWS IOT");

  while (!client.connect(THINGNAME)) {
    Serial.print(".");
    delay(100);
  }

  if(!client.connected()){
    Serial.println("AWS IoT Timeout!");
    return;
  }

  // Subscribe to a topic
  client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);

  Serial.println("AWS IoT Connected!");
}

void setup() {
  Serial.begin(9600);
  SPIFFS.begin();
  saveCerts();
  connectAWS();
  publishMessage();
}

In secrets.h
#include <pgmspace.h>

#define SECRET

// Amazon Root CA 1
static const char AWS_CERT_CA[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
awholebunchofrandomlettersandnumbers
-----END CERTIFICATE-----
)EOF";

// Device Certificate
static const char AWS_CERT_CRT[] PROGMEM = R"KEY(
-----BEGIN CERTIFICATE-----
awholebunchofrandomlettersandnumbers
-----END CERTIFICATE-----

)KEY";

// Device Private Key
static const char AWS_CERT_PRIVATE[] PROGMEM = R"KEY(
-----BEGIN RSA PRIVATE KEY-----
awholebunchofrandomlettersandnumbers
-----END RSA PRIVATE KEY-----
)KEY";

 Print and Error Message
[E][vfs_api.cpp:135] remove(): /AWS_CERT_CRT.txt does not exists or is directory
[E][vfs_api.cpp:135] remove(): /AWS_CERT_PRIVATE.txt does not exists or is directory

-----BEGIN CERTIFICATE-----
someprivatestuffIerased
-----END CERTIFICATE-----
 written to file system/AWS_CERT_CA.txt

-----BEGIN CERTIFICATE-----
someprivatestuffIerased
-----END CERTIFICATE-----
 written to file system/AWS_CERT_CRT.txt

-----BEGIN RSA PRIVATE KEY-----
someprivatestuffIerased
-----END RSA PRIVATE KEY-----
 written to file system/AWS_CERT_PRIVATE.txt
Reading 1189 bytes from file /AWS_CERT_CA.txt
Reading 1221 bytes from file /AWS_CERT_CRT.txt
Reading 1676 bytes from file /AWS_CERT_PRIVATE.txt
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
Connecting to Wi-Fi
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.192, MASK: 255.255.255.0, GW: 192.168.1.1
.Connecting to AWS IOT[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 258252
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[V][ssl_client.cpp:115] start_ssl_client(): Loading CA cert
[V][ssl_client.cpp:163] start_ssl_client(): Loading CRT cert
[V][ssl_client.cpp:170] start_ssl_client(): Loading private key
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[V][ssl_client.cpp:195] start_ssl_client(): Performing the SSL/TLS handshake...
Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered (loopTask)
Core 1 register dump:
PC      : 0x4008c363  PS      : 0x00060036  A0      : 0x8008c458  A1      : 0x3ffb0060
A2      : 0x3ffd9cbc  A3      : 0xbaad5678  A4      : 0x3ffd9cb0  A5      : 0x3ffb0190
A6      : 0x00000001  A7      : 0x00000000  A8      : 0x3ffd9cc8  A9      : 0x3ffd9cb4
A10     : 0x00000001  A11     : 0x3ffd9cb0  A12     : 0x00005640  A13     : 0x00005568
A14     : 0x3ffd9da8  A15     : 0x3ffd9ccc  SAR     : 0x0000001f  EXCCAUSE: 0x00000001
EXCVADDR: 0x00000000  LBEG    : 0x4000c2e0  LEND    : 0x4000c2f6  LCOUNT  : 0xffffffff

Backtrace: 0x4008c363:0x3ffb0060 0x4008c455:0x3ffb0090 0x40084e00:0x3ffb00b0 0x400850a3:0x3ffb00d0 0x400845c8:0x3ffb00f0 0x400f1099:0x3ffb0110 0x400ee30a:0x3ffb0130 0x400eed36:0x3ffb0150 0x400eeda1:0x3ffb0190 0x400ef154:0x3ffb01c0 0x400ef2ff:0x3ffb0240 0x400ef577:0x3⸮

Update
Exception can be fixed by making the variables global, but I now receive a repeating invalid certificate format error.
[ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 256736
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[V][ssl_client.cpp:115] start_ssl_client(): Loading CA cert
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():122]: (-8576) X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -8576
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 256124
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[V][ssl_client.cpp:115] start_ssl_client(): Loading CA cert
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():122]: (-8576) X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected

Update 2
Added the following
// At top of file
#define FORMAT_SPIFFS_IF_FAILED true

// In setup()
if(!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)){
   Serial.println("SPIFFS Mount Failed");
   return;
}

Can you provide a stack decode via https://github.com/me-no-dev/EspExceptionDecoder? It could also be that since you now allocate the buffers for the certificates on the stack of the function, that there's a stack overflow. Given that the error is Stack canary watchpoint triggered this is the most likely cause (a canary is a special value written into the end of the stack to check if it's been overwritten / overflowed). Please try: declare char AWS_CERT_CA_LOADED[] and friends variables as global variables (outside func) with some constant max memory size (2k), then load certs as usual

and retry the handshake.

@MaximilianGerhardt Thanks Maximilian.  That fixed the stack overflow error.  Now I receive an invalid format.  I'll continue to try additional approaches.

invalid format error is thrown by which function exactly? The certificate loading functions? Have you verified their content to be the same as when using static certificates?

@MaximilianGerhardt It seems I needed to format (?) SPIFFS for it to work properly.  Added a bit of code to "Update 2".


text:
AutoConnect module does not broadcast SSID on ESP32 Dev Board
This is my first post so I apologize if I'm missing all required info about my Arduino setup.  I'm a little new to this type of development.
Arduino 1.8.9
ESP32 Dev Module on /dev/cu.SLAB_USBtoUART
Mac OSX High Sierra 10.13.
I'm using the AutoConnect by Hieromon Ikasama v1.1.3 library to create an access point (AP), but the SSID (network name) is not being broadcasted even with the simplest code example.
Why isn't "ESP-78e9" showing up in my network list on my MAC or iPhone?
⸮⸮⸮8Y8⸮
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[E][Preferences.cpp:38] begin(): nvs_open failed: NOT_FOUND
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.192, MASK: 255.255.255.0, GW: 192.168.1.1
WiFi connected: 192.168.1.192 on ESP-78e9

Full code sample below, written with the Arduino IDE
#include <WiFi.h>
#include <WebServer.h>
#include <AutoConnect.h>

WebServer         Server;
AutoConnect       Portal(Server);
AutoConnectConfig Config;

void rootPage() {
  char content[] = "Hello, world";
  Server.send(200, "text/plain", content);
}

void setup() {

  Config.apid = "ESP-" + String((uint32_t)(ESP.getEfuseMac() >> 32), HEX);
  Config.psk = "Password1";
  Portal.config(Config);

  delay(5000);
  Serial.begin(9600);
  Serial.println();

  Server.on("/", rootPage);
  if (Portal.begin()) {
    // Serial.println("WiFi connected: " + WiFi.localIP().toString());
    Serial.println("WiFi connected: " + WiFi.localIP().toString() + " on " + Config.apid);
  }
}

void loop() {
    Portal.handleClient();
}

I've tried looking into why "nvs_open failed: NOT_FOUND" is occurring as that feels like the next step, but can't find any information on how to fix it.
I've also tried this on two boards of the same model.
Any ideas?
** Update **
I've modified the code to include the following, but still no AP and captive portal.
https://hieromon.github.io/AutoConnect/advancedusage.html#on-demand-start-the-captive-portal
According to the link above, that SHOULD start a captive portal before attempting to connect to WiFi.
  Config.autoRise = false;
  Config.immediateStart = true;

Instead I get the debug text here:
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START

Update 2
There may be a bug in the documentation.  I changed "autoRise" to true and the SSID was broadcasted.
  Config.autoRise = true;
  Config.immediateStart = true;

It looks like your ESP32 is already successfully connecting to an access point as a STA (station) and does not start its own Access Point (AP). You probably have already previously configured an SSID and password and the ESP32 is successfully reusing those, so it will not start the Captive Portal (as its own AP).
You should force AutoConnect to start up the Captive Portal or to forget its pre-programmed SSID and password. This can be achieved by On-demand starting of the Captive Portal like described on this page. According to the documentation you should put the following lines in your code (I have not tested this myself):
Config.autoRise = true;
Config.immediateStart = true;
Portal.config(Config);
....
Portal.begin();

NOTE: The documentation actually states Config.autoRise = false but it seems this does not have the desired effect.

Thanks @StarCat .  You'd think that would work according to the docs, but it doesn't.  AP_STOP and then STA_START occurs :/  See update in my post.

You might try to disable your regular Wifi temporarily and see if the portal comes up when the ESP cannot get a Wifi connection itself. What if you connect your browser to the IP address it shows in the serial output?

Thanks for the tips.  Looks like the autoRise = false is a bug and it should be autoRise = true.  I'll mark yours as accepted, but that may fool people in the future.

Thank you. I'll change it in my answer, but this comes from the documentation on the author's website.