|
| 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 | +// Selects 12V if available, and 15V otherwise. |
| 11 | + |
| 12 | +// Please see https://github.com/manuelbl/usb-pd-arduino/wiki for |
| 13 | +// instructions how to wire your specific board to a USB C connector. |
| 14 | +// For this sketch, "Sink Mode" is relevant. |
| 15 | +// |
| 16 | + |
| 17 | +#include "USBPowerDelivery.h" |
| 18 | + |
| 19 | +void setup() { |
| 20 | + Serial.begin(115200); |
| 21 | + PowerSink.start(handleEvent); |
| 22 | +} |
| 23 | + |
| 24 | +void loop() { |
| 25 | + PowerSink.poll(); |
| 26 | +} |
| 27 | + |
| 28 | +void handleEvent(PDSinkEventType eventType) { |
| 29 | + |
| 30 | + if (eventType == PDSinkEventType::sourceCapabilitiesChanged) { |
| 31 | + // source capabilities have changed |
| 32 | + if (PowerSink.isConnected()) { |
| 33 | + // USB PD supply is connected |
| 34 | + requestVoltage(); |
| 35 | + |
| 36 | + } else { |
| 37 | + // no supply or no USB PD capable supply is connected |
| 38 | + PowerSink.requestPower(5000); // reset to 5V |
| 39 | + } |
| 40 | + |
| 41 | + } else if (eventType == PDSinkEventType::voltageChanged) { |
| 42 | + // voltage has changed |
| 43 | + if (PowerSink.activeVoltage != 0) { |
| 44 | + Serial.printf("Voltage: %d mV @ %d mA (max)", PowerSink.activeVoltage, PowerSink.activeCurrent); |
| 45 | + Serial.println(); |
| 46 | + } else { |
| 47 | + Serial.println("Disconnected"); |
| 48 | + } |
| 49 | + |
| 50 | + } else if (eventType == PDSinkEventType::powerRejected) { |
| 51 | + // rare case: power supply rejected requested power |
| 52 | + Serial.println("Power request rejected"); |
| 53 | + Serial.printf("Voltage: %d mV @ %d mA (max)", PowerSink.activeVoltage, PowerSink.activeCurrent); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +void requestVoltage() { |
| 58 | + // check if 12V is supported |
| 59 | + for (int i = 0; i < PowerSink.numSourceCapabilities; i += 1) { |
| 60 | + if (PowerSink.sourceCapabilities[i].minVoltage <= 12000 |
| 61 | + && PowerSink.sourceCapabilities[i].maxVoltage >= 12000) { |
| 62 | + PowerSink.requestPower(12000); |
| 63 | + return; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // check if 15V is supported |
| 68 | + for (int i = 0; i < PowerSink.numSourceCapabilities; i += 1) { |
| 69 | + if (PowerSink.sourceCapabilities[i].minVoltage <= 15000 |
| 70 | + && PowerSink.sourceCapabilities[i].maxVoltage >= 15000) { |
| 71 | + PowerSink.requestPower(15000); |
| 72 | + return; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + Serial.println("Neither 12V nor 15V is supported"); |
| 77 | +} |
| 78 | + |
0 commit comments