|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Raspberry Pi (Trading) Ltd. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: BSD-3-Clause |
| 5 | + */ |
| 6 | + |
| 7 | +#include <stdio.h> |
| 8 | +#include <pico/stdlib.h> |
| 9 | +#include <power_status.h> |
| 10 | +#include "hardware/adc.h" |
| 11 | +#include "pico/float.h" |
| 12 | + |
| 13 | +#if CYW43_USES_VSYS_PIN |
| 14 | +#include "pico/cyw43_arch.h" |
| 15 | +#endif |
| 16 | + |
| 17 | +int main() { |
| 18 | + stdio_init_all(); |
| 19 | + |
| 20 | + adc_init(); |
| 21 | + adc_set_temp_sensor_enabled(true); |
| 22 | + |
| 23 | + // Pico W uses a CYW43 pin to get VBUS so we need to initialise it |
| 24 | + #if CYW43_USES_VSYS_PIN |
| 25 | + if (cyw43_arch_init()) { |
| 26 | + printf("failed to initialise\n"); |
| 27 | + return 1; |
| 28 | + } |
| 29 | + #endif |
| 30 | + |
| 31 | + bool old_battery_status; |
| 32 | + float old_voltage; |
| 33 | + bool battery_status = true; |
| 34 | + char *power_str = "UNKNOWN"; |
| 35 | + |
| 36 | + while(true) { |
| 37 | + // Get battery status |
| 38 | + if (power_source(&battery_status) == PICO_OK) { |
| 39 | + power_str = battery_status ? "BATTERY" : "POWERED"; |
| 40 | + } |
| 41 | + |
| 42 | + // Get voltage |
| 43 | + float voltage = 0; |
| 44 | + int voltage_return = power_voltage(&voltage); |
| 45 | + voltage = floorf(voltage * 100) / 100; |
| 46 | + |
| 47 | + // Display power if it's changed |
| 48 | + if (old_battery_status != battery_status || old_voltage != voltage) { |
| 49 | + char percent_buf[10] = {0}; |
| 50 | + if (battery_status && voltage_return == PICO_OK) { |
| 51 | + const float min_battery_volts = 3.0f; |
| 52 | + const float max_battery_volts = 4.2f; |
| 53 | + int percent_val = ((voltage - min_battery_volts) / (max_battery_volts - min_battery_volts)) * 100; |
| 54 | + snprintf(percent_buf, sizeof(percent_buf), " (%d%%)", percent_val); |
| 55 | + } |
| 56 | + |
| 57 | + // Also get the temperature |
| 58 | + adc_select_input(4); |
| 59 | + const float conversionFactor = 3.3f / (1 << 12); |
| 60 | + float adc = (float)adc_read() * conversionFactor; |
| 61 | + float tempC = 27.0f - (adc - 0.706f) / 0.001721f; |
| 62 | + |
| 63 | + // Display power and remember old vales |
| 64 | + printf("Power %s, %.2fV%s, temp %.1f DegC\n", power_str, voltage, percent_buf, tempC); |
| 65 | + old_battery_status = battery_status; |
| 66 | + old_voltage = voltage; |
| 67 | + } |
| 68 | + sleep_ms(1000); |
| 69 | + } |
| 70 | + |
| 71 | +#if CYW43_USES_VSYS_PIN |
| 72 | + cyw43_arch_deinit(); |
| 73 | +#endif |
| 74 | + return 0; |
| 75 | +} |
0 commit comments