|
| 1 | +// |
| 2 | +// USB Power Delivery for Arduino |
| 3 | +// Copyright (c) 2023 Manuel Bleichenbacher |
| 4 | +// |
| 5 | +// Licensed under MIT License |
| 6 | +// https://opensource.org/licenses/MIT |
| 7 | +// |
| 8 | + |
| 9 | +// |
| 10 | +// --- Test program switching between the available fixed voltages |
| 11 | +// |
| 12 | + |
| 13 | +#include <Arduino.h> |
| 14 | +#include "TaskScheduler.h" |
| 15 | +#include "ProtocolAnalyzer.h" |
| 16 | +#include "PowerDelivery.h" |
| 17 | +#include "CRC32.h" |
| 18 | + |
| 19 | +static void handleEvent(PDSinkEventType eventType); |
| 20 | +static void switchVoltage(); |
| 21 | +static bool hasExpired(uint32_t time); |
| 22 | + |
| 23 | +static bool isUSBPDSource = false; |
| 24 | +static uint32_t nextVoltageChangeTime = 0; |
| 25 | +static int voltageIndex = 0; |
| 26 | + |
| 27 | +void setup() { |
| 28 | + Serial.begin(115200); |
| 29 | + PowerSink.start(handleEvent); |
| 30 | + Serial.println(); |
| 31 | + Serial.println("USB Power Delivery"); |
| 32 | +} |
| 33 | + |
| 34 | +void loop() { |
| 35 | + PowerSink.poll(); |
| 36 | + ProtocolAnalyzer::poll(); |
| 37 | + |
| 38 | + if (isUSBPDSource && hasExpired(nextVoltageChangeTime)) |
| 39 | + switchVoltage(); |
| 40 | +} |
| 41 | + |
| 42 | +void switchVoltage() { |
| 43 | + // select next fixed voltage |
| 44 | + do { |
| 45 | + voltageIndex += 1; |
| 46 | + if (voltageIndex >= PowerSink.numSourceCapabilities) |
| 47 | + voltageIndex = 0; |
| 48 | + } while (PowerSink.sourceCapabilities[voltageIndex].supplyType != PDSupplyType::fixed); |
| 49 | + |
| 50 | + PowerSink.requestPower(PowerSink.sourceCapabilities[voltageIndex].maxVoltage); |
| 51 | + nextVoltageChangeTime += 3000; |
| 52 | +} |
| 53 | + |
| 54 | +void handleEvent(PDSinkEventType eventType) { |
| 55 | + switch (eventType) { |
| 56 | + case PDSinkEventType::sourceCapabilitiesChanged: |
| 57 | + if (PowerSink.isConnected()) { |
| 58 | + Serial.println("New source capabilities (USB PD supply)"); |
| 59 | + isUSBPDSource = true; |
| 60 | + voltageIndex = 0; |
| 61 | + nextVoltageChangeTime = millis() + 2000; |
| 62 | + } else { |
| 63 | + isUSBPDSource = false; |
| 64 | + Serial.println("New source capabilities (no USB PD supply connected)"); |
| 65 | + } |
| 66 | + break; |
| 67 | + |
| 68 | + case PDSinkEventType::voltageChanged: |
| 69 | + Serial.printf("Voltage changd: %5dmV %5dmA (max)", PowerSink.activeVoltage, PowerSink.activeCurrent); |
| 70 | + Serial.println(); |
| 71 | + break; |
| 72 | + |
| 73 | + case PDSinkEventType::powerRejected: |
| 74 | + Serial.println("Power request rejected"); |
| 75 | + break; |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +bool hasExpired(uint32_t time) { |
| 80 | + return (int32_t)(time - millis()) <= 0; |
| 81 | +} |
0 commit comments