 # Code explanation

hi, i'am trying to make a robot and i'am writing my code based on some found on web code (c for pic32) - but at some point i'am stuck, so maybe someone can help me to understand small part of that code.

What are those functions exactly do:

``````#define SDR4(a)  (((a)+   0x7)>> 4)
#define SDR8(a)  (((a)+  0x7f)>> 8)
#define SDR12(a) (((a)+ 0x7ff)>>12)
``````

they are used to calculate some long variables like this:

``````SVX.acc=SDR8(
SDR12((long)(RegFileL)*(SVX.theta -SVX.theta_ref))+
SDR12((long)(RegFileL)*(SVX.thetav-SVX.thetav_ref))+
SDR8( (long)(RegFileL)*(SVX.pos   -SVX.pos_ref))+
SDR8( (long)(RegFileL)*(SVX.vel   -SVX.vel_ref))
);
SVX.vel+=SDR4(SVX.acc);
SVX.pos+=SDR4(SVX.vel);
``````

where RegFileL[x] is static value - volatile unsigned long theta / theta_ref / pos_ref / vel_ref - long

They are rounding versions of shift right, normal shifts throw bits away and are biased. Adding before the shift removes the bias to make the shift right a much better version of divide by power of 2. One would normally add 0x8, 0x80 or 0x800 for standard rounding (round up on 0.5).