001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package org.wpilib.hardware.discrete; 006 007import org.wpilib.hardware.hal.DIOJNI; 008import org.wpilib.hardware.hal.HAL; 009import org.wpilib.hardware.hal.SimDevice; 010import org.wpilib.system.SensorUtil; 011import org.wpilib.util.sendable.Sendable; 012import org.wpilib.util.sendable.SendableBuilder; 013import org.wpilib.util.sendable.SendableRegistry; 014 015/** 016 * Class to read a digital input. This class will read digital inputs and return the current value 017 * on the channel. Other devices such as encoders, gear tooth sensors, etc. that are implemented 018 * elsewhere will automatically allocate digital inputs and outputs as required. This class is only 019 * for devices like switches etc. that aren't implemented anywhere else. 020 */ 021public class DigitalInput implements AutoCloseable, Sendable { 022 private final int m_channel; 023 private int m_handle; 024 025 /** 026 * Create an instance of a Digital Input class. Creates a digital input given a channel. 027 * 028 * @param channel the DIO channel for the digital input 0-9 are on-board, 10-25 are on the MXP 029 */ 030 @SuppressWarnings("this-escape") 031 public DigitalInput(int channel) { 032 SensorUtil.checkDigitalChannel(channel); 033 m_channel = channel; 034 035 m_handle = DIOJNI.initializeDIOPort(channel, true); 036 037 HAL.reportUsage("IO", channel, "DigitalInput"); 038 SendableRegistry.add(this, "DigitalInput", channel); 039 } 040 041 @Override 042 public void close() { 043 SendableRegistry.remove(this); 044 DIOJNI.freeDIOPort(m_handle); 045 m_handle = 0; 046 } 047 048 /** 049 * Get the value from a digital input channel. Retrieve the value of a single digital input 050 * channel from the FPGA. 051 * 052 * @return the status of the digital input 053 */ 054 public boolean get() { 055 return DIOJNI.getDIO(m_handle); 056 } 057 058 /** 059 * Get the channel of the digital input. 060 * 061 * @return The GPIO channel number that this object represents. 062 */ 063 public int getChannel() { 064 return m_channel; 065 } 066 067 /** 068 * Indicates this input is used by a simulated device. 069 * 070 * @param device simulated device handle 071 */ 072 public void setSimDevice(SimDevice device) { 073 DIOJNI.setDIOSimDevice(m_handle, device.getNativeHandle()); 074 } 075 076 @Override 077 public void initSendable(SendableBuilder builder) { 078 builder.setSmartDashboardType("Digital Input"); 079 builder.addBooleanProperty("Value", this::get, null); 080 } 081}