Thread: I hate "C"
View Single Post
  #1   Spotlight this post!  
Unread 19-01-2007, 23:56
maniac_2040's Avatar
maniac_2040 maniac_2040 is offline
Registered User
AKA: Matt
FRC #3302 (Turbo Trojans)
Team Role: Programmer
 
Join Date: Jan 2006
Rookie Year: 2005
Location: Clawson, Michigan
Posts: 34
maniac_2040 is infamous around these partsmaniac_2040 is infamous around these partsmaniac_2040 is infamous around these partsmaniac_2040 is infamous around these parts
Send a message via MSN to maniac_2040
I hate "C"

I'm having a very tedious coding problem and I know it has something to do with the types/type casting in C.

I was writing/testing some PID code. It worked fine(I was just tweaking gains), but I noticed some overflow, so I changed alot of my variables from ints to longs. Now when I try to print, nearly everything prints as zero. Here is the code in question:

Code:
  
/*
 * pid_output
 *
 * This function outputs a value using a PID control loop for the specified PID struct.
 * Takes a measurement, maximum output, and index of the gains for this loop in EEPROM.
 */
int Pid_Output(Pid_Struct * pid, long measurement,int maxOutput,int eeprom_index)
{
	int output = 0;
    
	//Get smaller names for the gains.
        int pn = EEPROM_Read(eeprom_index);
	int pd = EEPROM_Read(eeprom_index+1);
        int in = EEPROM_Read(eeprom_index+2);
	int id = EEPROM_Read(eeprom_index+3);
        int dn = EEPROM_Read(eeprom_index+4);
	int dd = EEPROM_Read(eeprom_index+5);
	long p, i, d;

	pid->error = pid->setPoint-measurement;

	if( ABS(pid->error) < (long)pid->tolerance )
		pid->error = 0;

	//Accumlate error into the error_i and set the last error.
          pid->error_i+=pid->error;    
	pid->error_d = (pid->error - pid->error_last);
	pid->error_last = pid->error;

	//This is the PID part:

             p =((pid->error * (long)pn) / (long)pd);
             i= ((pid->error_i * (long)in) / (long)id);
	d= (((long)pid->error_d * (long)dn) / (long)dd);

	output = p + i + d;
	//DEBUG UNCONVENTIONAL
	printf("\rMeasure: %d Target: %d Err: %d Err_I: %d Err_d: %d Output: %d Max: %d",measurement,pid->setPoint,
			(int)p,(int)i,(int)d, (int)output, (int)maxOutput );

	//Make sure we're in bounds
    if(ABS(output) > maxOutput )
        output = maxOutput*SIGN(output);

	output+=pid->offset;
        
    return output;
}
(Sorry about some of the indentions, got screwed up when I copied and pasted)

so what is happening here? the value for "output" prints out fine, but everything else comes up as zero... pn, pd, etc are non zero...

Maybe I'm just too tired/lazy to figure this out.