I implemented dc motor speed control project but there is one problem which i am not able to figure out .The problem is that my pid output which is float when assigned to short data type gives unexpected answer.since PWM inbuilt function in mikroc allows only short type dutycycle there is a need of float to short conversion. please help i am using pic16F877A.

    float to short conversion:
    float pid_out;
    short duty=(short)pid_out;
    if my pid_out<=100
    then duty=pid_out;
    and if my pid_out>100

for pid_out values less than or equal to hundred it gives same value for duty whereas for pid_out values greater than 100 it gives duty value in the range of 65500. please help unable to understand what is the mistake. For reading the values i used virtual terminal and uart.

  • \$\begingroup\$ Use "unsigned short" (in both places you use short) \$\endgroup\$
    – HKOB
    Feb 22 '15 at 13:07
  • \$\begingroup\$ where should i use unsigned short. I mean LHS or RHS \$\endgroup\$
    – dcmotor
    Feb 22 '15 at 13:09
  • \$\begingroup\$ unsigned short duty=(unsigned short)pid_out; \$\endgroup\$
    – HKOB
    Feb 22 '15 at 13:10
  • \$\begingroup\$ it is working can u explain me the logic please \$\endgroup\$
    – dcmotor
    Feb 22 '15 at 13:12
  • 1
    \$\begingroup\$ You likely do not need floating point arithmetics for this program. Neither PID regulation nor PWM calls for float. If you actually do need floats, you shouldn't be using the least code effective MCU on the market. \$\endgroup\$
    – Lundin
    Feb 24 '15 at 14:58

You should know that casting float to int or short, can result in undefined behavior, if the float has a value outside the range of the integer. So, if that is possible, you should think about how to handle the exception cases, if pid_out>255, or pid_out<0.

Otherwise the answer to your question is to use a "unsigned short" data type:

unsigned short duty=(unsigned short)pid_out;

This casts pid_out in the range 0..255, the same range as duty can hold.

See http://en.wikipedia.org/wiki/C_data_types for a list of C data types.

  • 1
    \$\begingroup\$ If MISRA-C and a static analyser would be used, then well-known compile-time bugs like this one would have been immediately spotted. \$\endgroup\$
    – Lundin
    Feb 24 '15 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.