2

I'm using an Adafruit NRF8001 Low Energy Bluetooth module and a Real Time Clock module with my Arduino board. I want to connect to the BLE module using UART to set the clock. I'll also be using UART to set alarms.

I'm not sure which is the best way to take a string from the UART receiver and pull it apart into the hours, minutes, second, etc.

Any ideas? I did look at the Arduino JSON library but it seems a little buggy, and possibly overkill.

Any help would be very much appreciated :)

2

The simplest method is to keep it as a fixed format string with line termination.

Read one line in from serial into a character array (aka C string) and then chop it up. As long as the string is in the correct format you can easily chop it around.

For instance, assume you chose the format YYYY-MM-DD HH:MM:SS\n which is quite common and easy to use, you may have data like this:

char *indata = "2015-08-22 17:23:48\n";

(\n is the new-line character)

Using simple char pointers you can get each substring quite easily:

First slice the string up into the component parts by replacing the separator tokens with character 0:

indata[4] = 0;
indata[7] = 0;
indata[10] = 0;
indata[13] = 0;
indata[16] = 0;

Then you can assign pointers to each segment:

char *year = indata;
char *month = indata + 5;
char *day = indata + 8;
char *hour = indata + 11;
char *minute = indata + 14;
char *second = indata + 17;

Or if you want it as integers, you can pass it straight to atoi:

int year = atoi(indata);
int month = atoi(indata + 5);
int day = atoi(indata + 8);
int hour = atoi(indata + 11);
int minute = atoi(indata + 14);
int second = atoi(indata + 17);

In fact, if passing it direct to atoi() you shouldn't need to even do the first stage, since it will stop parsing at the first non-numeric character.

There are more flexible ways of parsing the string too, using strtok(), but that is somewhat more advanced.

Note that this method is highly intolerant to invalid strings being passed, so you may want to first ensure that a) the string is the right length, and that b) there are the right separator tokens in the right placed, to validate that the string is properly formatted before proceeding.

  • Thank you @Majenjo. This might infact be the easiest way to do it. I can prepend the string with the item I want to update too. E.g. ST to set the clock, A1 to set alarm 1, A2 to set alarm to and so on. – Ian Nebbiolo Aug 22 '15 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.