Global variable does not work properly C - c

int counter = 0;
int main (void)
{
while(1)
{
counter++;
wait_ms(1000);
if(counter==5) Led_on();
putrsUSART("\n\rUSART: "); putiUSART(counter);
}
}
void putcUSART(u8 data)
{
//Wait until transmitt buffer is empty
while(! (USART1 -> SR & USART_SR_TXE));
//Send the data
USART1->DR = (data & 0xFF);
}
void putsUSART (u8 *data)
{
do{
putcUSART(*data);
}while (*data++);
}
void putiUSART (u32 value)
{
char TXBUFFER[32] = {0};
snprintf(TXBUFFER, sizeof(TXBUFFER), "%d",value);
putsUSART ((u8*)TXBUFFER);
}
I have a problem with the code above. Its so simple that I dont understand why it doesnt work.
If I place "int counter =0" inside the main loop (before while) then the counter counters correctly.
But now he does count but dont start by 0. But for example: 509888073;
I used a ARM32Fxx processor. Could it be a configuration fault?

A stab in the dark is that you're using an embedded compiler and your c-startup is not initialising the bss section. This would give the results you're seeing where local function variables are initialised, but statics are not.
To test if this is true, you can include counter in main again and mark it as static and you'll likely get the same result as it being global...
int main( void )
{
static int counter = 0;
...
Please show your compile + link commands. Ideally a pastebin of the disassembled exe would be good too.

Please check that the counter variable is extended some where and some other thread is using that variable while this thread in wait state. If it is working in inside the main means, this could be the reason

just try replacing the counter name with some other variable just to test if the counter is being used accidentally by some other thread.

Related

Accessing label address outside of function

I'm writing "threaded interpreter" using computed goto. How do I initialize address lookup table to be visible from different functions without additional runtime cost?
Label address is only visible at same function and static lookup table is initialized by compiler in data section without runtime cost at each call. But it's visible only in same function and I want to have another function to have access to it, for example to cache addresses and save lookups in main interpreter code. I can take pointer to this table and store it somewhere, but it will happen every time function is called, and it will get called frequently. Yes, it's just only one mov, but is there another way?
#include <stdio.h>
static void** table_ptr;
// how do i declare static variable and init it later once?
// Tried this. Generates runtime assigns at each call. Not unexpected
// static void** jumps_addr;
int main()
{
// labels are visible only inside the function
// generates runtime assigns at each call
// jumps_addr = (void* [10]){
// this initializes it in static data section, but name is only visible inside this function
static void* jumps_addr[10] = {
[1] = &&operation_print,
};
// want another way instead of this
table_ptr = jumps_addr;
// not optimize this
volatile int opcode = 1;
goto *jumps_addr[opcode];
return 0;
operation_print:;
printf("hello\n");
return 0;
}
void do_some_preprocessing_work(void){
// want access to jumps_addr table here
// without having to store it somewhere
// [do something with table_ptr]
// this is to prevent optimization to explore what compiler does on godbolt.org
// because it will optimize away table_ptr entirely if not used
volatile i = 1;
i += table_ptr[i];
//actual code here will store labbel addrs into opcode struct to save table lookup at runtime
}
The solution might sound unorthodox, but how about not to use any functions, but only goto.
Like so:
#include <stdio.h>
int main()
{
volatile int opcode;
static void* jumps_addr[10] = {
[0] = &&do_some_preprocessing_work,
[1] = &&operation_print
};
opcode = 0;
goto *jumps_addr[opcode];
return 1;
operation_print:
printf("hello\n");
return 0;
do_some_preprocessing_work:
printf("jumps_addr[%i]\n", ++opcode);
goto *jumps_addr[opcode];
return 1;
}

how to call a sub function only once within an periodically function call

I'm beginner with c and have a simple question:
I have a function myfunction() which is called periodically every 100 ms.
Within this function I have to call an other function but only once at the first call at beginn of myfunction(), but no periodically.
void myfunction() // function is called periodically every 100 ms
{
...
mySubfunction(); // this function have to be called only once in the first call of myFunction() and than skipped each time after that.
} ...
How to realize this in c?
Use static? Something along the lines of
void myfunction() // function is called periodically every 100 ms
{
static int once = 1;
if (once) {
mySubfunction();
once = 0;
}
}
The variable once in the example will be initalized only once and retain its value between invocations because of static keyword.
Be aware of implications in multithreaded environment, see this question.
you can have something like
static int flag = 1
void myfunction() // function is called periodically every 100 ms
{
if(flag)
{
mySubfunction();
flag = 0;
}
}
...
on first look task is very simply, can be next code:
void func()
{
static LONG first = TRUE;
if (_InterlockedExchange(&first, FALSE))
{
subfunc();
}
// some code
}
this give 100% guarantee that subfunc() will be called once and only once even if several thread in concurrent call your func()
but what be if // some code depended on result of subfunc ? in this case task become already not trivial. need some synchronization. and here already depended from os or compiler. in Windows, begin from Vista understand this problem and add function InitOnceExecuteOnce - read Using One-Time Initialization
if your subfunc() have no in and out parameters code can be very simply:
BOOL CALLBACK InitOnceCallback(PINIT_ONCE /*InitOnce*/, PVOID /*Parameter*/,PVOID* /*Context*/)
{
subfunc();
return TRUE;
}
void func()
{
static INIT_ONCE once = RTL_RUN_ONCE_INIT;
if (InitOnceExecuteOnce(&once, InitOnceCallback, 0, 0))
{
// somecode
}
// error init
}
also some modern compilers can correct handle static one time initialization. say latest versions of CL. with it code can be next:
void func()
{
static char tag = (subfunc(), 0);
// some code
}
here CL internally call special functions (implemented in CRT) _Init_thread_header, _Init_thread_footer - implementation can be look in crt source code - thread_safe_statics.cpp
This may be more advanced than you're looking for, but you could use function pointers and change which function gets called.
// Function declarations
void mySubfunction(void);
void myNormalfunction(void);
// Function pointer, which can be changed at run time.
static void (*myfunction)(void) = mySubfunction;
void mySubfunction(void)
{
// Do the sub-function stuff.
// Change the function pointer to the normal function.
myfunction = myNormalfunction();
// Do the normal function stuff (if necessary on the first call).
myNormalfunction();
}
void myNormalfunction(void)
{
// Etc.
}
int main(void)
{
int x;
for(x = 0; x < 3; x++)
{
// Call myfunction as you usually would.
myfunction();
}
return 0;
}

Circular Array Stuck in if statements

I am writing firmware for an MSP430 device that uses LEDs and photodiodes to detect specific types on ink. The device scans at about 155us and the samples under the scanner range from velocities of .1m/s to 3.3m/s. The goal of the device is to test for ink and measure the ink (pass) to test (not pass) ratio and turn on a green LED when the ratio is between the corresponding value and turn on a red LED when it is not. I am using static integer arrays to store the values of consecutive passes and test values to the same index number of each array. After the last index of the array, the index is set back to zero and the old values are written over.
GREEN_LED_ON; and similar definitions are port definitions for my MCU and are verified to be correct.
event is the test result. If ink is detected, event=DETECTED and vice versa
test will be the average set by a GUI, but for now it is nothing because I don't have this part of my function working
Normally, I will not have GREEN_LED_ON; etc in the if(event) loops, but I put them there to visual where my code is going wrong. The code seems to get stuck in which ever loop even starts with. For example, if I start with the device over no ink, the LED stays red, and when the device is over ink, the device stays green no matter what. Does anyone have any idea what I am doing wrong and how to fix it?
Notes:
*I also tried changing the while(event)s to if statements and I get the same result
*When I comment the arrays inside the if statements, the code works as expected
*Top version is the current portion of the code and the bottom is what I started with
void display(char event, char test) {
static int size=6;
static int array[6]={0}; //array with number of passes for each n
static int n=0;
static float sum=0;//total number of passes
static float average=0;//average pass rate over n
static int consecpass=0; //consecutive passes
static int consecfail=0; //consecutive fails
static int totalnumberoftests[6]={0}; //total number of tests conducted. Counts the number of passing or failing tests for the nth value
static float counter=1; //used to count the total number of tests
static int flag=0;
if(n==size) n=0;
if (event == DETECTED)
{
if (flag==0)
{
sum=sum-array[n];
counter=counter-totalnumberoftests[n];
array[n]=0;
totalnumberoftests[n]=consecfail;
sum=sum+array[n];
counter=counter+totalnumberoftests[n];
n++;
}
consecfail=0;
consecpass++;
//GREEN_LED_ON;
//RED_LED_OFF;
flag=1;
} if (event==NOT_DETECTED){
if(flag==1)
{
sum=sum-array[n];
counter=counter-totalnumberoftests[n];
array[n]=consecpass;
totalnumberoftests[n]=consecpass;
sum=sum+array[n];
counter=counter+totalnumberoftests[n];
n++;
}
//array[n]=consecpass;
//totalnumberoftests[n]=consecpass;
consecpass=0;
consecfail++;
flag=0;
//GREEN_LED_OFF;
//RED_LED_ON;
}
if (consecpass>8000)
{
sum=sum-array[n];
counter=counter-totalnumberoftests[n];
array[n]=consecpass;
totalnumberoftests[n]=consecpass;
sum=sum+array[n];
counter=counter+totalnumberoftests[n];
n++;
}
if(consecfail>30000)
{
sum=sum-array[n];
counter=counter-totalnumberoftests[n];
array[n]=0;
totalnumberoftests[n]=consecfail;
sum=sum+array[n];
counter=counter+totalnumberoftests[n];
n++;
}
average=sum/counter;
if(average<1 && average >0 )
{
GREEN_LED_ON;
RED_LED_OFF;
}else{
GREEN_LED_OFF;
RED_LED_ON;
}
}
This was what I originally started with:
void display(char event, char test) {
static int size=6;
static int array[6]={0}; //array with number of passes for each n
static int n=0;
static int sum=0;//total number of passes
static double average=0;//average pass rate over n
static int consecpass=0; //consecutive passes
static int consecfail=0; //consecutive fails
static int totalnumberoftests[6]={0}; //total number of tests conducted. Counts the number of passing or failing tests for the nth value
static float counter=0; //used to count the total number of tests
while(n<=size)
{
sum=sum-array[n]; //subtacts the nth value from the total sum of passing tests
counter=counter-totalnumberoftests[n]; //subtracts the nth value of the total number of tests run
if(event == DETECTED)
{
array[n]=0;
totalnumberoftests[n]=consecfail;
consecfail=0;
consecpass++;
GREEN_LED_ON;
RED_LED_OFF;
} if(event==NOT_DETECTED){
array[n]=consecpass;
totalnumberoftests[n]=consecpass;
consecpass=0;
consecfail++;
GREEN_LED_OFF;
RED_LED_ON;
}
sum=sum+array[n];
counter=counter+totalnumberoftests[n];
average=sum/counter;
/*if(average<1)
{
GREEN_LED_ON;
RED_LED_OFF;
}else{
GREEN_LED_OFF;
RED_LED_ON;
}*/
n++;
}
if(n>size) n=0;
}
*When I comment the arrays inside the if statements, the code works as expected
static int size=6;
static int array[6]={0}; //array with number of passes for each n
static int totalnumberoftests[6]={0};
and this
while(n<=size)
When n=6 you pass the array boundary - max index is 5 not 6 for those (min index = 0).
array[n]=0;
totalnumberoftests[n]=consecfail;
That is UB and this may produce invalid behavior.
Change condition in while to n < size.
Anyway this code seems "weird" to me.
To elaborate on my comment, if you are in an event-driven system, I expect there is some code (usually called an "event loop") somewhere that looks like this:
event_loop()
{
while (TRUE)
{
event = get_event_from_someplace(...);
display(...);
}
}
It may be that instead of calling display directly, there was some process where you register the event handler. But the upshot is that there is probably an endless loop in some library code that calls your function over and over and over again. So you don't need the while() in your code.
Your code should be a state machine that keeps track of internal state (using static variables, like you are) and then performs whatever updates are required for each call.
Something like this:
void display(char event, ...)
{
static int consecutive_passes = 0;
static int consecutive_fails = 0;
if (event == DETECTED) {
++consecutive_passes;
}
else if (event == NOT_DETECTED) {
++consecutive_fails;
}
else {
// What else is there?
}
}
The idea is that this code gets called every time there is an event, and it just updates whatever set of things need updating. But there is no while loop, because the calls are coming from the event loop, and that's all the while loop you need.

Counting the number of function calls in an executable

I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:
//file1.c
int main(){
foo1();
return 0;
}
and other C files like:
//file2.c
void foo1(){
foo2();
...
foo2();
}
and
//file3.c
void foo2(){
foo3();
foo3();
foo3();
}
Now I have my final executable a.out and want to know how many times foo3() is called inside foo1().
BTW, I am compiling and running my project on Linux.
You can use 2 global variables (put extern at the places that access the variable outside the file you declare them) :
int foo1_active = 0;
int foo3_counter = 0;
then each time foo1 is called you increment it variable and before the return you decrement it:
void foo1() {
foo1_active++;
...
foo1_active--;
return
}
when foo3 is called you check if foo1 active and if it does you increment the counter:
void foo3() {
if foo1_active > 0 {
foo3_counter++;
}
...
}
You have an ubuntu flag, so I assume you are using gcc. I'd strongly consider adding -pg to your CFLAGS and trying out gprof.
Profiling works by changing how every function in your program is
compiled so that when it is called, it will stash away some
information about where it was called from. From this, the profiler
can figure out what function called it, and can count how many times
it was called. This change is made by the compiler when your program
is compiled with the `-pg' option, which causes every function to call
mcount (or _mcount, or __mcount, depending on the OS and compiler) as
one of its first operations.
You can count function calls using a static variable instead of global variable.
int inc(){
static int counter = 1;
counter++;
return counter;
}
int main(){
int i;
for (i = 0; i < 10; i++)
printf("%d\n", inc());
return 0;
}

Calling main function from another function in C

I have a main function that runs a few functions during initialization and then runs a while loop that waits for commands from the UART.
When I see a specific command (let's say reset), I call a function that returns a value. I want to do the following things:
Save the returned value
Start the main function again with the returned value. The returned value is required during initialization of the functions in main.
I am newbie in C and I am not able to figure out a way save variable value in main.
The way I understand things, you essentially have the following setup:
int main(int argc, char *argv[]) {
int value = something_from_last_reset;
perform_initialization(value);
while(1) {
int next_command = wait_for_command();
if(next_command == RESET_COMMAND) {
value = get_value();
// somehow restart main() with this new value
}
}
return 0;
}
Here's one approach you could take:
// global
int value = some_initial_value;
void event_loop() {
while(1) {
int next_command = wait_for_command();
if(next_command == RESET_COMMAND) {
value = get_value();
return; // break out of the function call
}
}
}
int main(int argc, char *argv[]) {
while(1) {
perform_initialization(value);
event_loop();
}
return 0;
}
This essentially lets you "escape" from the event loop and perform the initialization all over again.
just wrap your main into infinity-loop.
int main(void)
{
int init_val = 0;
while (1)
{
// your code ...
init_val = some_function();
}
}
In theory this is possible, but it kind of breaks paradigms, and repetitively calling a function without ever letting it finish and return will quickly fill up your call stack, unless you take measures to unwind it behind the compiler's back.
A more common solution would be to write your main() function as one giant infinite while {1} loop. You can do all of your operation in an innner loop or whatever, and have clauses such that if you get your desired new value you can fall through to the bottom and loop back, effectively re-running the body of main with the new state.

Resources