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 edu.wpi.first.wpilibj; 006 007import edu.wpi.first.hal.AnalogJNI; 008import edu.wpi.first.hal.FRCNetComm.tResourceType; 009import edu.wpi.first.hal.HAL; 010import edu.wpi.first.util.sendable.Sendable; 011import edu.wpi.first.util.sendable.SendableBuilder; 012import edu.wpi.first.util.sendable.SendableRegistry; 013 014/** Analog output class. */ 015public class AnalogOutput implements Sendable, AutoCloseable { 016 private int m_port; 017 private int m_channel; 018 019 /** 020 * Construct an analog output on a specified MXP channel. 021 * 022 * @param channel The channel number to represent. 023 */ 024 public AnalogOutput(final int channel) { 025 SensorUtil.checkAnalogOutputChannel(channel); 026 m_channel = channel; 027 028 final int portHandle = HAL.getPort((byte) channel); 029 m_port = AnalogJNI.initializeAnalogOutputPort(portHandle); 030 031 HAL.report(tResourceType.kResourceType_AnalogOutput, channel + 1); 032 SendableRegistry.addLW(this, "AnalogOutput", channel); 033 } 034 035 @Override 036 public void close() { 037 SendableRegistry.remove(this); 038 AnalogJNI.freeAnalogOutputPort(m_port); 039 m_port = 0; 040 m_channel = 0; 041 } 042 043 /** 044 * Get the channel of this AnalogOutput. 045 * 046 * @return The channel of this AnalogOutput. 047 */ 048 public int getChannel() { 049 return m_channel; 050 } 051 052 public void setVoltage(double voltage) { 053 AnalogJNI.setAnalogOutput(m_port, voltage); 054 } 055 056 public double getVoltage() { 057 return AnalogJNI.getAnalogOutput(m_port); 058 } 059 060 @Override 061 public void initSendable(SendableBuilder builder) { 062 builder.setSmartDashboardType("Analog Output"); 063 builder.addDoubleProperty("Value", this::getVoltage, this::setVoltage); 064 } 065}