Software delay using C [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This code just calculates the software delay but whenever I try running the code it throws the following errors.Thanks in advance
error: called object is not a function or function pointer
error:expected identifier or '(' before numeric constant
#include<stdio.h>
#define delay 12800
struct my_time
{
int seconds;
int minutes;
int hours;
};
void display(struct my_time *t);
void delay(void);
void update(struct my_time *t);
int main()
{
struct my_time systime;
systime.hours=0;
systime.minutes=0;
systime.seconds=0;
while (1)
{
update(&systime);
display(&systime);
}
return 0;
}
void update(struct my_time *t){
t->seconds++;
if(t->seconds==60){
t->seconds=0;
t->minutes++;
}
if(t-> minutes==60){
t->minutes=0;
t->hours++;
}
if(t->hours==24) t->hours=0;
delay();
}
void display(struct my_time *t){
printf("%02d: ", t->hours);
printf("%02d:",t->minutes);
printf("%02d\n",t->seconds);
}
void delay(void){
long int t;
for(t=0;t<delay;t++);
}

you have defined delay to be 12800. in the line below:
#define delay 12800
in preprocessor time, preprocessor pass on your code and replace each delay he finds with 12800. so you function call : delay() becomes, 12800()! this is invalid hence the error you have got.
defines are written in uppecase letters always!
e.g. use this:
#define DELAY_T 12800

You've defined a delay macro. This will replace every instance of delay in the program (except inside strings). void delay(void); becomes void 12800(void); and so on.
To avoid this, the convention is to use all caps for macros: #define DELAY 12800.
However, there's no need for a macro. Use a constant integer. const int DELAY = 12800; It effectively does the same thing, and it's safer.

Related

What would make rand() return the same value for threads even if it is protected by a mutex?

I am looking to generate random values for 3 threads running in a freeRTOS environment. Knowing that rand() is not thread-safe I use a mutex to protect it. In addition, I call srand() only once. What should I consider when trying to solve this issue?
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "FreeRTOS.h"
#include "semphr.h"
#include "sensorDriver.h"
SemaphoreHandle_t semaphoreMutexDriver;
uint16_t sensorValue;
void sensorDriver_initialize()
{
srand(time(NULL));
semaphoreMutexDriver = xSemaphoreCreateMutex();
}
void getValue()
{
if (xSemaphoreTake(semaphoreMutexDriver, portMAX_DELAY))
{
sensorValue = (uint16_t)(rand() % 50);
xSemaphoreGive(semaphoreMutexDriver);
}
}
uint16_t sensorDriver_getValue()
{
getValue();
return sensorValue;
}
More code can be added upon request.
UPDATE 1
Tried making the sensorValue local to the function, like that:
uint16_t firstSensorDriver_getValue()
{
if (xSemaphoreTake(semaphoreMutexDriver, portMAX_DELAY))
{
uint16_t sensorValue = (uint16_t)(rand() % 50);
xSemaphoreGive(semaphoreMutexDriver);
return sensorValue;
}
}
Did not do the trick (if better suggestions implementation wise, please do not hesitate), also the thread puts the value into a struct after getting it, not sure if this helps. (each thread in its own struct).
UPDATE 2
Here is the struct and how the value is saved:
struct firstSensor
{
uint16_t firstSensorValue;
EventGroupHandle_t meassureEventGroup;
EventGroupHandle_t dataReadyEventGroup;
};
void firstSensor_fetchSensorValue(FirstSensor self)
{
self->firstSensorValue = sensorDriver_getValue();
}
UPDATE 3
Here is an example of the first and second thread/struct implementation
#ifndef FIRSTSENSOR_H
#define FIRSTSENSOR_H
typedef struct firstSensor* FirstSensor;
FirstSensor firstSensor_create(UBaseType_t taskPriority, EventGroupHandle_t
eventGroupMeassure, EventGroupHandle_t eventGroupDataReady);
uint16_t firstSensor_getSensorValue(FirstSensor self);
void firstSensor_destroySensor(FirstSensor self);
#endif
and similarly second thread header and source file
#ifndef SECONDSENSOR_H
#define SECONDSENSOR_H
typedef struct secondSensor* SecondSensor;
SecondSensor secondSensor_create(UBaseType_t taskPriority, EventGroupHandle_t
eventGroupMeassure, EventGroupHandle_t eventGroupDataReady);
uint16_t secondSensor_getSensorValue(SecondSensor self);
void secondSensor_destroySensor(SecondSensor self);
#endif
And implementation
struct secondSensor
{
uint16_t secondSensorValue;
EventGroupHandle_t meassureEventGroup;
EventGroupHandle_t dataReadyEventGroup;
};
void secondSensor_fetchSensorValue(SecondSensor self)
{
self->secondSensorValue = firstSensorDriver_getValue();
}
void secondSensor_task(void* instance)
{
EventBits_t eventBitsMeasure;
SecondSensor self = (SecondSensor*)instance;
for (;;)
{
eventBitsMeasure = xEventGroupWaitBits(self->meassureEventGroup, BIT_SECOND_SENSOR, pdTRUE, pdTRUE, portMAX_DELAY);
if ((eventBitsMeasure & BIT_SECOND_SENSOR) == BIT_SECOND_SENSOR)
{
secondSensor_fetchSensorValue(self);
xEventGroupSetBits(self->dataReadyEventGroup, BIT_SECOND_SENSOR);
}
}
}
UPDATE 4
Well technically they are random for each emm, run so to say, but they are same within the same run. Picture below on the left is what my small program is printing on the right simple random print.
UPDATE 5
Another weird thing is that everytime I run the code I get the same sequence of numbers as if stand is never called (even though it is), even if I seed the srand() with time(NULL) + clock() which should be different everytime. Maybe it can help...
so, not sure entirely why, yet, it only worked only if srand() was called 3 times (each time the task runs, but outside the infinite loop so that it runs only once, in the function that xTaskCreate is provided with upon creation of the task) instead only once in the main(). If it was called only once in the main function, the random values were as if the srand() function was never called. I suppose (only suppose, don't have any evidence yet) that it is because of the fact that each task has its own stack.
Thanks to everyone assisting in the troubleshooting...

corruption of the heap, error in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
well I dont need to explain too much, this function get this error at the line I marked all the time, only in this function there are allocations of memoery, please help me find out where is the issue...(read some other topics with that here, but nothing helped me solve it)
ERROR:"Windows has triggered a breakpoint in sapProject.exe.
This may be due to a corruption of the heap, which indicates a bug in sapProject.exe or any of the DLLs it has loaded.
"
void storeTok(char * lexem,int line,enum keywords typeof)
{
int ind;
if(tokens.size%100==0)
{
if(tokens.size==0)
{
tokens.ptrInd=-1;
tokens.first=(node*)malloc(sizeof(node));
tokens.first->back = NULL;
tokens.first->next = NULL;
tokens.last=tokens.first;
}
else
{
node * nodenz=(node*)malloc(sizeof(node)); /error is here
nodenz->back = tokens.last;
nodenz->next = NULL;
tokens.last->next=nodenz;
tokens.last=tokens.last->next;
tokens.last=nodenz;
}
}
// general
ind=tokens.size-(tokens.size/100)*100;
tokens.last->tokens[ind].type=typeof;
tokens.last->tokens[ind].linen=line;
tokens.last->tokens[ind].lexema=lexem;
tokens.size++;
}
Thanks!
edit(except this, there is also a header(and thats it..):
typedef struct token
{
char * lexema ;
int linen;
enum keywords type;
}token;
typedef struct node
{
struct node * next,*back;
token tokens [50];
}node;
typedef struct LL
{
struct node * last, *first, * ptr;
int size,ptrInd;
}LL;
LL tokens;
void storeTok(char * lexem,int line,enum keywords typeof);
main func:
void main()
{
int i;
for(i=0;i<26;++i)
{
storeTok("blabla",1,END);
storeTok("sdfasd",1,START);
storeTok("sfadds",1,IF);
storeTok("gvdfd",1,THEN);
storeTok("dfsfd",1,ELSE);
}
storeTok("dfsfd",1,EOF_);
}
That line is probably the victim. The code that corrupted the heap is elsewhere. You can use a tool like valgrind or a similar tool to find it. (Or give us enough code to replicate the error and we can track it down for you.)

How to verify that a function X() is getting called from function Y() not from function Z()? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Could you Please provide me any example How to verify that a function X() is getting called from function Y() not from function Z()?
Using 'C' or assembly language?
Thanks in advance.
Update:02-03-2015
Suppose kernel source code there are so many drivers calling the same function, like driver source code of SPI (Serial Phepheral Interface) and GPIO (General Purpose Input Output) is calling same function say "bzero()".
void bzero(void *s, size_t n);
I am going to test SPI and GPIO driver (driver code can not be modified). For that I have written the test driver. I can only call the function exposed from my test driver.
uint8_t SPI_read_write(uint8_t byte_out, char *s) // Function 1
{
bzero(s,sizeof(struct_global1));
return byte_in;
}
uint8_t GPIO_read_write(uint8_t byte_out, char *s)// Function 2
{
bzero(s,sizeof(struct_global2));
return byte_in;
}
int main()// Test driver
{
SPI_read_write(arg1,arg2);// When I call this function from test driver it will call bzero
}
Both the finction SPI_read_write() and GPIO_read_write() function calls the "bzero" function.
I need to ensure that "bzero" is getting called at any instance from SPI_read_write() function only.
Updates 15-04-2017
I am not able to get which line is unclear? some function fun1() can be called from N number of other function. how to determine which function called fun1()?
Probably it is related to stack, link register...
There is no way to determine the name of the function that is calling your function. This is entirely by design, because functions are intended to provide an abstraction that encapsulates a computation or an activity that is independent of the invocation site. Therefore, if you want to know which function is calling your function, the caller needs to provide this information.
C99-compliant compilers provide a way to determine the name of the current function, which can be used to pass to the target function, like this:
#define X() x(__func__)
void x(const char* caller) {
printf("x() is called from %s()\n", caller);
}
void y() {
X();
}
void z() {
X();
}
The above prints
x() is called from y()
x() is called from z()
Demo.
#include <execinfo.h>
#include <stdio.h>
void print_function(void *p) {
char cmd[128];
FILE *fp;
snprintf(cmd, sizeof(cmd), "addr2line -e %s -f %p", "print_caller", p);
fp = popen(cmd, "r");
if (fp) {
char buf[128];
while (fgets(buf, sizeof(buf), fp)) {
printf("%s", buf);
}
}
}
void Y()
{
print_function(__builtin_return_address(0));
}
void X()
{
Y();
}
int main()
{
X();
return 0;
}
$ gcc -g -o print_caller print_caller.c
$ ./print_caller
X
/home/viswesn/print_caller.c:24
I would also recommend you to view the man page of BACKTRACE() which may provide you more insight on how to view the functions that were called before getting in to the current funciton.

Using a function pointer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a function in C that is crashing my code and I'm having a hard time figuring out what is going on. I have a function that looks like this:
#define cond int
void Enqueue(cond (*cond_func)());
cond read() {
return IsEmpty(some_global); // Returns a 1 or a 0 as an int
}
Enqueue(&read);
However, when running the above, it segfaults as soon as Enqueue is called. It doesn't even execute anything inside the function. I ran gdb and it just shows it dying as soon as Enqueue is called- no statements are processed within it. Any idea what is going on? Any help would be appreciated.
Can you give more information about the code because according to my interpretation the code is working fine.I have tried this-
#define cond int
void Enqueue(cond (*cond_func)());
cond read()
{
int some_global=1;
return IsEmpty(some_global); // Returns a 1 or a 0 as an int
}
int IsEmpty()
{
return 1;
}
void Enqueue(cond (*cond_func)())
{
printf("Perfect");
return 0;
}
int main()
{
Enqueue(&read);
return 0;
}
And it is working fine.
#define cond int
was meant to be:
typedef int cond;
Although defining an alias for your function pointer might be much more reasonable here, for example:
typedef int (*FncPtr)(void);
int read() {
printf("reading...");
}
void foo(FncPtr f) {
(*f)();
}
int main() {
foo(read);
return 0;
}
This works fine:
#include <stdio.h>
#include <stdbool.h>
typedef bool cond;
void Enqueue(cond (*cond_func)(void)) {
printf("In Enqueue()...\n");
cond status = cond_func();
printf("In Enqueue, 'status' is %s\n", status ? "true" : "false");
}
bool IsEmpty(const int n) {
return true;
}
cond my_cond_func(void) {
printf("In my_cond_func()...\n");
return IsEmpty(1);
}
int main(void) {
Enqueue(my_cond_func);
return 0;
}
Your problem is likely coming from somewhere else, such as your definition of Enqueue() which you don't provide, or the fact your function is called read() and is conflicting with the more common function of that name.

Unable to pass C struct into function

I'm having trouble passing a struct into a function and I am running into an error:
'PWM_PINS' undeclared (first use in this function)
I am typically able to do this in a C++ compiler without any trouble. I would appreciate some advice as to what I might be doing wrong here.
I have included the relevant parts from the header and c file below.
pwm.h file:
typedef struct PWM_tag{
int PWM_1;
int PWM_2;
int PWM_3;
int PWM_4;
int PWM_5;
int PWM_6;
} PWM;
void PWM_Set( uint32_t channelNum, uint32_t cycle, PWM PWN_PINS );
pwm.c file:
#include "pwm.h"
void PWM_Set( uint32_t ChannelNum, uint32_t cycle, PWM PWN_PINS)
{
if ( ChannelNum == 1 )
{
LPC_PWM1->MR0 = cycle;
LPC_PWM1->MR1 = PWM_PINS.PWM_1;
LPC_PWM1->MR2 = PWM_PINS.PWM_2;
LPC_PWM1->MR3 = PWN_PINS.PWM_3;
LPC_PWM1->MR4 = PWM_PINS.PWM_4;
LPC_PWM1->MR5 = PWM_PINS.PWM_5;
LPC_PWM1->MR6 = PWM_PINS.PWM_6;
}
return;
}
You declared a parameter called PWN_PINS (with an N), but you are referring to PWM_PINS (with an M).
Fixing this typo will address this particular error. There may be more errors, though - it's hard to tell, because the snippet does not show essential parts, such as the declaration of LPC_PWM1 variable.
Is there misspelling in the code?
The function parameter is PWN_PINS.But the code have 5 PWM_PINS, and one PWN_PINS.
I think what you should do is to change all PWN_PINS to PWM_PINS.

Resources