Printf in keil for stm32f4-eval2 board - c++

Is there c++ or c code anywhere that will help me use printf in keil uvision 5 for the stm32f4-eval2 board? I know you have to retarget the uarts and usarts but I have not been able to do this without errors even with help from the sites I have found online.
I would like to be able to use the debug printf viewer.
I tried the following link but it did not work: http://www.keil.com/support/man/docs/ulinkpro/ulinkpro_trace_itm_viewer.htm

You are not very specific if you want to print via UART or if you want to print via ITM debug channel. For ITM it is pretty simple. Create a file with the following content and make sure SWO trace is enabled on your debug connection:
#include <stdio.h>
/* Replace next line: Include the device system header file here */
#error "device include file missing"
/* e.g.: #include "STM32F4xx.h" */
#pragma import(__use_no_semihosting_swi)
volatile int ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* CMSIS Debug Input */
int fputc(int c, FILE *f) {
return (ITM_SendChar(c));
}
int fgetc(FILE *f) {
while (ITM_CheckChar() != 1) __NOP();
return (ITM_ReceiveChar());
}
Make sure you tick the "Use MicroLib" option in Options for Target->Target

Related

How to inject environment variables into CPP file using Visual Code and Platform IO?

Just starting with this coming from a JS background.
I am looking into IoT development and wanted to set up my own repo without uploading the SSID and password of my personal WiFi.
Platform IO offers this platformio.ini as I understand to set build_flags.
build_flags =
-D SSID="MySSID"
I don't know how to access them from my CPP file though. I want to inject the value from the build flag SSID into my *.cpp file.
#define SSID
void loop()
{
Serial.println(SSID);
}
The above doesn't write anything to the serial monitor.
What am I doing wrong? The code does compile.
I know it's been two years, and you've probably moved on from this question. However, for anyone else - like myself - who happens across this from a Google search, here is the answer as I've found it:
According to PlatformIO's Dynamic Variables page, you correctly define the build variable so that it exists to C++ (as a macro); i.e., -DSSID="MySSID". What you missed, however, is that the values need to be quoted (and potentially escaped): -DSSID='"MySSID"' so that when you access the macro in C++ it is a const char * string and not an unknown symbol.
See the Warning at the bottom of the page, and note the quotes around the string:
Be careful with special characters in system environment variables on Unix systems, especially when they are used as the value for preprocessor directives. Symbols like $, &, ~, etc must be explicitly escaped, for example:
export WIFI_PASS='\"my\~p\&a\\\$\$\$\$word\"'
It wasn't initially obvious to me either, but it makes sense because the preprocessor will replace SSID with whatever you've defined and makes no assumptions about it or its type at all.
As #Azeem mentioned, you're redefining the SSID to an empty value. Using preprocessor like this, you must first check if the value exist and if not, assign it a default value.
Here is a simple C++ example:
#include <iostream>
#ifndef SSID
#define SSID "(SSID not defined)"
#endif
int main()
{
std::cout << "SSID value: " << SSID << std::endl;
return 0;
}
You can compile and run the code with:
g++ main.cpp -o main && ./main
As you see it prints (SSID not defined).
Now, compiling and running with the following:
g++ main.cpp -o main -DSSID='"Hello, World!"' && ./main
will output: SSID value: Hello, World!
If you want to learn more about preprocessor directives, cplusplus.com has very nice tutorial
Also, don't forget to start your Serial in void setup().

Arduino ports registers in Eclipse are not working

