Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5406

SDK • Re: Advice to get a float from user over serial and printf("%4X") issue [SOLVED]

$
0
0
I settled on the below for the concept code. I used roundf() to deal with certain floats not being converted to the correct binary as shown on table 7-1 of the datasheet.

Code:

// minicom local echo on#include <math.h>#include "pico/printf.h"#include "pico/stdio_uart.h"#include "pico/stdlib.h"#include "pico/time.h"int main() {    float foo = 0;    bool bar = 0;    stdio_uart_init();    // 2 second delay or we get garbage on the serial    sleep_ms(2000);    while(true){    printf("\ninput <= +255.9921 >= -256.0 ");    if ((bar = (scanf("%f",&foo)) == 0))    {    break;    }    else if (foo > 255.9921 || foo < -256.0)    {    printf("\nout of range %.9f",foo);    }    else    printf("\nyour input was %.9f",foo);    // Divides by the resolution to send the correct value to the register    // Round to the nearest integer before conversion    float toFloat = roundf(foo / 0.0078125);    printf("\ninput / offset (0.0078125) = %.9f",toFloat);    int16_t toTwos = (int16_t)toFloat;    printf("\n16 bit integer two's complement = DEC %d HEX 0x%4X",toTwos,(uint16_t)toTwos);    foo = 0;    }    printf("\nInvalid input, HALT");    while(1);    return 0;}

Statistics: Posted by breaker — Tue Jan 16, 2024 6:38 am



Viewing all articles
Browse latest Browse all 5406

Trending Articles