Basic

Printing formatted

To print something on a screen you can use usoc_printf. It works similarly as printf of the C standard library. The difference is that it does not have a return value.

#include <stdint.h>
#include "usoc_user_services.h"

int main() {
  for(uint32_t counter=0; counter<10; counter++) {
    usoc_printf("->Hello world :) -> %u\n", counter);
  }

  return 0;
}

The output is either displayed over uart0 or JTAG, depending on how the software was started. Also, the output is buffered until a newline character appears after which then the output will be written.

Another important thing to mention is that this implementation does not support printing floats or doubles. Thus the following code will not output anything.

float value = 3.6;
usoc_printf("%f", value)

Printing formatted to string

With usoc_sprintf you can also print to a string instead to UART or JTAG. The same limitations as for usoc_printf apply.

#include <stdint.h>
#include "usoc_user_services.h"

//buffer to print in
char buffer[128];

int main() {
  for(uint32_t counter=0; counter<10; counter++) {
    usoc_sprintf(buffer, "->Hello world :) -> %u\n", counter);
    usoc_printf(buffer)
  }

  return 0;
}

Memory allocation

As we are programming in C you have to allocate memory for larger data structures by yourself. The Ganymed has 4 MB of global SRAM from which you can allocate at most 1 MB at a time.

You can do it by using the function usoc_user_alloc. It is similar to that one found in the C standard library. It returns a pointer to the memory address containing the block of allocated memory. Note that the allocated memory will not be initialized which means that it will contain arbitrary values.

If the returned pointer is NULL then the memory allocation failed due to a lack of ressources.

An important difference is when you free the memory again. You will have to tell the corresponding function how much memory it has to free. That is why it is important to keep the size information at some place.

#include "usoc_user_services.h"

#define BUFFER_SIZE 128

int main() {
  char* buffer;

  buffer = usoc_user_alloc(BUFFER_SIZE);

  if(buffer == 0) {
    usoc_printf("Memory allocation failed!");
    return -1;
  }

  usoc_sprintf(buffer, "Allocated %d bytes at 0x%08lx\n", BUFFER_SIZE, buffer);
  usoc_printf(buffer);

  return 0;
}

After we are done using the data inside the allocated memory we have to free it again, otherwise it will result in one of the well known memory leaks. It is done by using the function usoc_user_free.

As already explained above you will need to give that function the size of the memory that you want to free. This diverges from the interface of the corresponding function in the C standard library.

Another good practice is to set the pointer to NULL so that it is not accessed accidentally later on.

  usoc_user_free(buffer, BUFFER_SIZE);
  char* = 0;