Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
5 years, 9 months ago.
I want to get the serial number and display it via the LEDs.
I want to get the serial number and display it via the LEDs.
I have this code to get the serial number:
uint32_t sn = microbit_serial_number();
Next I want to convert this to a string and display it via the display.scroll function:
uBit.display.scroll( … sn_as_string ...);
Q1. I don't know how to convert uint32_t sn to a string ?
Q2. What syntax should I use in the uBit.display.scroll() function to display the string ?
Regards, Chris
1 Answer
5 years, 9 months ago.
converting a number to a string is easy, use sprintf(), it's the same as printf but outputs to a buffer.
char buffer[16]; // 16 bytes = enough space for a 15 digit number plus termination, overkill for a single int. int len = sprintf(buffer,"%d",sn); // buffer now contains sn as a null terminated string, // len contains the length of the string.
There is also snprintf() which takes the size of the buffer to use in order to avoid overflowing it. Not needed for a trivial situation like this but handy for more complex situations where the maximum length of the final string is less well known.
However for what you want it's easier than that. MicroBit.getSerial() returns a string of the serial number. I don't have a microbit to test this on but I think the code should be:
#include "MicroBit.h" MicroBit uBit; int main() { uBit.init(); uBit.display.scroll(MicroBit.getSerial()); while(true) { } }
Andy, Thanks for your speedy response and excellent explanation. With your help, I have now successfully converted the serial number and displayed OK. The other option, to display it directly from the MicroBit.getSerial() function - I could not get it to compile. Thanks again, Chris.
Here's my code:
<code>
- include "MicroBit.h"
MicroBit uBit;
int main() { Initialise the micro:bit runtime. uBit.init();
uBit.display.scroll(MicroBit.getSerial()); <- Error: Type name is not allowed
uint32_t sn = microbit_serial_number();
char buffer[16]; 16 bytes = enough space for a 15 digit number plus termination, overkill for a single int. int len = sprintf(buffer,"%d",sn); buffer now contains sn as a null terminated string, len contains the length of the string.
uBit.display.scroll(buffer);
release_fiber(); }
</code>
posted by 18 Mar 2019