View previous topic :: View next topic |
Author |
Message |
kammenos
Joined: 25 Feb 2014 Posts: 2
|
Variables function-wide |
Posted: Tue Feb 25, 2014 12:57 pm |
|
|
Hello guys,
this is my 2nd day in C. So you will tell from my question. I want to declare a variable (say int8 Temp) which is:
1. accessible from all functions
2. variable content is not lost when a function ends.
Here is my example;
Code: |
int8 Temp;
void SetTemp(){
Temp=1;
}
void main(){
SetTemp()
If (Temp==1){
..... do something...
}
}
|
For some reason i cannot make it work. Any help?
Thanks |
|
|
kammenos
Joined: 25 Feb 2014 Posts: 2
|
|
Posted: Tue Feb 25, 2014 1:15 pm |
|
|
Ops... shame... found it. Just for the other newbies to learn and for the pros to confirm. Here is the actual code:
Code: |
int8 LastButtonPress;
int8 GetButtonPress(){
if (Button_L==0){
if (LastButtonPress==1){
output_high(LED_1);
}else{
output_low(LED_1);
}
LastButtonPress=1;
return(1);
}
LastButtonPress=0;
return(0);
}
void main() {
port_b_pullups (0b00111000);
while(TRUE){
if (GetButtonPress()==1){
}
delay_ms(100);
}
}
|
The idea is that when the button is pressed for the first time, the global parameter "LastButtonPress" will become one. The next time when it is kept pressed and the "LastButtonPress" is one, the LED will turn on. Nothing fancy, just to test the functionality.
So for the pros to confirm, my question now is:
Code: | if (GetButtonPress()==1){
}
|
It seems that if there is nothing between {}, the compiler does NOT run the GetButtonPress(), or maybe the whole line is just removed from the listing. Is this true? |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Tue Feb 25, 2014 1:22 pm |
|
|
Look at the .LST file and find out. |
|
|
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
|
Posted: Tue Feb 25, 2014 2:45 pm |
|
|
The best tool for getting correct answers and knowledge is the scientific method. Therefore I suggest you to make a simple test program that would show you if the function is executed during the test of the expression. Here is a code to hint you how to test "if the compiler runs the GetButtonPress()"
Code: |
int test_func(void)
{
output_toggle(LED); //the LED (blinking) shows you that test_func is called
your_code_here;
return (0); //you can change to return 1 so you can see if the led blinking yet
}
void main()
{
if(test_func()==0){ //
} //nothing inside the brackets
delay_ms(500);
}
|
I think it is very powerful tool to test the things you doubt. It might save time to all of us, and more important, to give you answers you understand, not given away. _________________ A person who never made a mistake never tried anything new. |
|
|
|