I am building a Arduino application in C with Eclipse and the Arduino plugin. In my old code I used pinMode and digitalWrite. But as you all know, this uses more space. So I am re-building my code now with port manipulation. If you don't know what that is, you can see it here: http://www.arduino.cc/en/Reference/PortManipulation
I will explain what I did.
Where there stands pinMode, I changed it to something like this: DDRD = 0b11111111;
And where there stands digitalWrite, I changed it to PORTD = 0b10000000;
You can see it in my code below.
Eclipse is now giving me the error (highlighting the words DDRD and PORTD with a red line) of symbol not resolved for DDRD and PORTD, but the program is building and running normal. How do I solve this?
#include <avr/io.h>
#include <util/delay.h>
int main()
{
UCSR0B = 0; // disconnect pins 0 and 1 from USART (Serial)
DDRD = 0b11111111; // all pins of port D as output
for(;;)
{
PORTD = 0b10000000; // Pin 7 on
_delay_ms(500); // Wait
}
}
These are multi-level macros which encode direct volatile access to the SFR locations.
They are individually defined in one of an assortment of chip-specific header files which avr/io.h will include when it is informed of the specific CPU variant you are using.
Normally this is done with the -mmcu flag to avr-gcc, for example
-mmcu=atmega328p
However, if the Eclipse plugin does it's own pass through the project sources to try to give you advisory errors, it may not be smart enough to turn that into a define (you can get Eclipse claiming errors even when gcc is happy). To work around that, you may need to explicitly define the cpu type above the include in your code, or in some configuration for Eclipse. For example:
#ifndef __AVR_ATmega328P__
#define __AVR_ATmega328P__
#endif
#include <avr/io.h>
Note that this may cause problems if you later change the processor type! And even as is, it's a little iffy as there are two potential names for each processor.
I have faced the same problem. This is what solved for me in Eclipse.
From project explorer right click on the active project > Index > Rebuild

put code executed by GDB

I have small question. Is it possible in C/C++ to put bit of codes that would interact a bit more with GDB ?
Let say I have a function like
void gdb_print(const char*);
This would print information in gdb while it executes! If it's not possible it would be awesome. Would be simple to track some information, and faster in some way!
I need something like this, because we're writing some plugins, and info from cout or cerr are not going to the console at all. So it would be something discrete. Also, could add some stuff like:
#ifdef __DEBUG__
#define debug_msg(x) gdb_print(x)
#else
#define debug_msg(x)
#endif
If it doesn't exist, let me know what you think about this!
I need something like this, because we're writing some plugins, and info from cout or cerr are not going to the console at all.
You can always write to console with:
FILE *console = fopen("/dev/tty", "w");
if (console != NULL) fprintf(console, "Your debug message\n");
I don't know of a method to write specifically to the terminal where GDB is running (which could well be different terminal from which the program itself was invoked).
try redirecting the stderr and stdout to a file using freopen. see this
This is a sample code to redirect stdout to a file in runtime:
/* freopen example: redirecting stdout */
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}
static int gdb = 0;
void gdb_print(char const * msg) {
if(gdb) printf("\tGDB: %s\n", msg);
}
When you load your program up in gdb, set a breakpoint in main, then set gdb to a non-zero value. This isn't the cleanest solution (and certainly not automated) but I think it'll give you what you're looking for. Be sure to use the per-processor to remove the calls in non-debug builds (no sense in having all those extra compares that'll never evaluate to true).

Printing output on the Output Window in Visual C++ IDE

How do I print on the output window in Visual C++? The project that I am working on isn't of a console window project type. That's when I build and run it, it doesn't open a console window. Instead, it opens a win32 application, which isn't built by me. I am just adding things to it.
I am pretty new to C++ and because I couldn't print variables out on any console, it makes it very hard for me to debug.
Since the Visual Studio 2010 project doesn't launch console when I build and run it, can I still print outputs such as variables and others on the Output window of the IDE?
Thanks for any help.
You can use OutputDebugString("..."); to print to the Output window of Visual Studio. You have to #include <windows.h> though.
I have written a portable TRACE macro.
On MS-Windows, it is based on OutputDebugString as indicated by other answers.
Here I share my work:
#ifdef ENABLE_TRACE
# ifdef _MSC_VER
# include <windows.h>
# include <sstream>
# define TRACE(x) \
do { std::stringstream s; s << (x); \
OutputDebugString(s.str().c_str()); \
} while(0)
# else
# include <iostream>
# define TRACE(x) std::clog << (x)
# endif // or std::cerr << (x) << std::flush
#else
# define TRACE(x)
#endif
example:
#define ENABLE_TRACE //can depend on _DEBUG or NDEBUG macros
#include "my_above_trace_header.h"
int main (void)
{
int v1 = 123;
double v2 = 456.789;
TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
}
Please feel free to give any improvements/suggestions/contributions ;-)
Instead of printing to the Output window in VS as indicated by other answers, I prefer to create a console window in my GUI apps, then use regular printf or cout to write debugging info to it. This has the benefit that you can do it even when you run without the debugger.
See this site for a simple function that sets up a console.
I have used this in the past, although not with a win32 application. You could give it a shot though :)
http://www.cplusplus.com/forum/lounge/17371/
You can use the Windows function OutputDebugString (see here) to send output to debuggers. These outputs are shown in the VS output window. You can also watch these outputs with external applications, e.g. DebugView.
Remember to remove these statements from your production code if you don't want other people to see these debug messages (which would otherwise be possible using tools like DebugView...)

