Friday, March 2, 2018

globals header file for EFM8 microcontrollers

C functions for EFM8 microcontrollers

You often need to use functions or macros across multiple header files, so it is better to put them in a separate header file for better organization. I use a header file called 'globals' and I will be adding or improving things as I go.

At the moment the file includes some macros such as CPU frequency and some functions.

uint16_t stringToInt(const char* str);
char toUpperCase(char c);
bool isLowerCase(const char c);
char *intToString(int16_t number); 

The function names are self explanatory. They are commented inside the file if you want to use them. Also it is a good idea to comment out the ones that you don't use, to save space.

Convert a string to an integer using a custom function

uint16_t stringToInt(const char* str){
 // When a decimal number (base 10) is multiplied by 10,
 // all of the digits shift left once. So each time a digit is entered,
 // the value of integerValue is shifted to the left and the new digit is added.

 // The character '0' has an ASCII value of 48.
 // So by subtracting 48 from the incomingByte,
 // we get the integer value of that ASCII character.

 uint16_t num = 0;
 uint8_t i = 0;
 bool isNegative = false;

 if(str[i] == '-'){
  isNegative = true;

 while (str[i] && (str[i] >= '0' && str[i] <= '9')){
  num = num * 10 + (str[i] - '0');

 if(isNegative) num = -1 * num;

 return num;

Example: unsigned int date_year = stringToInt("2020"); The returned value will be 2020 as an integer.

Convert an integer number into a string using custom function

char *intToString(int16_t number){
 char xdata string[7] = {0};
 uint8_t xdata length = 0, divide;
 int16_t xdata copyOfNumber = number;
 bool isNegative = false;

 // Find number of digits
 while(copyOfNumber != 0){
  copyOfNumber /= 10;

 copyOfNumber = number;

 if(number < 0){
  isNegative = true;
  copyOfNumber = 0 - copyOfNumber; // negative to positive

 for(divide = length; divide > 0; divide--){
  string[divide-1] = (copyOfNumber % 10) + '0';
  copyOfNumber /= 10;

 if(isNegative) string[0] = '-';

 return string;

Example: char *date_year = intToString(2020); The function will return the string "2020".

Convert a character to uppercase in C

char toUpperCase(char c){
     // Subtract the difference between lowerCase character
     // and it's upperCase character(for example:'a'-'A'=32)

 // If lowercase
 if(c >= 'a' && c <= 'z'){

  // Convert to uppercase
  c -= 32;

    return c;

Example: char a_uppercase = toUppercase('a'); a lowercase will be converted to A uppercase. The function will first check if the character is lowercase before converting it to uppercase.


Version 2.0

No comments:

Post a Comment