I have been using the console to print (through UART) it has always worked fine but for some reason every time I use sprintf
it seems to lock up the system and not allow me to print the string value or any other string in a buffer.
This is the part of my code that contributes to it.I am using MPLAB which has the harmony framework and uses FreeRTOS.
#include "app.h"
#include <stdio.h>
#include <string.h>
#include "system/console/sys_console.h"
#include "peripheral\sercom\usart\plib_sercom_usart_common.h"
#include "system/console/src/sys_console_uart.h"
#include "peripheral\port\plib_port.h"
#include "interrupts.h"
#include "peripheral\sercom\i2c_master\plib_sercom1_i2c_master.h"
#include "MC3416_Accel.h"
SYS_CONSOLE_HANDLE New_Console;
uint8_t limit = 0;
static char tilt_string[20];
void Acc_Task (void){
if (limit < 1)
{
limit++;
mc3416_accel_init();
mc3416_accel_read_tilt();
double tilt = mc3416_accel_get_tilt();
while (SYS_CONSOLE_Status(New_Console) != SYS_STATUS_READY)
{}
int result = sprintf(tilt_string,"%.2f",tilt);
SYS_CONSOLE_Write(New_Console, tilt_string, strlen(tilt_string));
}
}
//The accelerometer initialize function calls on a function that sets the accel to wake_mode (i2c communication) and uses this function to send a message when finished.
/***************************************************************************
Function to send a message to the console
****************************************************************************/
void mc3416_send_message(const char *message)
{
SYS_CONSOLE_Write(New_Console, message ,strlen(message));
while(SYS_CONSOLE_Status(New_Console) != SYS_STATUS_READY)
{
}
}
I can see that my value does come and gets changed into a string (through debugging) but for some reason it doesn't allow anything to happen after.
I have tried snprintf
and also not printing the string from sprintf
but something else after calling sprintf
it still does not work. Please help
I wrote an elementary way to convert the double to a string (doubleToString(tilt,tilt_string,3);) and it does work and allows everything else to work so I thought it was safe to assume the while loop worked ok. I placed it in the same place I had sprintf.
void intToString(int num, char *str) {
int i = 0;
if (num == 0) {
str[i++] = '0';
} else {
if (num < 0) {
str[i++] = '-';
num = -num;
}
int divisor = 1;
while (num / divisor > 0) {
divisor *= 10;
}
divisor /= 10;
while (divisor > 0) {
int digit = num / divisor;
str[i++] = '0' + digit;
num %= divisor;
divisor /= 10;
}
}
str[i] = '\0';
}
void doubleToString(double num, char *str, int precision) {
int intPart = (int)num;
intToString(intPart, str);
while (*str != '\0') {
str++;
}
if (precision > 0) {
*str++ = '.';
}
double fracPart = num - intPart;
for (int i = 0; i < precision; ++i) {
fracPart *= 10;
int digit = (int)fracPart;
*str++ = '0' + digit;
fracPart -= digit;
}
*str = '\0';
}