I am learning how to effectively use Leonardo/Micro's USB CDC serial port for stuff. I need some help figuring out how to mimic UNO's restart when serial port opens.
After some experimentation, I realized that opening Leonardo's USB CDC serial port won't reset the processor. OK. I have to find software way to do it.
What I tried was using if(Serial). According to the description, Serial==TRUE when serial port opens:
I tried this with the ASCII table example code:
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
pinMode(30,OUTPUT);
digitalWrite(30,LOW);
}
// first visible ASCIIcharacter '!' is number 33:
int thisByte = 33;
// you can also write ASCII characters in single quotes.
// for example. '!' is the same as 33, so you could also use this:
//int thisByte = '!';
void loop() {
if (thisByte==33) {
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
digitalWrite(30,HIGH);
delay(500);
digitalWrite(30,LOW);
// prints title with ending line break
Serial.println("ASCII Table ~ Character Map");
}
// prints value unaltered, i.e. the raw binary version of the
// byte. The serial monitor interprets all bytes as
// ASCII, so 33, the first number, will show up as '!'
Serial.write(thisByte);
Serial.print(", dec: ");
// prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Serial.print() and Serial.println(),
// so no modifier is needed:
Serial.print(thisByte);
// But you can declare the modifier for decimal if you want to.
//this also works if you uncomment it:
// Serial.print(thisByte, DEC);
Serial.print(", hex: ");
// prints value as string in hexadecimal (base 16):
Serial.print(thisByte, HEX);
Serial.print(", oct: ");
// prints value as string in octal (base 8);
Serial.print(thisByte, OCT);
Serial.print(", bin: ");
// prints value as string in binary (base 2)
// also prints ending line break:
Serial.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop:
if(thisByte == 126) { // you could also use if (thisByte == '~') {
// This loop loops forever and does nothing
thisByte=33;
while (Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
}
// go on to the next character
thisByte++;
}
My prototype board uses TXLED pin (D30) so don't be alarmed.
I was trying to let Micro wait until Serial disconnects and then wait for it reopen to reprint the ASCII table. Unfortunately this only works once immediately following a sketch upload. The LED on D30 blinks and I get the whole ASCII table. If I subsequently close and reopen the serial port monitor, I get some partial table and the LED is not blinking. I guess it never detects Serial becoming FALSE.
Without modification to the ASCII table code, I get nothing after I open serial monitor a second time.
What did I do wrong?