Code covered by the BSD License  

Highlights from
MATLAB Support Package for Finch Robot

image thumbnail

MATLAB Support Package for Finch Robot

by

 

20 Jan 2012 (Updated )

MATLAB connectivity code to a Finch Robot

finchComm
classdef finchComm < handle
    %FINCHCOMM Base communication to Finch
    %   Currently this uses the Java interface to communicate with the
    %   Finch.  This interface shows the commands used to communicate with
    %   the Finch HID device.
    %
    % For more information please see
    % <http://www.finchrobot.com/usb-protocol USB Protocol> for information
    
    %% Properties
    properties (Access=private)
        javaObj = [];
    end
    
    properties (Hidden=true)
        simulation = true;   % Checks parameters before every operation
    end
    
    
    
    methods
        function obj = finchComm(varargin)
            %Finch Constructor
            
            % check nargin
            if nargin==0
                try
                    if isempty(regexp(javaclasspath,'finch.jar','once'))
                        if ispref('Finch')
                            javaaddpath(getpref('Finch','FinchJavaDir'));
                        else
                            javaaddpath([fileparts(mfilename('fullpath')),filesep,'Finch Software',filesep,'SourceFiles',filesep,'finch.jar']);
                            addpref('Finch', 'FinchJavaDir',[fileparts(mfilename('fullpath')),filesep,'Finch Software',filesep,'SourceFiles',filesep,'finch.jar']);
                        end
                    end
                    
                    %import edu.cmu.ri.createlab.terk.robot.finch.*
                    obj.javaObj = edu.cmu.ri.createlab.terk.robot.finch.Finch();
                catch ME
                    error(['Was not able to find/load the finch.jar file.  ',...
                        'Please run Finch.setup to install Finch Java Files.']);
                end
                obj.simulation = false;
            else
                disp('Note: DEMO connection will be created');
                disp('Do not pass anything to constructor to connect with the hardware.');
                obj.javaObj = [];
                obj.simulation = true; % Used to flag Simulation mode
            end
        end
        function delete(obj)
            % distructor, closes connection and deletes object
            if ~obj.simulation
                obj.javaObj.quit();
            end
        end
        function varargout = disp(obj) % display
            % disp, displays the object
            if obj.simulation
                disp('Currently using Simulation mode');
                if nargout==1; varargout = {'Currently using Simulation mode'};end
            else
                disp('Connected to your Finch');
                if nargout==1; varargout = {'Connected to your Finch'};end
            end
            
                
        end
        
        
        %%
        function led(obj, red, green, blue,duration)
            %SETLED(RGB Color Value)
            %
            % setLED(int red, int green, int blue)
            % Sets the color of the LED in the Finch's beak
            %
            % setLED(int red, int green, int blue, int duration)
            % Sets the color of the LED in the Finch's beak for the length of time specified by duration.
            %
            % 'O' - control full-color LEDs (Orbs)
            if ~obj.simulation
                if exist('duration','var')
                    obj.javaObj.setLED(red,green,blue,duration);
                else
                    obj.javaObj.setLED(red,green,blue);
                end
            end
            
        end
        function motor(obj,rightM, leftM, duration)
            % setWheelVelocities(int leftVelocity, int rightVelocity)
            % This method simultaneously sets the velocities of both wheels.
            %
            % setWheelVelocities(int leftVelocity, int rightVelocity, int timeToHold)
            % This method simultaneously sets the velocities of both wheels.
            % 'M' - control the velocity of the motors
            if ~obj.simulation
                %setWheelVelocities(leftM,rightM,[lengthTime in msec])
                if exist('duration','var')
                    obj.javaObj.setWheelVelocities(leftM,rightM,duration);
                else
                    obj.javaObj.setWheelVelocities(leftM,rightM);
                end
            end
        end
        function buzz(obj, freq, duration)
            % buzz(int frequency, int duration)
            % Plays a tone at the specified frequency for the specified duration on the Finch's internal buzzer.
            % 'B' - sets the buzzer to chirp for some period of time
            if obj.simulation
                % Simulate the buzz sound from Finch
                freqArray = sin(2*pi*(0:1/8192:duration/1000)*freq); %Expect duration to be in milliseconds
                sound(freqArray);
            else
                obj.javaObj.buzz(freq,duration);
            end
        end
        function val = temperature(obj)
            % getTemperature()
            % The current temperature reading at the temperature probe.
            % 'T' - gets the temperature
            if obj.simulation
                val = round(rand(1)^2*100);
            else
                val = obj.javaObj.getTemperature();
                val = double(val);
            end
        end
        function valArray = lightSensors(obj)
            % getLightSensors()
            % Returns a 2 integer array containing the current values of both light sensors.
            % 'L' - gets the values of the two light sensors
            if obj.simulation
                valArray = round(rand(1,2));
            else
                valArray = obj.javaObj.getLightSensors();
                valArray = double(valArray);
            end
        end
        function valArray = accelerometer(obj)
            % val = getAccelerations()
            % Use this method to simultaneously return the current X, Y, and Z accelerations experienced by the robot.
            % 'A' - gets the accelerometer values of the X, Y, and Z axes, and the tap/shake byte.
            if obj.simulation
                valArray = round(rand(1,3));
            else
                valArray = obj.javaObj.getAccelerations();
                valArray = double(valArray);
            end
        end
        function valArray = obstacleSensors(obj)
            % [R,L] = getObstacleSensors()
            % Returns the value of both obstacle sensors.
            % 'I' - gets the values of the two obstacle sensors
            if obj.simulation
                valArray = round(rand(1,2));
            else
                valArray = obj.javaObj.getObstacleSensors();
                valArray = double(valArray);
            end
        end
        function stop(obj)
            % stopWheels()
            % Stops both wheels.
            % 'X' - set all motors and LEDs to off
            if ~obj.simulation
                obj.javaObj.stopWheels();
            end
            
        end
        function quit(obj)
            % quit - This method properly closes the connection with the Finch and resets the Finch so that it is immediately ready to be controlled by subsequent programs.
            % 'R' - turns off the motor and has the Finch go back into color-cycling mode (this is how we indicate that the Finch connection is closed).
            if ~obj.simulation
                obj.javaObj.quit();
            end
            
        end
        function sendZ(obj)
            % 'z' - Just sends a counter value showing the number of times z has been sent (for basic connectivity testing).
            disp('Not Implemented');
        end
        
    end
    methods(Static)
        %% Install Java Support Code
        function setup()
            % Finch.setup()
            %   Walks users through getting connectivity code
            %   Installs code in the same place as this file
            
            packageParentDir = fileparts(mfilename('fullpath'));
            defaultFinchDir = packageParentDir;%fullfile(getenv('SYSTEMDRIVE'), 'Finch');
            mainpageUrl = 'http://www.finchrobot.com/downloads';
            if ismac
                packageUrl = 'http://www.finchrobot.com/sites/default/files/Mac/FinchJava.zip';
            elseif ispc
                packageUrl = 'http://www.finchrobot.com/sites/default/files/Windows/FinchJava.zip';
            end
            
            choice = questdlg({'You need the Finch Software', ['(from ' mainpageUrl ')']}, ...
                'Finch Java Source', 'Download and Install', 'Cancel', 'Download and Install');
            
            switch choice
                case 'Download and Install'
                    zipFile = fullfile(defaultFinchDir, 'FinchJava.zip');
                    h = waitbar(0.25, 'Downloading the Java (~ 8.8 MB) ...');
                    
                    try
                        urlwrite(packageUrl, zipFile);
                    catch ME
                        delete(h)
                        error('Finch:DownloadFailed',['Unable to download the FinchJava. Check your internet connection.' char(10)...
                            'If you are connected to the internet and still see this error,' char(10)...
                            'see www.finchrobot.com for troubleshooting information.']);
                    end
                    
                    waitbar(0.75, h, 'Unzipping the FinchJava ...');
                    
                    try
                        unzip(zipFile, defaultFinchDir);
                    catch ME
                        delete(h);
                        error('Finch:UnzipFailed',['Unable to unzip the FinchJava' char(10)...
                            'See www.finchrobot.com for troubleshooting instructions.']);
                    end
                    
                    delete(h);
                    FINCHJAVADir = fullfile(defaultFinchDir, 'FinchJava.zip');
                    fprintf('# Installed FinchJava Software to %s\n', FINCHJAVADir);
                    
                case 'Cancel'
                    fprintf('# Cancelling Finch package setup\n');
                    return;
            end
            
            addpref('Finch', 'FinchJavaDir',[defaultFinchDir,filesep,'Finch Software',filesep,'SourceFiles',filesep,'finch.jar']);
            
            fprintf('# Added Finch package to MATLAB path\n');
            %% Add Finch.jar to the Java Path
            javaaddpath([defaultFinchDir,filesep,'Finch Software',filesep,'SourceFiles',filesep,'finch.jar']);
            
            %% add package to MATLAB path
            addpath(packageParentDir);
            result = savepath;
            
            if result==1
                nl = char(10);
                msg = ['# Unable to save updated MATLAB path (<a href="http://www.mathworks.com/support/solutions/en/data/1-9574H9/index.html?solution=1-9574H9">why?</a>)' nl ...
                    '  To save the path, you can: ' nl ...
                    '   1) Exit MATLAB ' nl ...
                    '   2) Right-click the MATLAB icon and select "Run as administrator" ' nl ...
                    '   3) Re-run vellscope.setup ' nl ...
                    ];
                disp(msg);
            else
                fprintf('# Added ''%s'' to MATLAB path\n', packageParentDir);
            end
            
            nl = char(10);
            msg = ['You can now navigate to any other directory and use the Finch package. ' nl ...
                'See <a href="matlab:edit(''gettingStarted.m'')">this example</a> to get started' nl ...
                ];
            disp(msg);
            
        end
    end
end


Contact us