# C functions

Hi,

I’m reading my C textbook for next semester and saw the section about functions. Got me really excited and I decided to use some functions to correct the joysticks.

Here’s my old codes:

``````while(true)
{
int rghtch1 = 0;
if((vexRT[Ch1] > 20)||(vexRT[Ch1] < -20))
{rghtch1 = vexRT[Ch1];}
else
{rghtch1 = 0;}

int rghtch2 = 0;
if((vexRT[Ch2] > 20)||(vexRT[Ch2] < -20))
{rghtch2 = vexRT[Ch2];}
else
{rghtch2 = 0;}

int leftch3 = 0;
if((vexRT[Ch3] > 20)||(vexRT[Ch3] < -20))
{leftch3 = vexRT[Ch3];}
else
{leftch3 = 0;}

int leftch4 = 0;
if((vexRT[Ch4] > 20)||(vexRT[Ch4] < -20))
{leftch4 = vexRT[Ch4];}
else
{leftch4 = 0;}
motor[WheelLeft] = leftch3 - rghtch1;
motor[WheelRght] = leftch3 + rghtch1;
motor[WheelMidd] = leftch4;
}
``````

It basically returns a 0 whenever the stick is under 20 and return a normal stick value otherwise.

Here’s the new code utilizing a function (or my perception of one):

``````int stablejoystick(char channel,int value)
{
int joystick = 0;
if((vexRT[channel] > value)||(vexRT[channel] < -value))
{int joystick = vexRT[channel];}
else
{int joystick = 0;}
return joystick;
}
{
while(true)
{
int rghtch1 = stablejoystick(Ch1,15);
int rghtch2 = stablejoystick(Ch2,15);
int leftch3 = stablejoystick(Ch3,15);
int leftch4 = stablejoystick(Ch4,15);
motor[WheelLeft] = leftch3 - rghtch1;
motor[WheelRght] = leftch3 + rghtch1;
motor[WheelMidd] = leftch4;
}
}``````

The problem seems to be that the variables within the stablejoystick “function” are global (I watch the global variable windows and they list joystick, channel and what not. It also seem to make the processor run slower I’m guessing because I called the functions 4 times.

I think I need to put the channel variable in primes like this

``````
int rghtch1 = stablejoystick(Ch1,15);

``````

I’m going to try that tonight.

Thanks,