6 years, 1 month ago.

USBSerial problems

on LPC1768 I'm playing with the USBSerial class.

Why does the below not work. When I send characters to the USBserial port from a terminal the first one gets printed out and then the MCU crashes?

Is it something obvious I am missing?

main

#include "mbed.h"
#include "USBSerial.h"
#include "SerialCMDParser.h"
 
DigitalOut myled(LED1);
USBSerial ser;
SerialCMDParser serCMDParser(ser);


int main() {
    
    while(1) {
        printf("testing usb serial\r\n");
        myled=!myled;
        wait(1);
    }
}

SerialCMDParser.h

#ifndef _SERCMDPARSER_H_
#define _SERCMDPARSER_H_

#include "mbed.h"
#include "USBSerial.h"

class SerialCMDParser
{
private:
    USBSerial &_ser;
     void _Read(void);

public:
    SerialCMDParser(USBSerial &ser);
};

#endif

SerialCMDParser.cpp

#include "mbed.h"
#include "SerialCMDParser.h"

SerialCMDParser::SerialCMDParser(USBSerial &ser)
:_ser(ser)
{
    _ser.printf("starting...\n\r");
    _ser.attach(this, &SerialCMDParser::_Read);
}

void SerialCMDParser::_Read(void){
    printf("reading\r\n");
    while(_ser.readable())
    {
       char c = _ser.getc();
       _ser.putc(c);
    }
}

Some ideas. First, don't use printf in ISR context. So comment out that line in _Read();

https://os.mbed.com/docs/v5.7/reference/mutex.html

USB device can be kind of big make sure main stack is large enough. When mbed dies it usually prints out a message telling you why. I take it you are not seeing any messages on the terminal? You have to make sure the NDEBUG macro is not defined to see messages I think.

I've had issues if I hit the USB serial receive routine too fast. I would make sure you are not sending characters too fast and focus on getting in and getting out of the ISR. I think if you are inside the ISR and another char is received it can cause issues. I would avoid the call to _ser.puc(c) from inside ISR. Instead put characters into a shared volatile buffer and then read them out during normal program flow. There is a circular buffer class inside mbed that's pretty good for this as you can simply keep pushing chars into it.

volatile CircularBuffer<char, kBufferSize> usb_buffer;

Where are you getting this USBSerial class from? I don't think it is part of regular mbed-os. Is this under /features/unsupported? I wonder if "unsupported" is a hint...

https://github.com/ARMmbed/mbed-os/tree/master/features/unsupported/USBDevice

posted by Graham S. 11 Mar 2018
Be the first to answer this question.