T
T
Taras Parashchuk2020-09-12 09:51:02
C++ / C#
Taras Parashchuk, 2020-09-12 09:51:02

How to do type casting in C?

Hello.
I'm making a frequency counter on an AVR microcontroller.
How to correctly cast the result type, for display on the screen or transmission via UART.
I get generally wrong results precisely because of the conversion.
For example, 234 or 000000. And it should be 1024 s, preferably with a fractional part (or without), at least some kind of result.
The formula below does not work. Zeros are obtained, but it should be 10004.03085khz
or at least 10004 or 100040308
unsigned long result = (16000000UL*(unsigned long)mesurImp)/baseImp;
mesurImp = 10171;
baseImp = 16267043;
How to get the correct result?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Taras Parashchuk, 2020-09-13
@taras1978

Found a solution.
For Atmel studio it was necessary to change the compiler settings.
In order for it to display float b double numbers.
tick vprintf library(-Wl,-u,vfprintf).
And set the flag -lprintf_flt
Read more here
https://startingelectronics.org/articles/atmel-AVR...

1
15432, 2020-09-12
@15432

unsigned long is probably 32-bit. And its maximum value is 4294967295, so there is an overflow when multiplying.
use unsigned long long, or count in floating point types (float, double)

V
vanyamba-electronics, 2020-09-12
@vanyamba-electronics

In AVR-GCC, the type sizes are as follows:

  • char, unsigned char = uint8_t
  • short, unsigned short = uint16_t
  • int, unsigned int = uint16_t
  • long, unsigned long = uint32_t

Thus the variables mesurImp and baseImp must be of type unsigned long.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question