Arduino and also EspressIF have really good libraries for UART Serial communication using USB. I've written a custom library based on EspressIF hardwareserial.h
library, available on GitHub here:
To initialize serial communication it can be done like below:
// ----------------------------------------------------
void mSerial::start(int baud) {
if (this->DEBUG_EN) {
if ( this->DEBUG_TO == this->DEBUG_BOTH_USB_UART || this->DEBUG_TO == this->DEBUG_TO_USB ){
Serial.begin(115200);
Serial.println("mSerial started on the USB PORT.");
}
if ( this->DEBUG_TO == this->DEBUG_BOTH_USB_UART || this->DEBUG_TO == this->DEBUG_TO_UART ){
this->UARTserial->begin(baud);
this->UARTserial->println("mSerial started on the UART PORT.");
}
}
}
To receive serial data it can be done like this:
// -----------------------------------------------------------------
bool mSerial::readSerialData(){
this->serialDataReceived = "";
if( Serial.available() ){ // if new data is coming from the HW Serial
while(Serial.available()){
char inChar = Serial.read();
this->serialDataReceived += String(inChar);
}
this->printStr(">");
return true;
}else{
return false;
}
}
and to send serial data like this:
xSemaphoreTake(MemLockSemaphoreSerial, portMAX_DELAY); // enter critical section
this->UARTserial->print(mem);
this->UARTserial->print(str);
this->UARTserial->flush();
xSemaphoreGive(MemLockSemaphoreSerial); // exit critical section
I use a SemaphoreHandle_t
so I can better handle the dual-core activity on the 2 cores of the ESP32.
One final note, when changing core frequency, is needed special handling of serial communication. I've written a function for that purpose alone. The full code can be found here. Below is only the function :
// ****************************************************
bool setMCUclockFrequency(int clockFreq){
xSemaphoreTake(this->McuFreqSemaphore, portMAX_DELAY);
this->McuFrequencyBusy = true;
changeMcuFreq(this-, this->interface->MIN_MCU_FREQUENCY);
this->UARTserial->flush();
setCpuFrequencyMhz(Freq);
this->CURRENT_CLOCK_FREQUENCY=Freq;
if (Freq < 80) {
this->MCU_FREQUENCY_SERIAL_SPEED = 80 / Freq * this->SERIAL_DEFAULT_SPEED;
} else {
this->MCU_FREQUENCY_SERIAL_SPEED = this->SERIAL_DEFAULT_SPEED;
}
this->UARTserial->end();
delay(300);
this->UARTserial->begin(this->MCU_FREQUENCY_SERIAL_SPEED);
this->UARTserial->print("The current Serial Baud speed on the UART Port is ");
this->UARTserial->println(this->MCU_FREQUENCY_SERIAL_SPEED);
this->mserial->printStrln("Setting to min CPU Freq = " + String(getCpuFrequencyMhz()));
this->McuFrequencyBusy = false;
xSemaphoreGive(this->interface->McuFreqSemaphore);
return true;
};