Is there a TRACE statement for basic win32 C++?

In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?
_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.
Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. Thanks to Thomas Rizos for the original:
// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873
#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#ifdef _DEBUG
#define TRACEMAXSTRING 1024
char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
va_list args;
va_start(args,format);
int nBuf;
nBuf = _vsnprintf(szBuffer,
TRACEMAXSTRING,
format,
args);
va_end(args);
_RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
&strrchr(__FILE__,'\\')[1],__LINE__); \
_RPT0(_CRT_WARN,szBuffer); \
TRACE
#else
// Remove for release mode
#define TRACE ((void)0)
#define TRACEF ((void)0)
#endif
#endif // __TRACE_H__850CE873
From the msdn docs, Macros for Reporting:
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.
There is also OutputDebugString. However that will not be removed when compiling release.
Trace macros that provide messages with source code link, run-time callstack information, and function prototype information with parameter values:
Extended Trace: Trace macros for Win32
I just use something like this (from memory, not tested at all...)
#define TRACE(msg) {\
std::ostringstream ss; \
ss << msg << "\n"; \
OutputDebugString(msg.str()); \
}
And then I can write things like :-
TRACE("MyClass::MyFunction returned " << value << " with data=" << some.data);
You can wrap that in some #ifdefs to remove it in release builds easily enough.
I found that using the _RPT() macro will also work with a C source file in Visual Studio 2005. This article Debugging with Visual Studio 2005/2008: Logging and Tracing provides an overview of TRACE, _RPT, and other logging type macros.
I generate a line for a log file called the ASSRTLOG which contains logs and when writing the log to the file, I also do the following source code line:
_RPT1(_CRT_WARN, "ASSRTLOG: %s", szLog1);
This line puts the same log that is going into the log file into the output window of the Visual Studio 2005 IDE.
You might be interested in the mechanics behind the approach we are using for logging. We have a function PifLogAbort() which accepts a series of arguments that are then used to generate a log. These arguments include the name of the file where the log is being generated along with the line number. The macro looks like this:
#define NHPOS_ASSERT_TEXT(x, txt) if (!(x)) { PifLogAbort( (UCHAR *) #x , (UCHAR *) __FILE__ , (UCHAR *) txt , __LINE__ );}
and the function prototype for PifLogAbort() look like this:
PifLogNoAbort(UCHAR *lpCondition, UCHAR *lpFilename, UCHAR *lpFunctionname, ULONG ulLineNo)
and to use the macro we will insert a line like this:
NHPOS_ASSERT_TEXT(sBRetCode >= 0, "CliEtkTimeIn(): EtkTimeIn() returned error");
What this macro will do is that if the return code is less than 0 (the assertion fails), a log will be generated with the provided text. The log includes the condition that generated the log along with file name and line number.
The function PifLogAbort() generates logs with a specified length and treats the output file as a circular buffer. The logs have a time and date stamp as well.
In those cases where we want to generate the descriptive text dynamically at run time, perhaps to provide the actual error code value, we use the sprintf() function with a buffer as in the following code sequence:
if (sErrorSave != STUB_BM_DOWN) {
char xBuff[128];
sprintf(xBuff, "CstSendBMasterFH: CstComReadStatus() - 0x%x, sError = %d", usCstComReadStatus, CliMsg.sError);
NHPOS_ASSERT_TEXT((sErrorSave == STUB_BM_DOWN), xBuff);
}
If we want the logs to not be generated, all we need to do is to go to the single header file where the macro is defined and define it to be nothing then recompile. However we have found that these logs can be very valuable when investigating field issues and are especially useful during integration testing.
Windows Events are a potential replacement for TRACE macros, depending on your particular scenario. The code gets compiled into both Debug and Release configurations. Event tracing can then be dynamically enabled and disabled, displayed in real-time, or dumped on a client's machine for later diagnosis. The traces can be correlated with trace information gathered from other parts of the OS as well.
If you merely need to dump information whenever code reaches certain checkpoints, together with variable content, stack traces, or caller names, Visual Studio's Tracepoints are a non-intrusive option to do so.