1 // Copyright 2023 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 15 #include "pw_digital_io_rp2040/digital_io.h" 16 17 #include "hardware/gpio.h" 18 #include "pw_digital_io/digital_io.h" 19 #include "pw_status/status.h" 20 21 namespace pw::digital_io { 22 Rp2040DigitalIn(Rp2040Config config)23Rp2040DigitalIn::Rp2040DigitalIn(Rp2040Config config) : config_(config) {} 24 DoEnable(bool enable)25Status Rp2040DigitalIn::DoEnable(bool enable) { 26 if (!enable) { 27 gpio_deinit(config_.pin); 28 return OkStatus(); 29 } 30 31 gpio_init(config_.pin); 32 gpio_set_dir(config_.pin, GPIO_IN); 33 return OkStatus(); 34 } 35 DoGetState()36Result<State> Rp2040DigitalIn::DoGetState() { 37 if (gpio_get_function(config_.pin) != GPIO_FUNC_SIO || 38 gpio_get_dir(config_.pin) != GPIO_IN) { 39 return Status::FailedPrecondition(); 40 } 41 42 const bool pin_value = gpio_get(config_.pin); 43 const State state = config_.PhysicalToLogical(pin_value); 44 return pw::Result<State>(state); 45 } 46 Rp2040DigitalInOut(Rp2040Config config)47Rp2040DigitalInOut::Rp2040DigitalInOut(Rp2040Config config) : config_(config) {} 48 DoEnable(bool enable)49Status Rp2040DigitalInOut::DoEnable(bool enable) { 50 if (!enable) { 51 gpio_deinit(config_.pin); 52 return OkStatus(); 53 } 54 55 gpio_init(config_.pin); 56 gpio_set_dir(config_.pin, GPIO_OUT); 57 return OkStatus(); 58 } 59 DoSetState(State level)60Status Rp2040DigitalInOut::DoSetState(State level) { 61 if (gpio_get_function(config_.pin) != GPIO_FUNC_SIO || 62 gpio_get_dir(config_.pin) != GPIO_OUT) { 63 return Status::FailedPrecondition(); 64 } 65 66 gpio_put(config_.pin, config_.LogicalToPhysical(level)); 67 return OkStatus(); 68 } 69 DoGetState()70Result<State> Rp2040DigitalInOut::DoGetState() { 71 if (gpio_get_function(config_.pin) != GPIO_FUNC_SIO || 72 gpio_get_dir(config_.pin) != GPIO_OUT) { 73 return Status::FailedPrecondition(); 74 } 75 76 const bool pin_value = gpio_get(config_.pin); 77 const State state = config_.PhysicalToLogical(pin_value); 78 return pw::Result<State>(state); 79 } 80 81 } // namespace pw::digital_io 82