{{tagb|→}} See also the '''[[CHDK_Scripting_Cross_Reference_Page|Scripting Cross Reference Page]]''' for the complete list of CHDK scripting commands for Lua and uBASIC. And also see: http://chdk.wikia.com/wiki/Script_commands and http://chdk.wikia.com/wiki/UBASIC/Scripts and http://chdk.wikia.com/wiki/Lua/Lua_Reference .

+

{{tagb|→}} See also the '''[[CHDK_Scripting_Cross_Reference_Page|Scripting Cross Reference Page]]''' for the complete list of CHDK scripting commands for Lua and uBASIC. And also see: http://chdk.wikia.com/wiki/Script_commands and http://chdk.wikia.com/wiki/UBASIC/Scripts and http://chdk.wikia.com/wiki/Lua/Lua_Reference .

*Scripts may conflict with your camera if it is set to its fully automatic state. If you are having problems try setting your camera into "P" mode. When CHDK is not loaded: press the cam/movie button then the right button until P is highlighted and press SET. Also consider setting your camera to a fixed ISO value instead of AutoISO. When CHDK is not loaded: press the SET button, then scroll up to the top and right to a fixed ISO value.

+

*Scripts may conflict with your camera if it is set to its fully automatic state. If you are having problems try setting your camera into "P" mode. When CHDK is not loaded: press the cam/movie button then the right button until P is highlighted and press SET. Also consider setting your camera to a fixed ISO value instead of AutoISO. When CHDK is not loaded: press the SET button, then scroll up to the top and right to a fixed ISO value.

−

*Use any text editor to compose your scripts. Make sure it is saving the file as TEXT-ONLY. Do NOT use programs like Word or other advanced editors. These insert hidden header info and use non-standard ASCII characters for Return/Line-Feed commands, quotation-marks, and others. The simplest of text-editors will suffice, even then watch out not to use TAB for indenting. (Notepad in Windows, nano in Linux for example.) Macusers,makesureyourscriptisin UTF-8 encoding, see [[FAQ/Mac#How_to_Copy_Script_Files_Without_Errors|this special note concerning Macs and Script Files]].

+

*Use a plain text editor to compose your scripts. Make sure it saves the file as TEXT-ONLY. Do NOT use programs like Word, wordpad or other advanced editors. These insert hidden header info and use non-standard ASCII characters for Return/Line-Feed commands, quotationmarks, and others. The simplest of texteditors will suffice (Notepad in Windows, nano in Linux for example).ScriptsmustbesavedasASCIIplaintext. UTF-8 may work, but is not recommended because some editors insert a [http://en.wikipedia.org/wiki/Byte_order_mark unicode BOM] at the start. Mac users see [[FAQ/Mac#How_to_Copy_Script_Files_Without_Errors|this special note concerning Macs and Script Files]].

−

*Keep all commands in lower-case. Variables are case-sensitive (a and A are not the same).

+

*Keep all commands in lower-case. Variables are, however, case-sensitive (a and A are not the same).

−

*Be aware that not all commands work on all cameras,if you plan on sharing your script try to keep it as generic as possible unless you have a special need for the camera-specific commands. Try to also provide a more generic version so that all may benefit from it.

+

*Be aware that not all commands work on all cameras.If you plan on sharing your script try to keep it as generic as possible unless you have a special need for the camera-specific commands. Try to also provide a more generic version so that all may benefit from it.

−

*IfusingearlierCHDKBuildssomecommandslistedherewillnotbeavailable to youandcauseerrors,thistutorialwillbeupdatedasnewcommandsandchangesaremadetoCHDK.

+

*Keepyourscriptconciseandefficient!Ittakes10msoftimeforeach line of script to beinterpretedbytinyuBASIC.Ascript10lineslongtakes1/10thofasecond,100lines takes a full second, etc. This can greatly impact high-speeduses.

−

*Keepyour script conciseandefficient !

+

*Ifyou write an interesting script,'''shareit'''withthe rest of us at [[uBASIC/Scripts|'''User Written Scripts''']] so we may learn from you! Beginner script writers can be some of the most creative! Also if you are just starting out use the page for ideas and examples.

−

:It takes 10ms of time for each line of your script to be interpreted by tiny uBASIC. If your script is 10 lines long this takes 1/10th of a second, 100 lines takes a full second, etc. This can greatly impact high-speed uses.

−

:Note: This is mainly uBasic-related; current CHDK version are using some optimations for more efficient scripting.

−

*Ifyouwritean interesting script, '''share it''' with the rest of uson the UserWrittenScriptspagessowemaylearnfromyou!Beginnerscript-writerscan be some of themostcreative!

+

*Havealookat the settingsin the scriptingmenu,therearesomeinterestingfeaturesavailablesuchas'''autostart''','''parametersets'''&more...

−

−

*See these pages for some ideas and examples if you are just starting out: [[uBASIC/Scripts|'''User Written Scripts''']]

−

−

*Have a look to the settings in the scripting menu, there are some interesting features available like '''autostart''', '''parameter sets''' & more...

:This optional statement specified a list of strings that are can be scrolled by the user to select a parameter's value. The parameter's value will be the position of the chosen string in the list. Usage example:

+

:This optional statement specifies a list of strings that are can be scrolled by the user to select a parameter value. The parameter value will be the position of the chosen string in the list (starting with 0). String values will only be assigned if there is no "@range" statement. Usage example:

@param f Channel (U,Y,V,R,G,B)

@param f Channel (U,Y,V,R,G,B)

@default f 1

@default f 1

−

@values f U Y V R G

+

@values f U Y V R G B

−

+

:In this case the string "Y" is the default, as ''f'' has the default value of 1.

−

;'''Notes:'''

+

:If a variable had to be assigned the three values of -1, 0 and 1 via corresponding strings, then the three strings would be defined as "@values" with initial values of 0, 1, and 2, then 1 is subtracted in the body of the script:

+

@param f Brightness Threshold

+

@default f 1

+

@values f Darker Off Lighter

+

f=f-1

+

rem f now has the values of -1 for "Darker", 0 for "Off", and 1 for "Lighter"

+

;'''Notes'''

+

:

:If there is no '''@title''' command the filename of script is used.<br />If there are no '''@param''' commands CHDK assumes that there are three adjustable variables: '''a''', '''b''' and '''c'''.<br />Remember -- when naming <b>@param</b> variables, use only a character from a through z.

:If there is no '''@title''' command the filename of script is used.<br />If there are no '''@param''' commands CHDK assumes that there are three adjustable variables: '''a''', '''b''' and '''c'''.<br />Remember -- when naming <b>@param</b> variables, use only a character from a through z.

−

After your default variable values have been defined here, it is good to add some lines right after this section to ensure those numbers will be used in case the user has input 0 (zero) for some value that needs to be higher (or lower). Youwillseethis in scripts as:

+

After default variable values have been defined here, it is good to add some lines right after this section to ensure those numbers will be used in case the user has input 0 (zero) for some value that needs to be higher (or lower). Thiscanbeseen in scripts as:

−

if '''a'''&lt;2 then let '''a'''<nowiki>=</nowiki>5

+

if '''a'''&lt;2 then let '''a'''=5

−

:If your default value that you wanted the user to start out at for parameter variable '''a''' was 5, then if they left that setting at 0 (zero) or 1, then this will automatically increase that variable's value back up to 5.

+

:If the default value that you wanted the user to start out at for parameter variable '''a''' was 5, then if they left that setting at 0 (zero) or 1, then this will automatically increase that variable's value back up to 5.

−

After you have set up your variable parameters,then comes the brunt of your script, the part that does the actual work and tells the camera what to do, when to do it, and what buttons or commands need to be executed. Since we are working with a very small subset of the larger uBASIC programming language, it might be good to list and explain only those that are available to the CHDK script writer.

+

After variable parameters have beeninitialised comes the brunt of your script, the part that does the actual work and tells the camera what to do, when to do it, and what buttons or commands need to be executed. Since we are working with a very small subset of the larger uBASIC programming language, it might be good to list and explain only those that are available to the CHDK script writer.

----

----

Line 430:

Line 447:

+ Addition

+ Addition

- Subtraction

- Subtraction

−

* Multiplication

+

<nowiki>*</nowiki> Multiplication

/ Division

/ Division

% Remainder (explanation see below)

% Remainder (explanation see below)

Line 572:

Line 589:

To enable file logging, call print_screen() with a non-zero value. This will create a log file in the /CHDK/LOG directory with name LOG_nnnn.TXT, where nnnn is the absolute value of the parameter you passed to the print_screen statement.

To enable file logging, call print_screen() with a non-zero value. This will create a log file in the /CHDK/LOG directory with name LOG_nnnn.TXT, where nnnn is the absolute value of the parameter you passed to the print_screen statement.

−

If the passed value is less than -10000, the log will append to the end of the exiting log file. If the passed value is greater than -100000, the old file will be overwritten. If the passed value is a boolean ''false'', logging will be disabled. If the passed value is a boolean ''true'', a new log file LOG_0001.TXT will be created.

+

If the passed value is less than 0, the log will append to the end of the exiting log file. If the passed value is greater than 0, the old file will be overwritten. If the passed value is a 0 or boolean ''false'', logging will be disabled. If the passed value is a boolean ''true'', a new log file LOG_0001.TXT will be created.

Example:

Example:

Line 591:

Line 608:

print_screen(false)

print_screen(false)

print "This is not written to a file"

print "This is not written to a file"

−

print_screen(-10000-5)

+

print_screen(-5)

print "This is written to the end of file LOG_0005.TXT"

print "This is written to the end of file LOG_0005.TXT"

print_screen(false)

print_screen(false)

Line 616:

Line 633:

===enter_alt===

===enter_alt===

−

:This command causes a CHDK script to re-enter &lt;Alt&gt; mode while running (typically after having used the exit_alt() function). Available in Lua only.

+

:This command causes a CHDK script to re-enter &lt;Alt&gt; mode while running (typically after having used the exit_alt() function).

+

Note that the uBASIC version of this command expects a single parameter (which is not used). The correct uBASIC syntax is

+

enter_alt 0

+

:

+

:

+

===get_alt_mode===

+

:This command returns the current ALT state. This can be used to by a script so that it does not attempt to read button pushes or to update the LCD when the CHDK has left ALT mode while the script is still running (possibly because the user pressed the ALT key).

−

===is_key===

+

Lua : function returns ''true'' if CHDK is currently in ALT mode and ''false'' otherwise.

−

''---> should be moved to other keyb related command section !''

−

−

Also added a varation of the '''is_key''' statement, so '''is_key''' can be used as:

−

<pre>

−

if is_key "set" then goto "continue"

−

</pre>

−

And also as:

−

<pre>

−

k = is_key "set"

−

</pre>

−

The original statement version (example below) may still be used.

−

<pre>

−

is_key k "set"

−

if k=1 then goto "continue"

−

</pre>

−

−

The main reason for this new ''''is_key''' option and other loop methods is that you can now more easily make key-press detection loops. Such as:

−

−

<pre>

−

do

−

if is_key "right" then gosub "r_label"

−

if is_key "left" then gosub "l_label"

−

until is_key "set"

−

−

rem begin r_label subroutine

−

:r_label

−

(commands)

−

rem begin l_label subroutine

−

:l_label

−

(commands)

−

</pre>

+

uBasic : function return 1 if CHDK is currently in ALT mode and 0 otherwise.

:(insert more information on variable parameter functions and uses as they become known or more familiar)

:(insert more information on variable parameter functions and uses as they become known or more familiar)

−

===md_get_cell_diff===

===md_get_cell_diff===

−

[mx3]it is optional procedure for those people who want to know where on scene actually detection happened. this procedure is designed for scene change advanced analysis.

+

This function is for those people who want to know where on scene actually detection happened. This procedure is designed for scene change advanced analysis.

−

I'm not sure many people will need to use it.

−

most people will need to use "h" variable from above sample to trigger shoot. (feel free to rephrase)[/mx3]

:Usage: md_get_cell_diff (column), (row), x<br /><br />

:Usage: md_get_cell_diff (column), (row), x<br /><br />

−

:Where x will be difference of 0 to 255 between the last and present change in that cell. Triggering a script to shoot on this value may be done by detecting no change, or how much sensitivity you would like to detect in that cell.<br /><br />

+

:where x will be difference of 0 to 255 between the last and present change in that cell. Triggering a script to shoot on this value may be done by detecting no change, or how much sensitivity you would like to detect in that cell.<br /><br />

:Examples:

:Examples:

:If you would like to have the camera shoot an image when all motion stops, use:

:If you would like to have the camera shoot an image when all motion stops, use:

Line 745:

Line 764:

(If values less than zero are entered or if total number of cells is greater than 1024, it defaults to 3 x 3.)

(If values less than zero are entered or if total number of cells is greater than 1024, it defaults to 3 x 3.)

−

Parameter 'g' determines if the grid showing the detected cells is displayed.

These commands are designed to allow your script to control your camera much like you would manually. Nearly anything you can do by pressing buttons on your camera with your own fingers, you can also do automatically with these script commands. The complexity and time-line of your script is only limited by your imagination and trying to keep your script under the 8K character (8192 byte) limit. (See "starting out" section above for script length limit; this might not be accurate any more)

+

==shoot==

+

:Records an image.

−

Cameracommandscanbewritten in 3flavors/ command-methods:

+

:Thiscommandissimilarto the '''click "shoot_full"''' command (see below), but it waits for the camera to perform some normally automatic actions, such as auto-focusing, charging the flash, etc. For example: if in AUTO,P,Tv, Av, or any SCN modes, using the "shoot" command causes the camera to check focus and exposure for each shot. When "shoot" is used in intervalometer scripts this far surpasses the camera's own built-in intervalometer in that the camera only sets exposure and focus once for the initial exposure, as if it was only using the "click 'shoot_full'" command. This "shoot" command in an intervalometer script allows it to compensate for all the things that can change over the course of many minutes and hours. For more precise manual control of the camera in scripts, see the '''click "shoot_half"''', '''click "shoot_full"''', when used in conjunction with the '''get_tv, set_tv, set_tv_rel, get_av, set_av, set_av_rel''' commands below.

+

+

:Since revision 2529 (only CHDK 1.2) 'shoot' returns a control value.

+

+

:0 - shoot ok

+

+

:1 - shutter half press timed out (SD card full, etc)

+

+

:2 - shoot failed (twice) after half press

+

+

+

==Camera Button Commands==

+

These commands are designed to allow your script to control your camera much like you would manually. Nearly anything you can do by pressing buttons on your camera with your own fingers, you can also do automatically with these script commands. The complexity and time-line of your script is only limited by your imagination.

+

+

Camera button commands can be written in 3 flavors / command-methods:

*'''click "{{button|button-name}}"'''

*'''click "{{button|button-name}}"'''

Line 861:

Line 882:

</pre>

</pre>

−

==shoot==

−

:Records an image.

−

:Thiscommandissimilar to the '''click "shoot_full"''' command (see below), but it waits for the camera to perform some normally automatic actions, such as auto-focusing, charging the flash, etc. For example: if in AUTO, P, Tv, Av, or any SCN modes, using the "shoot" command causes the camera to check focus and exposure for each shot. When "shoot" is used in intervalometer scripts this far surpasses the camera's own built-in intervalometer in that the camera only sets exposure and focus once for the initial exposure, as if it was only using the "click 'shoot_full'" command. This "shoot" command in an intervalometer script allows it to compensate for all the things that can change over the course of many minutes and hours. For more precise manual control of the camera in scripts, see the '''click "shoot_half"''', '''click "shoot_full"''', when used in conjunction with the '''get_tv, set_tv, set_tv_rel, get_av, set_av, set_av_rel''' commands below.

+

===PossibleValidButtonNames===

+

+

The following is a list of button names recognized by CHDK. Note that one or more buttons are probably not available on any particular camera.

#press "shoot_full" activates both shoot_full and shoot_half. To release just shoot_full, use release "shoot_full_only"

+

#"fe" = microphone

+

#"remote" = status of USB connector +5V pin

+

#"no_key" is returned if wait_click times out

==click/press/release "up", "down", "left", "right"==

==click/press/release "up", "down", "left", "right"==

Line 884:

Line 903:

==click/press/release "shoot_full_only"==

==click/press/release "shoot_full_only"==

−

:Actuates only the shutter-release button "full press" internal switch. This is mostly useful where a click "shoot half" has been previously used and you wish to hold the focus and exposure locked. Doing a release "shoot_full_only" will then simulate only letting the shutter button up to the half-press position (whereas a release "shoot_full" simulates letting the shutter button return fully to the off position). (for more info, see [http://chdk.setepontos.com/index.php?topic=1444.0 this forum thread] )

+

:Actuates only the shutter-release button "full press" internal switch. This is mostly useful where a click "shoot half" has been previously used and you wish to hold the focus and exposure locked. Doing a release "shoot_full_only" will then simulate only letting the shutter button up to the half-press position (whereas a release "shoot_full" simulates letting the shutter button return fully to the off position). (for more info, see [http://chdk.setepontos.com/index.php?topic=1444.0 this forum thread] )

:There are several commands for getting and setting the aperture and the speed. They only work in Manual mode; well you can change the settings in any mode, but they are effective in manual mode, probably also in Av and Tv modes). I put a test script for these commands in the "user written scripts"

:For the S2/S3 IS the Av and Tv settings provide the following actual values:

−

−

Aperture Exposure

−

Value index Value index Value index

−

F/2.7 0 15" -12 1/15 12

−

F/3.2 10 13" -11 1/20 13

−

F/3.5 11 10" -10 1/25 14

−

F/4.0 12 8" -9 1/30 15

−

F/4.5 13 6" -8 1/40 16

−

F/5.0 14 5" -7 1/50 17

−

F/5.6 15 4" -6 1/60 18

−

F/6.3 16 3"2 -5 1/80 19

−

F/7.1 17 2"5 -4 1/100 20

−

F/8.0 18 2" -3 1/125 21

−

1"6 -2 1/160 22

−

1"3 -1 1/200 23

−

1"" 0 1/250 24

−

0"8 1 1/320 25

−

0"6 2 1/400 26

−

0"5 3 1/500 27

−

0"4 4 1/640 28

−

0"3 5 1/800 30

−

1/4 6 1/1000 31

−

1/5 7 1/1250 32

−

1/6 8 1/1600 33

−

1/8 9 1/2000 34

−

1/10 10 1/2500 35

−

1/13 11 1/3200 0

−

−

:For Tv, 2 values are equal, 1" and 1/3200 with 0.

−

−

−

CHDK Build 119 Remapped Values (* = change)

−

−

S3-IS (Should be the same on all camera models now? If so we can remove the previous tables. Please confirm on other models.)

−

<pre>

−

Aperture Exposure

−

Value index Value index Value index

−

* F/2.7 9 * 15" -12 1/15 12

−

F/3.2 10 * 13" -11 1/20 13

−

F/3.5 11 * 10" -10 1/25 14

−

F/4.0 12 8" -9 1/30 15

−

F/4.5 13 6" -8 1/40 16

−

F/5.0 14 5" -7 1/50 17

−

F/5.6 15 4" -6 1/60 18

−

F/6.3 16 3"2 -5 1/80 19

−

F/7.1 17 2"5 -4 1/100 20

−

F/8.0 18 2" -3 1/125 21

−

1"6 -2 1/160 22

−

1"3 -1 1/200 23

−

1"" 0 1/250 24

−

0"8 1 1/320 25

−

0"6 2 1/400 26

−

0"5 3 1/500 27

−

0"4 4 1/640 28

−

0"3 5 * 1/800 29

−

1/4 6 * 1/1000 30

−

1/5 7 * 1/1250 31

−

1/6 8 * 1/1600 32

−

1/8 9 * 1/2000 33

−

1/10 10 * 1/2500 34

−

1/13 11 * 1/3200 35

−

</pre>

−

−

−

;Usage Notes

−

:

−

−

When using the '''set_tv''', '''set_tv_rel''', or '''set_av''', '''set_av_rel''' commands it was found that it may not be effective if inserted into a sequence of commands that used the '''press''' and in some instances the '''click "button"''' commands. If when testing your script that you find these commands will not alter the shutter-speed or aperture, try moving them to a position just before any '''press "shoot_half/full"''' or '''click "timer"''' (unique s-series) commands. For an example see the [[uBASIC/Scripts: Lightning_Photography|"Lightning Photography"]] scripts on where the '''set_tv''' command had to be placed before it would work. It was tried in all other locations before the actual shooting was to begin, setting the shutter-speed in other locations in the script wouldn't work otherwise.

−

−

----

==set_zoom / set_zoom_rel / get_zoom / set_zoom_speed==

==set_zoom / set_zoom_rel / get_zoom / set_zoom_speed==

:Syntax:

:Syntax:

−

::'''set_zoom x''' (where x is 0 to 8, 14, or 129, see Range)

+

::'''set_zoom x''' (where x is 0 to 8, 14, or 127, see Range)

::'''set_zoom_rel x''' (x is +/- relative change)

::'''set_zoom_rel x''' (x is +/- relative change)

::'''x''' = '''get_zoom '''(zoom-step value placed in variable x)

::'''x''' = '''get_zoom '''(zoom-step value placed in variable x)

Line 1,188:

Line 1,059:

:Range:

:Range:

::A-series: x = 0 to 8 or 14 (9 or 15 steps)

::A-series: x = 0 to 8 or 14 (9 or 15 steps)

−

::S-series: x = 0 to 128 (129 steps)

+

::S-series: x = 0 to 127 (128 steps)

+

+

Note 1 ; this function has no effect on many Powershot camerass.

−

Note 1: Camera does not refocus automatically after the end of zooming. Use a click or press/release "shoot_half" command to implement a refocusing if needed.

+

Note 2: Camera does not refocus automatically after the end of zooming. Use a click or press/release "shoot_half" command to implement a refocusing if needed.

−

Note 2: It was found that if using the slowest speed (5), that an S3 IS might shut down after it has waited too long for the zoom to traverse the whole range of 129 steps, a speed of 10 did not exhibit this behavior on an S3 IS. 5 is '''so slow''' though, that I doubt it would rarely be needed, except in movie-shooting scripts, and then the range could be limited to prevent camera shut-down.

+

Note 3: It was found that if using the slowest speed (5), that an S3 IS might shut down after it has waited too long for the zoom to traverse the whole range of 129 steps, a speed of 10 did not exhibit this behavior on an S3 IS. 5 is '''so slow''' though, that I doubt it would rarely be needed, except in movie-shooting scripts, and then the range could be limited to prevent camera shut-down.

−

'''Note 3: CAUTION!''' (found on S3 IS) If '''set_zoom_speed''' is not written into the script when '''set_zoom x''' is used, the camera will refocus some of your optics to make it where the camera is unable to focus on anything in any mode. The camera (when zooming without a set-zoom speed) appears to move an internal lens element that puts the lens into a Super-Macro mode where it focuses on internal lens elements at widest-angle. If this command is left out of a script using the '''set_zoom x''' command, you will have to shut down your camera and restart it to reset the zoom-lens' optics back to defaults. However, an interesting thing is found -- when running the [[uBASIC/Scripts: Zoom_Shoot|"Zoom-Shoot"]] script by rem-ing out the set_zoom_speed command (removing it from being implemented), after the camera resets its zoom, the lens is now in a ZOOMED tele-macro SUPER-MACRO MODE! Giving you close-up focusing ability at fullest zoom! (as if you had placed a +4 or so close-up lens on your camera) Far surpassing the capabilities that Canon designed. Perhaps this "bug" could be put to great use? Or it might damage your focusing and zooming mechanisms. USE WITH CAUTION. Because you can hear the camera strain up against some internal lens-adjustment stops when it's trying to reset the zoom. And the only way to "un-do" this (really nice!) tele-super-macro mode is by turning the camera off and on again.

+

'''Note 4: CAUTION!''' (found on S3 IS) If '''set_zoom_speed''' is not written into the script when '''set_zoom x''' is used, the camera will refocus some of your optics to make it where the camera is unable to focus on anything in any mode. The camera (when zooming without a set-zoom speed) appears to move an internal lens element that puts the lens into a Super-Macro mode where it focuses on internal lens elements at widest-angle. If this command is left out of a script using the '''set_zoom x''' command, you will have to shut down your camera and restart it to reset the zoom-lens' optics back to defaults. However, an interesting thing is found -- when running the [[uBASIC/Scripts: Zoom_Shoot|"Zoom-Shoot"]] script by rem-ing out the set_zoom_speed command (removing it from being implemented), after the camera resets its zoom, the lens is now in a ZOOMED tele-macro SUPER-MACRO MODE! Giving you close-up focusing ability at fullest zoom! (as if you had placed a +4 or so close-up lens on your camera) Far surpassing the capabilities that Canon designed. Perhaps this "bug" could be put to great use? Or it might damage your focusing and zooming mechanisms. USE WITH CAUTION. Because you can hear the camera strain up against some internal lens-adjustment stops when it's trying to reset the zoom. And the only way to "un-do" this (really nice!) tele-super-macro mode is by turning the camera off and on again.

(Leaving this small chart here for reference, but is no longer applicable to the new set_zoom commands.)

(Leaving this small chart here for reference, but is no longer applicable to the new set_zoom commands.)

: If you are having problems using ''set_focus'', try putting your camera into P mode rather than Auto.

+

: Range:

+

: x = 0 to 65535 (millimeters)

+

: Many Canon P&S cameras will focus using just the ''set_focus'' command. If you are having problems using ''set_focus'', try putting your camera into P mode rather than Auto. If your camera has an MF (manual focus) mode you may need to enable it (possibly by issuing the sequence of ''click "ButtonName"'' commands for your camera) for ''set_focus ''to work, or use the [[Script_commands#set_mf|set_mf()]] script command. Enabling AFL mode may also enable the set_focus() function. Cheaper point-and-shoots do not typically have an MF mode but may have an AFL (auto focus lock) mode - check your user manual for instructions or use the [[Script_commands#set_aflock|set_aflock(1)]] script function. Also, set_focus may not work on cameras lacking the CHDK SD (subject distance) Override Menu.

−

: Note that most of the set_XXX commands happenwhen they are supposed to happen during the camera shooting process.So they should be called before shoot or shoot_half is called, and likely will not read back what yousetthem to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

+

: Note that most of the set_XXX commands takeplace during the camera shooting sequence,so they should be called before shoot or shoot_half is called, and will probably not read back what theyhavebeen set to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

−

: Note that ''set_focus ''(on all cameras?) requires the execution of "''shoot''" before it takes effect:

+

: Also note that ''set_focus ''(on all cameras?) requires the execution of "''shoot''" before taking effect:

@title focusTest1 script

@title focusTest1 script

print "Focus Test1!"

print "Focus Test1!"

Line 1,232:

Line 1,104:

end

end

−

:If you comment out the "''shoot''" above, you will see that the focus will not change.

+

:If you comment out the "''shoot''" above, you will see that the focus has not changed.

:Use of press/release "''shoot_half''" also works (focus is set correctly after the press and is retained after the release as well). And note also that the delay "''sleep 500''" after ''set_focus ''is required. If you remove the "''sleep 500''" below it will fail (Set!=B4, Set!=Aft).

:Use of press/release "''shoot_half''" also works (focus is set correctly after the press and is retained after the release as well). And note also that the delay "''sleep 500''" after ''set_focus ''is required. If you remove the "''sleep 500''" below it will fail (Set!=B4, Set!=Aft).

Line 1,255:

Line 1,127:

: When larger focus step changes are made, the end result reported by ''get_focus ''may be +/- 1 focus step from the ''set_focus ''value. So use caution if you loop waiting for ''get_focus ''to match.

: When larger focus step changes are made, the end result reported by ''get_focus ''may be +/- 1 focus step from the ''set_focus ''value. So use caution if you loop waiting for ''get_focus ''to match.

−

:More expensive Canon cameras with a manual focus mode may need to be put into manual focus mode (by issuing the sequence of ''click "ButtonName"'' commands for your camera) for ''set_focus ''to work. Cheaper point-and-shoots do not have manual focus mode and do not require this extra step. If your camera is missing the CHDK SD (subject distance) override menu, set_focus may not work for you.

+

:

==set_iso / get_iso==

==set_iso / get_iso==

Line 1,268:

Line 1,140:

==set_led==

==set_led==

−

LED lampconControl

+

Camera LED lampscontrol.

Usage:

Usage:

−

:::'''set_led a b c'''

+

:'''set_led a b c'''

−

*Note:thiscommandmaynot work on all cameras !

+

Parameter'''a'''istheLED-lamp.

−

+

:The valid values for '''a''' and the LED that corresponds to each value are different for every camera. Typically they will be values between 0 and 15. Determining the usable values for any particular camera requires either a trial & error process of trying every value or reading the source code in the lib.c file for that camera.

−

ItriedwithA560anditworked,butthereisno led 10 (and not 6).

+

:ThetablebelowshowsometypicalvaluesforA500seriescameras.

−

And I think these work with any A500-series camera.

−

−

Parameter '''a''' is the LED-lamp as follows:

<pre>

<pre>

Value of "a" LED Lamp

Value of "a" LED Lamp

Line 1,287:

Line 1,159:

10 Timer / Tally Lamp (bright orange lamp in front on S3)

10 Timer / Tally Lamp (bright orange lamp in front on S3)

</pre>

</pre>

−

Parameter '''b'''

−

0LEDis off

+

Parameter'''b'''sets the LED off or on.

−

1 LED is on

−

Parameter'''c'''(optional)

+

:0=LED is off

+

:1 = LED is on

−

brightness0 - 200, (Fingalosays,"Seemsto work only on the blue LED.")

+

Parameter'''c''' (optional)controlsLEDbrightness.

−

LedsworkonA560,but this don't work any led on A560

+

:c=0-200

+

+

Note : brightness only works on some early model Powershot cameras

+

+

Example Code:

−

Example:

<pre>

<pre>

rem Turn on AF_Lamp, Focus Assist Lamp

rem Turn on AF_Lamp, Focus Assist Lamp

Line 1,306:

Line 1,176:

</pre>

</pre>

−

'''IMPORTANT NOTE''': When using any LED lamp controls, remember to reset them to their original condition as they were before executing your script. Failure to do so may result in your power-indicator not alerting you that your camera still powered on. Or other important camera functions involving the LED lamps may not light at their proper times.

+

'''IMPORTANT NOTES'''

+

+

#This command may not work on all cameras !

−

Note 2: When testingthe Blue LED brightnessbyputting it in a for x=0 to 200loop to rampthevalueallthewayupin1valueincrements, then and back down again, it doesn't appear to behavelinearly.TheLEDrampsup,thenturnsoff,brieflyflashes,rampsupagain,flashes,then ramps down and flashes (or something similar to that). Isuspectitmightbeworkingfrom0to127usingbinary bit values. But I've nottesteditforthis.

+

#When usingany LED lampcontrols,remember to resetthem to theiroriginalconditionastheywerebeforeexecutingyourscript.Failure to dosomayresultinyourpower-indicatornotalertingyouthatyourcamerastillpoweredon. OrotherimportantcamerafunctionsinvolvingtheLEDlampsmaynotlightattheirpropertimes.

+

#When testing the Blue LED brightness by putting it in a for x=0 to 200 loop to ramp the value all the way up in 1 value increments, then and back down again, it doesn't appear to behave linearly. The LED ramps up, then turns off, briefly flashes, ramps up again, flashes, then ramps down and flashes (or something similar to that). I suspect it might be working from 0 to 127 using binary bit values. But I've not tested it for this.

==get_vbatt==

==get_vbatt==

Line 1,333:

Line 1,204:

:a = 0 then RAW recording is '''OFF'''

:a = 0 then RAW recording is '''OFF'''

:a = 1 then RAW recording is '''ON'''

:a = 1 then RAW recording is '''ON'''

−

−

*Note: There's a special parameter value (255) for [[Badpixel removal]]

Set "Dark Frame Subtraction" state (ON|OFF|AUTO); in earlier builds this was called "noise reduction" (nr).

+

Set "Dark Frame Subtraction" state (AUTO|OFF|ON).

Determines whether the camera will do a dark frame subtraction after taking a shot. Auto means the camera decides, OFF means no, ON means yes. Dark frame acquistion and subtraction typically occures for images with an exposure time of 2/3 of a second or longer. It does consume time (it's equivalent to taking another image at the same exposure time).

Determines whether the camera will do a dark frame subtraction after taking a shot. Auto means the camera decides, OFF means no, ON means yes. Dark frame acquistion and subtraction typically occures for images with an exposure time of 2/3 of a second or longer. It does consume time (it's equivalent to taking another image at the same exposure time).

Line 1,360:

Line 1,229:

Where:

Where:

:the variable a determines the state: 0=Auto 1=OFF, 2=ON

:the variable a determines the state: 0=Auto 1=OFF, 2=ON

−

==get_tick_count==

==get_tick_count==

−

This function returns the time, in milliseconds, since the camera was turned on. Note that this function format is a bit different from the standard CHDK uBasic function format.

+

This function returns the time, in milliseconds, since the camera was turned on.

Usage:

Usage:

Line 1,372:

Line 1,240:

==get_day_seconds==

==get_day_seconds==

−

This function returns the number of seconds since midnight. Note that this function format is a bit different from the standard CHDK uBasic function format.

+

This function returns the number of seconds since midnight.

Usage:

Usage:

Line 1,478:

Line 1,346:

−

=Enhanced & new commands=

+

=Enhanced Commands=

−

TheAllbestbuildisamajorrewriteofCHDK, in manyways. ItalsoincludesmanynewuBASICcommands. Below is a partiallistof [[CHDK_firmware_usage/AllBest#Current_List_of_uBASIC_Operations_and_Commands:|thecompletelistofavailablecommands]],thosewhichareunique to theAllbestbuild.Thesehavenotbeendocumented in totalyet,andmore uBASIC commandsarebeingaddedfrequently. (PleaseseetheCHDKforumfordiscussionsof any worksinprogress.)

+

NOTE:Syntaxusageinmostcasesis'''command_namex''', where x either sets or returns the value in thatcommand. Unlessstatedotherwise,assumethisusagesyntax. Otherwisethey may be acting as their own variable, and may be used as-is in a commandstring.Example: get_vbattisitsownvariable.Itcaneitherbe assigned to anothervariablewith'''x=get_vbatt''',orusedonits own as in '''printget_vbatt'''.Thedifferent types of uBASIC commandsyntaxwillbeclarified as needed or as discovered. (Developersdon'tdocumentthingsverywell.We,as end-users, sometimes have to find these things by trial-and-error, or be perceived as a major nuisance by hounding them for any cluesintowhat they did. :) I use both methods. :) )

NOTE: Syntax usage in most cases is '''command_name x''', where x either sets or returns the value in that command. Unless stated otherwise, assume this usage syntax. Otherwise they may be acting as their own variable, and may be used :as-is in a command string. Example: get_vbatt is its own variable. It can either be assigned to another variable with '''x=get_vbatt''', or used on its own as in '''print get_vbatt'''. The different types of uBASIC command syntax will be clarified as needed or as discovered. (Developers don't document things very well. We, as end-users, sometimes have to find these things by trial-and-error, or be perceived as a major nuisance by hounding them for any clues into what they did. :) I use both methods. :) )

+

===get_av96===

+

: This function returns the current aperature setting in APEX96 units.

: Returns the Av setting value in APEX96 units for M (manual) or Av (aperture priority) modes on cameras that support those modes.

+

+

===get_user_av_id===

+

: Returns the index into the aperature table found in the camera's CHDK shooting.c file for the current Av setting in APEX96 units for M (manual) or Av (aperture priority) modes on cameras that support those modes.

−

===get_av96===

−

This function returns the current aperature setting in APEX96 units.

===get_bv96===

===get_bv96===

−

This function returns the current brightness value in APEX96 units.

+

: This function returns the current brightness value in APEX96 units.

===get_dof===

===get_dof===

−

Get the depth of sharpness in mm, as calculated from your current focal length (zoom) and aperture (Av). Use it as a number in an equation: n = get_dof

+

Get the depth of sharpness in mm, as calculated from the current zoom and aperture (Av) values. Use it as a number in an equation: n = get_dof

−

You can do arithmetic directly with the '''''get_xxxx''''' variables. For example, to increase the focus value you already have stored in f by the depth of field, you can write

+

Arithmetic can be directly performed with the '''''get_xxxx''''' variables. For example, to increase the focus value already stored in f by the depth of field, write:

n = get_dof

n = get_dof

Line 1,501:

Line 1,368:

f = f + n

f = f + n

−

Or you can combinethe steps:

+

Or the steps can becombined:

f = f + get_dof

f = f + get_dof

===get_far_limit===

===get_far_limit===

−

Get the maximum distance of acceptable sharpness in mm. The difference between far limit and near limit is your depth of field. CHDK calculates the values from the cameras current focal length (zoom), aperture (Av), and focus distance.

+

Get the maximum distance of acceptable sharpness in mm. The difference between far limit and near limit is your depth of field. CHDK calculates the values from the cameras current focal length (zoom), aperture (Av), and focus distance.

n = get_far_limit

n = get_far_limit

Line 1,517:

Line 1,384:

n = get_hyp_dist

n = get_hyp_dist

−

Depth of field is that range of distances that are acceptably focused, given the lens's focal length (zoom), aperture (Av), and focus distance. Hyperfocal distance is the closest distance the lens can focus and still be sharp to infinity. When the subject distance (focus) is set to the hyperfocal distance, '''get_far_limit''' will equal infinity, and '''get_near_limit''' will be 0.5 * the focus distance.

+

Depth of field is that range of distances that are acceptably focused, given the lens's focal length (zoom), aperture (Av), and focus distance. Hyperfocal distance is the closest distance the lens can focus and still be sharp to infinity. When the subject distance (focus) is set to the hyperfocal distance, '''get_far_limit''' will equal infinity, and '''get_near_limit''' will be 0.5 * the focus distance.

+

+

===get_sv96===

+

: Returns the Speed Value (ISO, image sensor sensitivity) that the camera is set to in APEX96 units. Use in conjunction with set_sv96.

+

+

: ''uBasic Syntax: get_sv96 x''

+

: ''LUA Syntax: x=get_sv96()''

+

+

: Note that typically get_XXX is called at the beginning of a script after a shoot_half to grab what the camera would automatically set the value to. And then get_XXX is called after a set_xxx and shoot combination later in the script along with a print or log of the value to verify that the value read back matches what was set.

+

+

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

+

:

===get_iso_market===

===get_iso_market===

−

get "marketing" ISO (See the [[CHDK_firmware_usage/AllBest#Show_.27Real.27_ISO|Allbest's Firmware Usage page on ISO values]] for what is meant by a "Market Value".)

+

: get "marketing" ISO (see [[CHDK_firmware_usage/AllBest#Show_.27Real.27_ISO|ISO values]] for what is meant by a "Market Value".)

+

+

===get_iso_real===

+

+

: get real "value" ISO (see [[CHDK_firmware_usage/AllBest#Show_.27Real.27_ISO|ISO values]] for what is meant by a "Market Value".)

===get_iso_mode===

===get_iso_mode===

−

obtain ISO mode (the former get_iso)

+

: obtain ISO mode (the former get_iso)

:Eg. the A620 list

:Eg. the A620 list

Line 1,532:

Line 1,399:

:400-&gt; 400,

:400-&gt; 400,

−

===get_iso_real===

+

−

get real "value" ISO

===get_near_limit===

===get_near_limit===

Line 1,539:

Line 1,406:

n = get_near_limit

n = get_near_limit

−

''Near limit'' and ''far limit'' combine to define the camera's ''depth of field'' (see [http://chdk.wikia.com/wiki/CHDK_scripting#get_dof get_dof]), the range of distances that is acceptably sharp. CHDK calculates the values based on the current settings for focal length (zoom), aperture (Av), and focus distance.

+

''Near limit'' and ''far limit'' combine to define the camera's ''depth of field'' (see [http://chdk.wikia.com/wiki/CHDK_scripting#get_dof get_dof]), the range of distances that is acceptably sharp. CHDK calculates the values based on the current settings for focal length (zoom), aperture (Av), and focus distance.

−

===get_sv96===

−

: Returns the Speed Value (ISO, image sensor sensitivity) that the camera is set to in APEX96 units. Use in conjunction with set_sv96.

−

: ''uBasic Syntax: get_sv96 x''

−

: ''LUA Syntax: x=get_sv96()''

−

−

: Note that typically get_XXX is called at the beginning of a script after a shoot_half to grab what the camera would automatically set the value to. And then get_XXX is called after a set_xxx and shoot combination later in the script along with a print or log of the value to verify that the value read back matches what was set.

−

−

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

===get_tv96===

===get_tv96===

Line 1,561:

Line 1,420:

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

−

===get_user_av_id===

+

===get_user_tv96===

−

the former get_av. Get custom installation av (in the manual modes) for ID in CHDK

−

:Eg. the A620list

+

<p style="font-size:13px;margin-left:24px;">Returns the Tvsetting value in APEX96 units for M (manual) or Tv (shutter priority) modes on cameras that support those modes.</p>

−

::(9, 288, "2.8")

−

::(10, 320, "3.2")

−

::(11, 352, "3.5")

−

::(12, 384, "4.0")

−

::(13, 416, "4.5")

−

::(14, 448, "5.0")

−

::(15, 480, "5.6")

−

::(16, 512, "6.3")

−

::(17, 544, "7.1")

−

::(18, 576, "8.0")

−

:The first of values-in ID CHDK. The move to the next ID is, in fact, a shift in the 1/3 ev. The second value is a av * 96

−

:

−

−

===get_user_av96===

−

returns custom av * 96

===get_user_tv_id===

===get_user_tv_id===

−

returns CHDK identifier for the establisheduser manual modes tv.

+

: Returns the index in the aperture table found in the camera's CHDK shooting.c file for the current Avsettingin APEX96 units for M (manual) or Av (aperture priority) modes on cameras that support those modes.

+

===set_av96===

+

:Directly sets the aperature (in apex96 units). Rounds the passed parameter to the nearest standard Canon setting for the camera ( e.g. f5.94 rounds to f5.6 - values are stored in each cameras shooting.c file). Works in any mode.

−

:Eg. the A620list

+

: Note that most lower cost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutterspeed, ISO setting and a Neutral Density filter to determine the amount of exposure to the subject light that is allowed to reach the image sensor. See set_tv96_direct below.

−

::(-4, -128, "2.5")

−

::(-3, -96, "2")

−

::(-2, -64, "1.6")

−

::(-1, -32, "1.3")

−

::(0, 0, "1")

−

::(1, 32, "0.8")

−

::(2, 64, "0.6")

−

::(3, 96, "0.5")

−

::(4, 128, "0.4")

−

−

:::'''Important:''' earlier scripts just use the "get_tv" and "get_av" commands, these must be changed to this newer "get_user_tv_id" and "get_user_av_id" commands to make them work properly if using Allbest builds.

−

−

:This is part of possible values. Meaning load deflection on the id-the same as in the case of av

−

−

===get_user_tv96===

−

returns value installed in the user manual modes importance tv * 96

===set_av96_direct===

===set_av96_direct===

−

Directly set the aperture, without allowing Canon to round to the nearest 1/3stop. Theoretically precise to 1/96 of a full f/-stop, though the mechanics of the camera is unlikely to match that precision. Works in any mode.

+

:Directly set the aperture, without tryng to round to the nearest Canonsetting. Theoretically precise to 1/96 of a full f/-stop, though the mechanics of the camera is unlikely to match that precision. Works in any mode.

−

: Unlike the recommended set_tv96_direct which simply changes a timer, since this moves the aperture motor, use caution when using this function. It may be safer to use set_av96 below (assuming it alters your value to a safe setting beforeapplying-Idon'tknow...)

+

: Unlike the recommended set_tv96_direct which simply changes a timer, since this moves the aperture motor, use caution when using this function. It may be safer to use '''set_av96''' below ( it will alters the passed value to a safe setting fromtheshooting.c file associated witheachcamera'sCHDK port)

−

: Note that most lower cost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutter speed to determine the amount of exposure to the subject light that is allowed to reach the image sensor. See set_tv96_direct below.

+

: Note that most lower cost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutter speed, ISO setting and a Neutral Density filter to determine the amount of exposure to the subject light that is allowed to reach the image sensor. See set_tv96_direct below.

: set_av96_direct should allow you to use in-between values not in the table. Convert the desired aperture (f-stop) to and Av96 value with the formula:

: set_av96_direct should allow you to use in-between values not in the table. Convert the desired aperture (f-stop) to and Av96 value with the formula:

Line 1,583:

Line 1,442:

: Conversely,

: Conversely,

: '''f-stop''' = 2 ^ (''Av96'' / 192)

: '''f-stop''' = 2 ^ (''Av96'' / 192)

−

:CAUTION: The formulas above don't acknowledge any limits to the width or narrowness of your camera's aperture. Attempting to exceed the limits of your model may damage the aperture motor or mechanism.

−

===set_av_rel===

+

:'''CAUTION''': The formulas above doesn't acknowledge any limits to the width or narrowness of your camera's aperture. Attempting to exceed the limits of your model may damage the aperture motor or mechanism.

−

see "set_user_av_by_id_rel (compatibility)

−

===set_av96===

−

the installation av * 96 in accordance with acceptable Canon list for the camera. Works in any mode

−

−

: Note that most lower cost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutter speed to determine the amount of exposure to the subject light that is allowed to reach the image sensor. See set_tv96_direct below.

−

−

===set_av===

−

see "set_user_av_by_id (compatibility)

===set_iso_mode===

===set_iso_mode===

−

the installationofaregimeISO.

+

: Sets propcase PROPCASE_ISO_MODE to the ISOtableprop_idvalue from the iso_table[ ] in the camera's shooting.c file - indexed by thepassedparameter.

:Setsthesv96overridevaluebasedonaninputparamter in ISO sensitivityunits (real rather than market units).

===set_sv96===

===set_sv96===

−

: Used to set the Speed Value (ISO) with a APEX96 value. The Speed Value is the sensitivity of the camera's image sensor. Typically: higher sensitivity used for fast action shots at the expense of detail versus lower sensitivity used for slow/static shots with higher detail, but requiring longer exposure times.

+

: Used to set the Speed Value (ISO) with an APEX96 value. The Speed Value is the sensitivity of the camera's image sensor. Typically: higher sensitivity used for fast action shots at the expense of detail versus lower sensitivity used for slow/static shots with higher detail, but requiring longer exposure times.

: ''uBasic Syntax: set_sv96 x''

: ''uBasic Syntax: set_sv96 x''

: ''LUA Syntax: set_sv96(x)''

: ''LUA Syntax: set_sv96(x)''

−

: Note that you can determine the APEX96 value for ISO XXX by first setting your camera to ISO XXX then running a script which calls get_sv96 and prints the result. To set your iso: when chdk is not loaded: press set, then up to the top line then right to select the iso value, then set again. (Not sure whether the APEX96 values versus ISO values match from camera to camera, so this method will always work.)

+

: Note that you can determine the APEX96 value for ISO XXX by first setting your camera to ISO XXX then running a script which calls get_sv96 and prints the result. To set your iso: when chdk is not loaded: press set, then up to the top line then right to select the iso value, then set again. (Not sure whether the APEX96 values versus ISO values match from camera to camera, so this method will always work).

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

: Note that most of the set_XXX commands happen when they are supposed to happen during the camera shooting process. So they should be called before shoot or shoot_half is called, and likely will not read back what you set them to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

: Note that most of the set_XXX commands happen when they are supposed to happen during the camera shooting process. So they should be called before shoot or shoot_half is called, and likely will not read back what you set them to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

+

+

===set_tv96===

+

:Directly sets the shutter speed (in apex96 units). Rounds the passed parameter to the nearest standard Canon setting for the camera ( e.g. 1/105 seconds rounds to 1/100 seconds - values are stored in each cameras shooting.c file). Works in any mode but will limit the minumum and maximum shutter speed to the min and max value defined in the table.

===set_tv96_direct===

===set_tv96_direct===

−

: This is the recommended method of setting TimeValue (shutterspeed)fornew scripts. It uses a APEX96 value. Note that set_tv96 (no "direct" in the name) will ignore tv values which don't exactly match a standard camera value, while set_tv96_direct will set the exact value given. If you wish to stay within your camera's published shutter speeds (not required, but maybe you want to for other reasons) you can still use set_tv96_direct using the standard values. For standard values, refer to the table below (note that they are simply multiples of 32: N*32).

+

: This is the recommended method of setting shutterspeeds (TvorTimeValue). It uses an APEX96 value.

+

+

: Note that set_tv96 (no "direct" in the name) will round Tv values to a standard camera value, while set_tv96_direct will set the exact value given. If you wish to stay within your camera's published shutter speeds (not required, but maybe you want to for other reasons) use set_tv96. For a generic list of standard values, refer to the table below - actual values are camera dependent.

: ''uBasic Syntax: set_tv96_direct x''

: ''uBasic Syntax: set_tv96_direct x''

: ''LUA syntax: set_tv96_direct(x)''

: ''LUA syntax: set_tv96_direct(x)''

−

: Note that mostlowercost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutter speed set by this time value to determine the amount of subject light that is allowed to reach the image sensor. But don't be concerned; because of the increased sensitivity of digital image sensors (versus film), the results are still excellent after the cost reduction of removing aperture control. Note that these lower cost cameras use the Neutral Density Filter to compensate for the lack of aperture control (see http://chdk.wikia.com/wiki/ND_Filter). You will likely want to disable this filter by issuing the command set_nd_filter(2) to give yourself complete control of exposure.

+

: Note that manylessexpensive Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the ISO setting, a Neutral Density filter and the shutter speed set by this time value to determine the amount of subject light that is allowed to reach the image sensor. But don't be concerned; because of the increased sensitivity of digital image sensors (versus film), the results are still excellent after the cost reduction of removing aperture control.

−

: If your exposures stillseem to contradict what you expect, try setting your camera to a fixed ISO setting (instead of auto iso).WhenCHDKis not loaded do: press SET to bring up the hidden menu most do not realize is there, scroll up to the top entry (usually) then right/left to choose iso speed. Alternatively, in your script, perform a get_sv96 at the beginning of your script '''after '''a shoot_half (which will grab the autoiso value the camera thinksyoushoulduse, or your fixed setting if not autoiso), then perform a set_sv96 (with this grabbed value) coupled with your set_tv96_direct '''before '''the actual shoot/shoot_half when taking your shots.

+

: If your exposures arenot what you expect, try setting your camera to a fixed ISO setting (instead of auto ISO) whenusingset_tv96_direct. Alternatively, in your script, perform a get_sv96 at the beginning of your script '''after '''a shoot_half (which will grab the autoiso value the camera determinesshouldbeused, or the fixed setting if not autoiso), then perform a set_sv96 (with this grabbed value) coupled with set_tv96_direct '''before '''the actual shoot/shoot_half when taking shots.

−

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name).

+

: If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX values multiplied by 96 (thus the 96 in the name).

−

: Note that most of the set_XXX commands happen when they are supposed to happen during the camera shooting process.So they should be called before shoot or shoot_half is called, and likely will not read back what you set them to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

+

: Note that most of the set_XXX commands happen when they are supposed to happen during the camera shooting process,so they should be called before shoot or shoot_half is called, and likely will not read back what you set them to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

: Non-standard Shutter speed tv96_direct values can be calculated with this formula:

: Non-standard Shutter speed tv96_direct values can be calculated with this formula:

:Sets the aperture to be used (in APEX96 units) on cameras with M (manual) or Av (aperture priority) modes when those modes are selected. Overrides the values set by the Canon UI.

−

−

===set_tv96===

−

: Not recommended as results can be unpredictable. See set_tv96_direct above.

−

direct tv installation * 96 from a list of valid values CANON (this value type N * 32. N for the A620 can have values from -12 to 32. works by installing excerpts from the CHDK interface

−

−

===set_tv===

−

see "set_user_tv_by_id" (interoperability)

===set_user_av_by_id_rel===

===set_user_av_by_id_rel===

−

avinstallationon the currentuseronbias.Theoffsetindicated in Id. The Idrationalewaslistedabove.

+

:Like'''set_user_av96''' (above) except that the aperturesettingusedistakenfromthe aperture table for the camera in the CHDK shooting.c file. The actualvalueusedfromthe table is determined by the index value passed as a parameter to the function.

===set_user_av_by_id===

===set_user_av_by_id===

−

CustomInstallationavaccordingto the Id in CHDK. The pointaboveid-

+

:Like '''set_user_av96''' (above)exceptthatthe aperture setting used is taken from the aperture table for the camera in the CHDK shooting.c file. The actualvalueused from the table is the current value in the table the offset by the index value passed as a parameter to the function.

the installation of custom Tv * 96. Of the number of allowable and non C

−

===ExampleExposure Setting Script===

+

<pstyle="font-size:13px;">

−

:If you are using this to set a shutter speed, set it to 138*ln(x), where x is the time in seconds.

+

</p>

−

::Example of usage (set_shutter for Ixus) by Allbest

+

===set_user_tv96===

+

: Sets the shutter speed to be used (in APEX96 units) on cameras with M (manual) or Tv (shutter priority) modes when those modes are selected. Overrides the values set by the Canon UI.

−

:::@title Shutter TEST

+

===set_user_tv_rel_by_id===

−

:::sleep500

+

: Like '''set_user_tv96''' (above) except that the shutter speed setting used is taken from the shutter speed table for the camera in the CHDK shooting.c file. The actual value used from the table is determined by the index value passed as a parameter to the function.

−

:::rem initiation

−

:::press "shoot_half"

+

===set_user_tv_by_id===

−

:::release"shoot_half"

+

: Like '''set_user_tv96''' (above) except that the shutter speed setting used is taken from the shutter speed table for the camera in the CHDK shooting.c file (comment: might be an idea to link to this table - SkepticaLee). The actual value used from the table is the current value in the table the offset by the index value passed as a parameter to the function.

:If you are using this to set a shutter speed, set it to 138*ln(x), where x is the time in seconds.

−

:::end

+

:Example of usage (set_shutter for Ixus) by Allbest

+

@title Shutter Test

+

sleep 500

+

rem initiation

+

press "shoot_half"

+

release "shoot_half"

+

get_tv96 t

+

<nowiki>:set_shutter

+

print "Tv set to",t

+

wait_click

+

is_key k "set"

+

if k=1 then goto "k_set"

+

is_key k "down"

+

if k=1 then t=t-32

+

k=0

+

is_key k "up"

+

if k=1 then t=t+32

+

k=0

+

set_tv96_direct t

+

goto "set_shutter"

+

:k_set

+

shoot

+

end</nowiki>

===wheel_right===

===wheel_right===

−

Simulates the movment of the jog dial one click clockwise.

+

: Simulates the movement of the jog dial one click clockwise.

===wheel_left===

===wheel_left===

−

Simulates the movment of the jog dial one click counterclockwise.

+

: Simulates the movement of the jog dial one click counter clockwise.

===get_autostart===

===get_autostart===

−

parameter checking autostart for scripts

+

: Parameter checking autostart for scripts.

−

+

: Syntax: '''x=get_autostart''' (or used as its own variable string in calculations, see get_vbatt example)

−

::Syntax: x=get_autostart (or used as it's own variable-string in calculations, see get_vbatt example)

===set_autostart===

===set_autostart===

−

Setting this option to autostart scripts

+

: Set this option to autostart scripts.

−

+

: Be careful with these commands. Autostart opens the script when the camera is turned on.

−

:With these commands should be cautious. Specified Autorun leads to the script when you turn a camera on.

===get_usb_power===

===get_usb_power===

−

checking for USB connectivity. Works for series A and S-asa minimum.

+

: Checks for USB connectivity. Works for A and S series.

−

+

: Syntax: '''x=get_usb_power'''

−

:Syntax x=get_usb_power

−

===shut_down===

===shut_down===

Line 1,758:

Line 1,631:

:Example, '''if x=(some calculation) then shut_down''', or just used as a line on its own at the end of your script.

:Example, '''if x=(some calculation) then shut_down''', or just used as a line on its own at the end of your script.

−

:Note: in Lua, you can also use ''post_levent_to_ui('PressPowerButton')'' which may prove to be more reliable as it will be treated by the camera firmware just like a real power button press

+

:Note: in Lua, ''post_levent_to_ui('PressPowerButton')'' can also be used, which may prove to be more reliable as it will be treated by the camera firmware just like a real power button press.

:

:

Line 1,799:

Line 1,672:

=USB Remote Cable-Release Function=

=USB Remote Cable-Release Function=

−

This amazing feature was found by a talented Ukrainian programmer known as Zosim. You may find his original source code and executable binaries for the A710 IS camera at [http://ewavr.nm.ru/chdk/ CHDK binaries and source] and [http://ewavr.nm.ru/chdk/remote.htm photos to build simple cable-release switch]. Fingalo and Microfunguy have both added this remarkable addition to their builds of CHDK.

+

This amazing feature was found by a talented Ukrainian programmer known as Zosim. You may find his original source code and executable binaries for the A710 IS camera at [http://ewavr.nm.ru/chdk/ CHDK binaries and source] and [http://ewavr.nm.ru/chdk/remote.htm photos to build simple cable-release switch].

−

BeSURE to also check out the [[CHDK_firmware_usage#Special_Builds_Features|'''Special Builds Features''']] in the Firmware Usage page for two new Script Menu items on howyou can usethisfeaturetocompletelyoperateyourcamerabyremotecontrolonly. From turning it on to executing your last loaded/used script.

Using nothing more than a 3-volt button-battery and a small switch, you may turn any USB extension cable into a remote shutter release by running a small script. Or by using this script method as a subroutine within your own much more complex scripts.

−

−

:<s>NOTE: This feature is only available to camera models A610, A620, A630, A640, A710, and S3 IS so far. It is unknown at this time if it is adaptable to the other cameras supported by CHDK. (Though, I get the feeling someone will eventually find a way.)</s>

−

−

::The above is no longer true. Most all the cameras are supported for the Remote USB feature, and most all of the different builds also include it now.

−

−

:<s>'''IMPORTANT''': With this remote function in these builds the camera will not enter download mode when connecting your computer's USB cable while CHDK is loaded. For normal camera to computer download mode just disable CHDK by turning off write protect on the SD card. However, while CHDK is running a USB-Remote script you may use the USB connection of your computer to easily test that all is working properly. When connecting camera to computer the 5-volts on the computer's USB port will be detected and activate your script command(s).</s>

−

−

::The above is no longer true on more recent builds of CHDK. There are now two new functions available in the Scripting Menu to enable or disable remote sensing so that you may still download images from your camera while CHDK is still loaded and running as well as a setting to allow activating the last loaded script. See the "[[CHDK_firmware_usage#Special_Builds_Features|Special Build Usage]]" section for a little more info.

Running this small script (or the loop embedded as a subroutine in more lengthy scripts) is all you will need:

−

−

<pre>

−

@title Remote button

−

:loop

−

wait_click 1

−

is_key k "remote"

−

if k=1 then shoot

−

goto "loop"

−

end

−

</pre>

−

−

Or, if using Fingalo's builds you may like his version with the simpler '''while/wend''' loop commands:

−

−

<pre>

−

@title Remote button

−

while 1

−

wait_click 1

−

if is_key "remote" then shoot

−

wend

−

−

end

−

</pre>

−

−

There are many ways of using this "remote" key function, these are just two of the more simple (and faster) ways to implement it.

−

That's it! That's all you need! Well, one of those little scripts, the right CHDK build, and the [http://ewavr.nm.ru/chdk/remote.htm cable-switch] (this link is 404 - [[User:Soapytoo|Soapytoo]] 22:50, July 14, 2010 - use http://chdk.wikia.com/wiki/USB_Remote_Cable instead) too. :-)

Between MX3's Motion-Detection options and this amazing USB cable-release method, there is no limit to the various ways you may control your camera by remote means. Any simple electronic circuit that can close a switch and feed a 3v to 5v DC signal to the USB port's proper contacts (observe proper polarity!) can now be used. There is also no limit to the length of wire that you may use, as long as you keep the final contact voltage at the camera-end between the 3vdc and 5vdc range. Use sound-sensitive circuits to record when sound-events happen. Use light or motion changing events to trigger shooting sessions. Use any CHDK intervalometer scripts or electronic intervalometer circuits to trigger shots. (There are thousands of simple circuits like these all over the internet.) Have your mouse or cat press a switch to record their vanity-quotient for a science-fair project! The sky (literally) is the limit to how many ways you may use these functions.

Between MX3's Motion-Detection options and this amazing USB cable-release method, there is no limit to the various ways you may control your camera by remote means. Any simple electronic circuit that can close a switch and feed a 3v to 5v DC signal to the USB port's proper contacts (observe proper polarity!) can now be used. There is also no limit to the length of wire that you may use, as long as you keep the final contact voltage at the camera-end between the 3vdc and 5vdc range. Use sound-sensitive circuits to record when sound-events happen. Use light or motion changing events to trigger shooting sessions. Use any CHDK intervalometer scripts or electronic intervalometer circuits to trigger shots. (There are thousands of simple circuits like these all over the internet.) Have your mouse or cat press a switch to record their vanity-quotient for a science-fair project! The sky (literally) is the limit to how many ways you may use these functions.

Line 1,876:

Line 1,707:

rem If this line is left out and a&gt;=0 then an error

rem If this line is left out and a&gt;=0 then an error

rem (unk statement or unk label) will be generated

rem (unk statement or unk label) will be generated

−

:nega

+

<nowiki>:</nowiki>nega

----

----

Line 1,888:

Line 1,719:

===Using the UBASIC_TEST.EXE Console===

===Using the UBASIC_TEST.EXE Console===

−

:Download this small file http://grandag.nm.ru/hdk/ubasic_test.rar (BEWARE - LINK&nbsp;TRIES&nbsp;TO&nbsp;INSTALL&nbsp;ADWARE&nbsp;ON&nbsp;YOUR&nbsp;COMPUTER!&nbsp; SUGGEST&nbsp;FINDING&nbsp;THE&nbsp;FILE&nbsp;ELSEWHERE). &nbsp;UnRAR (like UnZIP) it to your scripts working location on your hard-drive. You should have a file named ubasic_test.exe in your scripts-work folder now. You have to run this program from a Windows Command Prompt (the old time DOS window). Some people have a "Launch Command Prompt Here" on the right-click menu of Windows Explorer, so you can just right-click on the folder where your scripts and ubasic_test.exe file reside. (You can get this by installing "Open Command Window Here" Power Toy, available [http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx here].) Or you can go to Programs &gt; Accessories &gt; Command Prompt (where I have mine for some reason). And use the CD command to Change Directories until you get to where your scripts and ubasic_test.exe file reside. For example, if you start out in root directory C:\ and your scripts are on drive D: in a sub-folder called CHDK\Files\Scripts\, at the command prompt just type

+

:Download this small file http://web.archive.org/web/20070806121635/http://grandag.nm.ru/hdk/ubasic_test.rar (BEWARE - LINK&nbsp;TRIES&nbsp;TO&nbsp;INSTALL&nbsp;ADWARE&nbsp;ON&nbsp;YOUR&nbsp;COMPUTER!&nbsp; SUGGEST&nbsp;FINDING&nbsp;THE&nbsp;FILE&nbsp;ELSEWHERE). &nbsp;UnRAR (like UnZIP) it to your scripts working location on your hard-drive. You should have a file named ubasic_test.exe in your scripts-work folder now. You have to run this program from a Windows Command Prompt (the old time DOS window). Some people have a "Launch Command Prompt Here" on the right-click menu of Windows Explorer, so you can just right-click on the folder where your scripts and ubasic_test.exe file reside. (You can get this by installing "Open Command Window Here" Power Toy, available [http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx here].) Or you can go to Programs &gt; Accessories &gt; Command Prompt (where I have mine for some reason). And use the CD command to Change Directories until you get to where your scripts and ubasic_test.exe file reside. For example, if you start out in root directory C:\ and your scripts are on drive D: in a sub-folder called CHDK\Files\Scripts\, at the command prompt just type

cd D:\CHDK\Files\Scripts

cd D:\CHDK\Files\Scripts

:and you'll be where you're supposed to be. (You might want to rename that little program to just test.exe to make it easier to type each time.)

:and you'll be where you're supposed to be. (You might want to rename that little program to just test.exe to make it easier to type each time.)

Contents

Scripts may conflict with your camera if it is set to its fully automatic state. If you are having problems try setting your camera into "P" mode. When CHDK is not loaded: press the cam/movie button then the right button until P is highlighted and press SET. Also consider setting your camera to a fixed ISO value instead of AutoISO. When CHDK is not loaded: press the SET button, then scroll up to the top and right to a fixed ISO value.

Use a plain text editor to compose your scripts. Make sure it saves the file as TEXT-ONLY. Do NOT use programs like Word, wordpad or other advanced editors. These insert hidden header info and use non-standard ASCII characters for Return/Line-Feed commands, quotation marks, and others. The simplest of text editors will suffice (Notepad in Windows, nano in Linux for example). Scripts must be saved as ASCII plain text. UTF-8 may work, but is not recommended because some editors insert a unicode BOM at the start. Mac users see this special note concerning Macs and Script Files.

Keep all commands in lower-case. Variables are, however, case-sensitive (a and A are not the same).

Be aware that not all commands work on all cameras. If you plan on sharing your script try to keep it as generic as possible unless you have a special need for the camera-specific commands. Try to also provide a more generic version so that all may benefit from it.

Keep your script concise and efficient! It takes 10ms of time for each line of script to be interpreted by tiny uBASIC. A script 10 lines long takes 1/10th of a second, 100 lines takes a full second, etc. This can greatly impact high-speed uses.

If you write an interesting script, share it with the rest of us at User Written Scripts so we may learn from you! Beginner script writers can be some of the most creative! Also if you are just starting out use the page for ideas and examples.

Have a look at the settings in the scripting menu, there are some interesting features available such as autostart, parameter sets & more...

Let's break down what each of those lines mean and how they are used by CHDK.

@title Your Script Title

This is the title that will appear when you have the script loaded in CHDK and go to "Scripting Parameters" menu selection. It will appear under the line "----Current Script----" as well as in the lower-left corner of your viewfinder when you are in <ALT> mode. Keep your title short (24 characters or less). Otherwise the title will cover up the <ALT> label.

@param x (label)

@default x n

@range x n m

This is where you will define the beginning values of any variables used in your script. These are often used to set how many exposures you want, how long of a delay you want, how many bracketing steps you want, etc. These variables can be changed by the end-user from the "Scripting Parameters" menu items. In that sub-menu, they will appear under the line "----Script Parameters-----"

@param x (label)

The "x" in that line will be one of any lower-case latin letter from a to z. The (label) is the text string that will appear in your "----Script Parameters----" list, to let the end user know which of the variables they are changing (i.e. number of shots, how many steps, etc.).

Up to 26 @param statments, user-controllable variables, may be used in any one script.

Note: CHDK allows you to have up to 26 user-definable variables from a to z. There are a total number of 52 variables available for your use, a to z and A to Z, but the user-definable variables must be in lower-case if used for that purpose. Also be aware that lower and uppercase variables are unrelated. If you use a lower-case j for a variable, it is not the same as using J, and vice-versa.

@default x n

This optional statement sets up the default, or beginning value of your (lower-case letter) variable, where "x" is the variable from the @param statement above, and "n" is the default value to start with. This value is only used when a script is loaded for the first time.

Note it is up to the script writer to ensure that the @default value lies within @range - this is not validated when the script is loaded.

Note also that defining a range will override setting string values (see next section).

@values x aaa bbb ccc ddd eee (CHDK release 1.2.0 and later only)

This optional statement specifies a list of strings that are can be scrolled by the user to select a parameter value. The parameter value will be the position of the chosen string in the list (starting with 0). String values will only be assigned if there is no "@range" statement. Usage example:

@param f Channel (U,Y,V,R,G,B)
@default f 1
@values f U Y V R G B

In this case the string "Y" is the default, as f has the default value of 1.

If a variable had to be assigned the three values of -1, 0 and 1 via corresponding strings, then the three strings would be defined as "@values" with initial values of 0, 1, and 2, then 1 is subtracted in the body of the script:

@param f Brightness Threshold
@default f 1
@values f Darker Off Lighter
f=f-1
rem f now has the values of -1 for "Darker", 0 for "Off", and 1 for "Lighter"

Notes

If there is no @title command the filename of script is used.If there are no @param commands CHDK assumes that there are three adjustable variables: a, b and c.Remember -- when naming @param variables, use only a character from a through z.

After default variable values have been defined here, it is good to add some lines right after this section to ensure those numbers will be used in case the user has input 0 (zero) for some value that needs to be higher (or lower). This can be seen in scripts as:

if a<2 then let a=5

If the default value that you wanted the user to start out at for parameter variable a was 5, then if they left that setting at 0 (zero) or 1, then this will automatically increase that variable's value back up to 5.

After variable parameters have been initialised comes the brunt of your script, the part that does the actual work and tells the camera what to do, when to do it, and what buttons or commands need to be executed. Since we are working with a very small subset of the larger uBASIC programming language, it might be good to list and explain only those that are available to the CHDK script writer.

All programs are designed to mindlessly repeat some commands. In order to make them work in the proper order, and the correct number of sequences, they have to be contained in some simple recurring loops and counters. Testing for when some condition has been met, before it can go onto the next command, or finally end the program (script).

There are several ways this can be done in uBASIC. By using numeric counters, and loops.

This one is simple. If you see a command that says "let a = 2" then that's exactly what happens. It defines the value of 2 to the variable a.

This command is mostly included just for legibility. You can leave off the let command and it will still work. Example: let a=2 can be written more simply as a=2. Or this example: if z>5 then let b=0 can be simplified to if z>5 then b=0. Doing so will greatly save on script space if you have to define and redefine many variables many times.

These are used to set up simple loops. You will often see them in scripts as in this example:

for n=2 to a
sleep t
print "Shoot", n, "of", a
shoot
next n

The first line "for n=2 to a" means that the "for / to / next" loop will run while variable-n equals the sequence of numbers of 2 up to whatever the number variable-a has been assigned to. The commands that take place in the loop are containted between the FOR statement and the NEXT statment. "next n" tells the loop to go back to the beginning "for ..." statement until the the a value has been reached.

For example:

for n=1 to 10
print "This is line number", n
next n

This will produce the sequence of:

This is line number 1
This is line number 2
This is line number 3
.
.
.
This is line number 9
This is line number 10

And then that loop will end and go onto the next sequence of commands.

A standard BASIC step command was added to the for/to/next commands make loops easier. Instead of using multiple lines for counters to increment numeric expressions with commands like a=a+1 or b=b-3, a simple next command may now be used.

Usage:

for var=expr to expr step expr

statement

statement

statement

...

next var

Where var can be any variable, expr can be any defined variable or math expression, and step can be any defined variable or math expression. The step value may also be negative to increment in reverse.

If using the default values this simple script will start out at the Near Focus value of 2500mm, increment that value by 100mm every time, shoot an image, and exit when the focus has reached or passed 4500mm.

For complex programming tasks, it is often helpful to split the program into smaller subroutines that can be called with gosub and goto commands. A sub-routine can be nearly anything but it is generally used for a set of commands that will be called-up more than once. Instead of writing the same set of commands over and over again you put that code into a subroutine and then call it up from within the main program by using gosub "label" or goto "label". Subroutines are generally placed after the main code. A labeled subroutine that will be called by gosub "label" needs to end with the return comand, to tell the script to jump out of that section of code and return back to from where it was called.

GOSUB and GOTO are similar but you should refrain from using GOTO unless you know what you are doing. GOSUB will always return from a subroutine as soon as it reaches the RETURN command. GOTO does not behave this way. GOTO should only be used when you are going to jump to a section of the script one time and under special circumstances.

A simple GOSUB example (the subroutine's label and subroutine are in bold):

for x=1 to 10
gosub "display"
next x
:display print xreturn

A longer example that would capture three images with increased ISO settings would look something like this:

shoot
for i=1 to 3
gosub "incISO"
shoot
next i
for i=1 to 3
gosub "decISO"
next i
end
:incISOclick "menu"[some more clicks]return:decISOclick "menu"[some more clicks]return

An example using the GOTO command taken from an endless intervalometer script. NOTE: This situation creates an endless loop. Until you manually override, the script it will continue. This is generally considered BAD FORM! Any script should include/end-with all the commands to reset the camera to its original configuration prior to running the script, and properly end with the END command. Do not do this kind of thing, unless you have a special need for it and know what you are doing.

Another method of creating loops for repetitive instructions or when waiting for some condition to be true. Code within a Do/Until loop will always be executed at least once (unlike While/Wend loops)

Usage:

do

statement

statement

statement

...

until relation

Where relation may be any logical expression. When it is true, the loop will exit.

Example:

rem set some starting values for the variables
y=0
x=5
rem start do-loop
do
rem increment x by 10 each time
x=x+10
rem increment y by 1 each time
y=y+1
rem print results to viewfinder mini-console
print "This DO loop happened", y; "times."
rem repeating do-loop until x is equal to the value of 55
until x=55
end

Similar to the DO / UNTIL loops. The loop will continue to execute while some statement remains true, and will end, wend (while-end), when that statement is no longer true. Unlike Do/Until loops, code within a While/Wend loop may never be run, if the test condition is already false when the While statement is first reached.

Usage:

while relation

statement

statement

statement

...

wend

Example:

x=0
while x<200
x=x+25
print "The value of x is", x
wend

This loop will increment the value of x by 25 each time and print the value of x, as long as (while) the variable x remains less-than 200

The "rem" (which stands for "remark") command is sometimes used to place a comments in a script. It is only used as a reminder for the person writing or viewing the script, like an internal note. This command is not executed nor seen when the script is run. However, keep in mind that scripts for CHDK can be only 8k (8,192 characters) in length. (Only 2k in CHDK before Build 119.) Too many REM statements can slow down your script as well as taking up valuable space.

REM statements can always be removed from a script if you feel there are too many or unneeded. Removing a rem line will not impact the operation of the script in any way (other than speeding it up and using up less memory space).

Most of the expressions are easy to understand, but the % (remainder) operation might like a short explanation.

Example: Let's say you have computed a number to equal how many seconds something will take for a duration. Such as s=(some math expression) Where s is being assigned the number of seconds computed.

In math it's called "modulo".

Now you want to display that as minutes and seconds. You will need a print statement such as:

print "Total Time:" , s/60; "min", (the remainder of s/60); "sec"

There is a very simple way to do this using the % command. Think of % as "the remainder of s being divided by". So all you need to do is have this print statement:

print "Total Time:" , s/60; "min", s%60; "sec"

If s had the value of 328 seconds, then this would print out to

Total Time: (328/60)=5 min (the remainder of 328/60)=28 sec

or more simply

Total Time: 5 min 28 sec

Some further notes:

< Less Than
> Greater Than
= Equal
<= Less Than or Equal
>= Greater Than or Equal
<> Not Equal

are relational operators. In "if" statements, only single relational operators are allowed. This means, you can't have something like "if a<2 and b>3 then...". Strike-out portion no longer applicable to build #144 or later.

& And
| Or
^ Xor

are bitwise operators, not logic operators. (The logic operators of and, or, and not have been added to CHDK build #144 or later.) Example use of the bitwise &, |, and ^ binary operators are:

e=5|3
print e

will return "7".
5&3 will result in "1"
5^3 will result in "6"
For an explanation refer to bitwise operators

The print_screen function enables/disables logging to a file a copy of print statements to the mini-console screen.

uBASIC :

To enable file logging, call print_screen with a non-zero value. This will create a log file in the /CHDK/LOG directory with name LOG_nnnn.TXT, where nnnn is the absolute value of the parameter you passed to the print_screen statement.

If the passed value is negative, the log will append to the end of the exiting log file. If the passed value is positive, the old file will be overwritten. If the passed value is zero, the logging will be disabled.

Example:

@title uBASIC Printscreen Test
@param a None
@default a 0
set_console_layout 0 0 45 12
print "uBASIC : this is not written to a file"
print_screen 5
print "uBASIC : this is written to file LOG_0005.TXT"
print "a="a
print "done"
print_screen 0
print "This is not written to file"
print_screen -5
print "This is written at the end of LOG_0005.TXT"
print_screen 0
end

Lua

To enable file logging, call print_screen() with a non-zero value. This will create a log file in the /CHDK/LOG directory with name LOG_nnnn.TXT, where nnnn is the absolute value of the parameter you passed to the print_screen statement.

If the passed value is less than 0, the log will append to the end of the exiting log file. If the passed value is greater than 0, the old file will be overwritten. If the passed value is a 0 or boolean false, logging will be disabled. If the passed value is a boolean true, a new log file LOG_0001.TXT will be created.

Example:

--[[
@title Lua Printscreen Test
@param a None
@default a 0
--]]
set_console_layout(0,0,45,12)
print("Lua : this is not written to a file" )
print_screen(5)
print("Lua : this is written to the file LOG_0005.TXT")
print("a=",a)
print("done")
print_screen(false)
print "This is not written to a file"
print_screen(-5)
print "This is written to the end of file LOG_0005.TXT"
print_screen(false)

cls stands for "Clear Screen". This is used to clear the mini-console screen from any "print" statements in an easy way. Instead of having to issue 5 command lines of print " ", you just need to issue this one small cls command.

This command returns the current ALT state. This can be used to by a script so that it does not attempt to read button pushes or to update the LCD when the CHDK has left ALT mode while the script is still running (possibly because the user pressed the ALT key).

Lua : function returns true if CHDK is currently in ALT mode and false otherwise.

uBasic : function return 1 if CHDK is currently in ALT mode and 0 otherwise.

This should be the last line of every uBASICC script. It tells the script to cease all operations and return camera control back to you. Before ending a script, it is good-form to always reset any camera settings that the script took control of during initialization of your routine or during. So that the end user doesn't have to undo all the keypresses and menu changes that the script created.

Note 1: There has been much discussion on the proper ways to use this sometimes-confusing and highly adaptable and user-configurable feature. A lengthy discussion on the new CHDK Forum on how to get the fastest reaction times for lightning photography has shed some light on the subject (pun not intended). For further clarification on the best ways to implement some of the timing controls, see this post in the "Motion Detection Too Slow?" discussion thread. Which also includes a script optimized to obtain the fastest detection speed possible by using 2 different methods (both available in the same script). The MD routine has been reworked for some cameras so the internal "immediate shoot" option is now lightning-fast (literally). This change will probably be added to all new future builds (note added 2008-02-07 c.e.).

Note 2: Hints and tips for usage have been scattered all over the net, a new "Motion Detection Settings" page was created to try to assemble some of the best tips. If you can add to it or help clarify it, please do so. The page linked in the strike-out comment is wholly irrelevant as-is. The info there was taken out of context from another post discussing a script that uses the md-routine, and has no information about the md command itself. A good idea poorly implemented. If you would still like to create a more concise and clear explanation of all of the md parameters and usage, with sample script explanations, feel free to use that page, Delete everything on it if you have to and start from scratch. Otherwise, don't even bother reading it, it's useless as is. Its existence only creates more confusion the way it stands now and is subject for complete deletion. [mr.anon]

The minumum number of variables that must be set with this command are:

md_detect_motion a, b, c, d, e, f, g, h

Timeout: [mx3]it is time in milliseconds for which md_detect_motion will block execution of next ubasic commands if during this period no motion detected. this parameter is useful if you want to execute periodically some other ubasic commands together with MD.

i.e. MD routine waits for changes for 1 second. if no motion detected script can continue to execute some other code and then if required can resume motion detection by calling again md_detect_motion.
so timeout is just time for which md routine will wait for changes. Practically, this TIMEOUT value (parameter d) shall be greater than the MILLISECONDS DELAY (parameter p), or else you will always get RETURN VARIABLE (parameter h)=0. (feel free to change this text to be better English)[/mx3]

Comparison Interval: The time delay in milliseconds in which to check for a change in a cell's values. If you need to filter out small changes made frequently by faster moving objects (leaves in the wind, or flying insects, for example) you would increase this value so that timed samples are further apart. Very useful when trying to detect changes in very slow moving subjects, i.e. snails, slime-molds, a slow-moving criminal trying to avoid motion detection devices :-), etc.

h - RETURNED VARIABLE: this variable must be used for decision whether you want to make shoot. it contains count of cells where change is more than specified threshold value.

example: if h>0 then shoot

n=2 (debug mode): Since build #684 (Jan 18th 2009), this debug feature has been removed to save RAM. To use it, a custom CHDK version must now be built (OPT_MD_DEBUG=1 in makefile.inc will enable motion detector debug).

(insert more information on variable parameter functions and uses as they become known or more familiar)

This function is for those people who want to know where on scene actually detection happened. This procedure is designed for scene change advanced analysis.

Usage: md_get_cell_diff (column), (row), x

where x will be difference of 0 to 255 between the last and present change in that cell. Triggering a script to shoot on this value may be done by detecting no change, or how much sensitivity you would like to detect in that cell.

Examples:

If you would like to have the camera shoot an image when all motion stops, use:

if x=0 then "shoot"

To shoot an image when any motion is detected at all use:

if x>0 then "shoot"

Interesting use of MD

The following was copied from a post where MX3 mentions a feature of md_get_cell_diff that was never documented before.

nobody tried to use MD to get overall luminosity to automatically
adjust shutter speed override?
MD setup:
set delay interval to 2-3 secs
timeout=delay_interval+1
threshold=255 (so it will not trigger )
cols=1
rows=1
md_get_cell_diff 1, 1, overall_luminocity
shutter_override_time = some_formulae ( overall_luminocity )
I don't have camera nearby to test it.
I have thought about timelapse movie script which would automatically override shutter speed at night. I'm planning to make 2 days timelapse
movie ( it seems 8gb SD card and power adapter will help also :-) )
NOTE: when MD stops working on timeout, cells containg absolute values instead of difference.

The most important info contained in that final "NOTE:".

Referring to the 'md_detect_motion' command-parameters in the WIKI article, 'a' and 'b' define the number of rows and columns to split the screen into.
(If values less than zero are entered or if total number of cells is greater than 1024, it defaults to 3 x 3.)

detected_cells_count, // output parameter. count of cells where pixel values differs enough to trigger motion detection
// clipping. allows to exclude some region from motion detection triggering
// or use only selected area to make motion detection
// I'm not sure that following parameters are required but using them anyway

This command is similar to the click "shoot_full" command (see below), but it waits for the camera to perform some normally automatic actions, such as auto-focusing, charging the flash, etc. For example: if in AUTO, P, Tv, Av, or any SCN modes, using the "shoot" command causes the camera to check focus and exposure for each shot. When "shoot" is used in intervalometer scripts this far surpasses the camera's own built-in intervalometer in that the camera only sets exposure and focus once for the initial exposure, as if it was only using the "click 'shoot_full'" command. This "shoot" command in an intervalometer script allows it to compensate for all the things that can change over the course of many minutes and hours. For more precise manual control of the camera in scripts, see the click "shoot_half", click "shoot_full", when used in conjunction with the get_tv, set_tv, set_tv_rel, get_av, set_av, set_av_rel commands below.

These commands are designed to allow your script to control your camera much like you would manually. Nearly anything you can do by pressing buttons on your camera with your own fingers, you can also do automatically with these script commands. The complexity and time-line of your script is only limited by your imagination.

Camera button commands can be written in 3 flavors / command-methods:

click "button-name"

Presses the button momentarily, used for one time, instantaneous commands. This will be the most often used method of issuing a camera command.

press "button-name"

Presses and HOLDS the required camera button, it remains pressed until the same button-name is given the release command. Some camera commands can only be accessed when a button is held down during use.

Example: In Manual Focus in the S-series cameras the MF button needs to be held down while the focus commands are being issued. Or when shooting in high-speed burst mode, then the shutter button must be held down during its needed duration with the press "shoot_full" command.

release "button-name"

Ends the press "button-name" command. If using a press "button-name" command be sure to end it with the release "SAME-button-name command at the appropriate sequence in your script to reset things back to normal.

All camera command buttons that you can press manually you may use in your scripts using this syntax. The only exception is the often-used shoot command. shoot is used by itself without the leading click, press, and release command methods.

All button-pressing commands (except shoot) should be written in the following syntax:

command-method "button-name"

Where command-method may be click, press, or release, and the button-name must be enclosed in double-quotes.

For example, a simple script using all 3 command-methods which makes AELock and AFLock on A-series cameras:

Note: press and release would not normally be used with this button, but without knowing each and every camera model's functions and the creative ways some might use scripts, these two command-methods are also mentioned.

On the SX10IS, holding down SET causes a clock to fill the display. The clock appears after holding the button down for ~2 seconds and disappears about 5 seconds after releasing the button.

Actuates the shutter-release in the half-press position. This is often used to lock focus, exposure, or other camera settings.

(Note: In dim light it can sometimes take up to 2+ seconds for a camera to hunt for focus. If your script is using this command to set auto-focus, and is designed for or intended to also be used in low-light conditions, it would be good to follow a press "shoot_half" command with a sleep x command, where x can have a value from 1500 to 2500.)

Actuates only the shutter-release button "full press" internal switch. This is mostly useful where a click "shoot half" has been previously used and you wish to hold the focus and exposure locked. Doing a release "shoot_full_only" will then simulate only letting the shutter button up to the half-press position (whereas a release "shoot_full" simulates letting the shutter button return fully to the off position). (for more info, see this forum thread )

Initiates your camera's zoom control one zoom-step at a time. (It is uncertain at this time (I didn't test it), how this will act using the press and release commands.) The A-Series cameras have 9 or 15 zoom steps (0 to 8/14), and the S-series cameras have 129 zoom steps (0 to 128). This command may require an extra sleep command after each zoom step. When using click the S-series cameras implement this command very slowly. Here's an example of how it may be used in a loop:

This is used to alter some of the cameras settings that can only be set through the record menus, to set up the camera before a script-session, or during.

Note: press and release would not normally be used with this button, but without knowing each and every camera model's functions and the creative ways some might use scripts, these two command-methods are also mentioned.

This :slowsync" sub-routine will initialize the camera's flash setting into slow-sync mode. Note also the sleep commands, giving your camera time to respond to the new settings between each directional button-press. Button-press delay times may be camera specific. (Meaning it might be a good idea to set up a user-defined variable for these in some scripts to save on script-size and make the script more adaptable to more makes and models of cameras. A note could be made in the accompanying script's documentation on what button-press delays are needed per make and model of camera.)

Note: press and release would not normally be used with this button, but without knowing each and every camera model's functions and the creative ways some might use scripts, these two command-methods are also mentioned.

Note: press and release would not normally be used with this button, but without knowing each and every camera model's functions and the creative ways some might use scripts, these two command-methods are also mentioned.

This will often be used to select some shooting parameters like exposure-compensation, movie frame-rates, white-balance settings, ... any of the options that can be reached by pressing this button on your camera. It is then used in conjunction with directional button-presses to choose the desired settings.

Note: press and release would not normally be used with this button, but without knowing each and every camera model's functions and the creative ways some might use scripts, these two command-methods are also mentioned.

In this "Exposure Bracketing" script, if you follow the embedded button-presses, you'll see that your Exposure Compensation setting is being selected by using the click "erase" command. The click "right" and click "left" commands are moving the Exposure compensation settings to the right and left (more exposure and less exposure), just as you would if you were doing this manually from one shot to the next.

set_zoom_speed x (where x can be from 5-100 range. Will do nothing for A-series)

(5 is 5% of high-speed, 100 is 100% of high-speed)

Range:

A-series: x = 0 to 8 or 14 (9 or 15 steps)

S-series: x = 0 to 127 (128 steps)

Note 1 ; this function has no effect on many Powershot camerass.

Note 2: Camera does not refocus automatically after the end of zooming. Use a click or press/release "shoot_half" command to implement a refocusing if needed.

Note 3: It was found that if using the slowest speed (5), that an S3 IS might shut down after it has waited too long for the zoom to traverse the whole range of 129 steps, a speed of 10 did not exhibit this behavior on an S3 IS. 5 is so slow though, that I doubt it would rarely be needed, except in movie-shooting scripts, and then the range could be limited to prevent camera shut-down.

Note 4: CAUTION! (found on S3 IS) If set_zoom_speed is not written into the script when set_zoom x is used, the camera will refocus some of your optics to make it where the camera is unable to focus on anything in any mode. The camera (when zooming without a set-zoom speed) appears to move an internal lens element that puts the lens into a Super-Macro mode where it focuses on internal lens elements at widest-angle. If this command is left out of a script using the set_zoom x command, you will have to shut down your camera and restart it to reset the zoom-lens' optics back to defaults. However, an interesting thing is found -- when running the "Zoom-Shoot" script by rem-ing out the set_zoom_speed command (removing it from being implemented), after the camera resets its zoom, the lens is now in a ZOOMED tele-macro SUPER-MACRO MODE! Giving you close-up focusing ability at fullest zoom! (as if you had placed a +4 or so close-up lens on your camera) Far surpassing the capabilities that Canon designed. Perhaps this "bug" could be put to great use? Or it might damage your focusing and zooming mechanisms. USE WITH CAUTION. Because you can hear the camera strain up against some internal lens-adjustment stops when it's trying to reset the zoom. And the only way to "un-do" this (really nice!) tele-super-macro mode is by turning the camera off and on again.

(Leaving this small chart here for reference, but is no longer applicable to the new set_zoom commands.)

sleep 500+? delay required after call to set_focus and before shoot/shoot_half (see below)

shoot or shoot_half required after call to set_focus (see below)

x = get_focus (the current focus distance in mm is placed in variable x)

get_focus may also be used directly in an expression where its numerical value might fit: set_focus ((3 * get_focus) / 2)

would set a new focus distance 1.5X farther than the current distance.

LUA Syntax:

set_focus(x)

x=get_focus()

Range:

x = 0 to 65535 (millimeters)

Many Canon P&S cameras will focus using just the set_focus command. If you are having problems using set_focus, try putting your camera into P mode rather than Auto. If your camera has an MF (manual focus) mode you may need to enable it (possibly by issuing the sequence of click "ButtonName" commands for your camera) for set_focus to work, or use the set_mf() script command. Enabling AFL mode may also enable the set_focus() function. Cheaper point-and-shoots do not typically have an MF mode but may have an AFL (auto focus lock) mode - check your user manual for instructions or use the set_aflock(1) script function. Also, set_focus may not work on cameras lacking the CHDK SD (subject distance) Override Menu.

Note that most of the set_XXX commands take place during the camera shooting sequence, so they should be called before shoot or shoot_half is called, and will probably not read back what they have been set to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

Also note that set_focus (on all cameras?) requires the execution of "shoot" before taking effect:

If you comment out the "shoot" above, you will see that the focus has not changed.

Use of press/release "shoot_half" also works (focus is set correctly after the press and is retained after the release as well). And note also that the delay "sleep 500" after set_focus is required. If you remove the "sleep 500" below it will fail (Set!=B4, Set!=Aft).

Furthermore, the delay required after set_focus depends upon the distance the focus motor has to travel. So a step size of 1 between focus steps might require a sleep 500, while a step size of 10 might require a sleep 1500. Also, if in your script you set_tv, set_sv, set_av, this may cause your camera to adjust focus itself in which case the focus motor travel may not be from your last focus position but instead from where the camera auto focus left it (so may require a larger delay). If in doubt, use a sleep 3000 until everything is working.

When larger focus step changes are made, the end result reported by get_focus may be +/- 1 focus step from the set_focus value. So use caution if you loop waiting for get_focus to match.

The valid values for a and the LED that corresponds to each value are different for every camera. Typically they will be values between 0 and 15. Determining the usable values for any particular camera requires either a trial & error process of trying every value or reading the source code in the lib.c file for that camera.

The table below show some typical values for A500 series cameras.

Value of "a" LED Lamp
4 GREEN (by power switch on S3 and A560)
5 YELLOW (by power switch on S3 and under green led on A560 )
6 (not used)
7 ORANGE (red LED on back of S3 and same place than green on A560)
8 BLUE
9 Focus Assist / Auto-Focus Lamp / AF Lamp (bright green on S3 and bright orange on A560)
10 Timer / Tally Lamp (bright orange lamp in front on S3)

When using any LED lamp controls, remember to reset them to their original condition as they were before executing your script. Failure to do so may result in your power-indicator not alerting you that your camera still powered on. Or other important camera functions involving the LED lamps may not light at their proper times.

When testing the Blue LED brightness by putting it in a for x=0 to 200 loop to ramp the value all the way up in 1 value increments, then and back down again, it doesn't appear to behave linearly. The LED ramps up, then turns off, briefly flashes, ramps up again, flashes, then ramps down and flashes (or something similar to that). I suspect it might be working from 0 to 127 using binary bit values. But I've not tested it for this.

Determines whether the camera will do a dark frame subtraction after taking a shot. Auto means the camera decides, OFF means no, ON means yes. Dark frame acquistion and subtraction typically occures for images with an exposure time of 2/3 of a second or longer. It does consume time (it's equivalent to taking another image at the same exposure time).

Note: although this command refers to "raw", it actually applies regardless of whether you are in RAW mode or not. AUTO is the state the camera normally is in. CHDK allows you to change this to the ON or OFF states, and this uBasic command allows you to change it in a script.

This is a powerful pair of commands. These are used to read and set "property-case" values in the firmware of your camera. They can be used for: detecting and setting the flash mode, mode-dial position, the internal self-timer delay, video frame rates, and more.

A new page has been created to describe the use of some of the more useful property case values. See this link The Property Case Use page

The presently known property-case values were originally taken from a list posed at a Russian authored List of known Property Cases. A more up to date list can be found here: this page of Property Case IDs [There now is a Discussion page section for user contributions to determining the values and uses of the property cases. It also has a link to script for exploring these items. You can find it here: Property case exploration.]

IMPORTANT

USE THE SET_PROP COMMAND WITH CAUTION. NOT ALL HAVE BEEN TESTED FOR POSSIBLE OUTCOMES.

Additional information (hopefully growing) about what values might work for some of these properties can be found at the following link: Property case exploration page. This link also has a more complete description of the MyColors settings (contrast, saturation, sharpness, individual color intensities, etc)

NOTE: Syntax usage in most cases is command_name x, where x either sets or returns the value in that command. Unless stated otherwise, assume this usage syntax. Otherwise they may be acting as their own variable, and may be used as-is in a command string. Example: get_vbatt is its own variable. It can either be assigned to another variable with x=get_vbatt, or used on its own as in print get_vbatt. The different types of uBASIC command syntax will be clarified as needed or as discovered. (Developers don't document things very well. We, as end-users, sometimes have to find these things by trial-and-error, or be perceived as a major nuisance by hounding them for any clues into what they did. :) I use both methods. :) )

For the functions listed below CHDK uses APEX96 values to set and calculate exposure.

Returns the index into the aperature table found in the camera's CHDK shooting.c file for the current Av setting in APEX96 units for M (manual) or Av (aperture priority) modes on cameras that support those modes.

Get the maximum distance of acceptable sharpness in mm. The difference between far limit and near limit is your depth of field. CHDK calculates the values from the cameras current focal length (zoom), aperture (Av), and focus distance.

n = get_far_limit

is the most basic use, but it can be combined into more complex arithmetic expressions.

Depth of field is that range of distances that are acceptably focused, given the lens's focal length (zoom), aperture (Av), and focus distance. Hyperfocal distance is the closest distance the lens can focus and still be sharp to infinity. When the subject distance (focus) is set to the hyperfocal distance, get_far_limit will equal infinity, and get_near_limit will be 0.5 * the focus distance.

Returns the Speed Value (ISO, image sensor sensitivity) that the camera is set to in APEX96 units. Use in conjunction with set_sv96.

uBasic Syntax: get_sv96 x

LUA Syntax: x=get_sv96()

Note that typically get_XXX is called at the beginning of a script after a shoot_half to grab what the camera would automatically set the value to. And then get_XXX is called after a set_xxx and shoot combination later in the script along with a print or log of the value to verify that the value read back matches what was set.

If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

Get the closest distance that is within the range of acceptable sharpness.

n = get_near_limit

Near limit and far limit combine to define the camera's depth of field (see get_dof), the range of distances that is acceptably sharp. CHDK calculates the values based on the current settings for focal length (zoom), aperture (Av), and focus distance.

Returns the Time Value (shutter speed) of the camera in APEX96 units. Use in conjunction with set_tv96 described below.

uBasic Syntax: get_tv96 x

LUA Syntax: x=get_tv96()

Note that typically get_XXX is called at the beginning of a script after a shoot_half to grab what the camera would automatically set the value to. And then get_XXX is called after a set_xxx and shoot combination later in the script along with a print or log of the value to verify that the value read back matches what was set.

If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

Returns the index in the aperture table found in the camera's CHDK shooting.c file for the current Av setting in APEX96 units for M (manual) or Av (aperture priority) modes on cameras that support those modes.

Directly sets the aperature (in apex96 units). Rounds the passed parameter to the nearest standard Canon setting for the camera ( e.g. f5.94 rounds to f5.6 - values are stored in each cameras shooting.c file). Works in any mode.

Note that most lower cost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutter speed, ISO setting and a Neutral Density filter to determine the amount of exposure to the subject light that is allowed to reach the image sensor. See set_tv96_direct below.

Directly set the aperture, without tryng to round to the nearest Canon setting. Theoretically precise to 1/96 of a full f/-stop, though the mechanics of the camera is unlikely to match that precision. Works in any mode.

Unlike the recommended set_tv96_direct which simply changes a timer, since this moves the aperture motor, use caution when using this function. It may be safer to use set_av96 below ( it will alters the passed value to a safe setting from the shooting.c file associated with each camera's CHDK port)

Note that most lower cost Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the shutter speed, ISO setting and a Neutral Density filter to determine the amount of exposure to the subject light that is allowed to reach the image sensor. See set_tv96_direct below.

set_av96_direct should allow you to use in-between values not in the table. Convert the desired aperture (f-stop) to and Av96 value with the formula:

Av96 = 192 * ln(f-stop) / ln(2)

(answer must be rounded to a whole number)

Conversely,

f-stop = 2 ^ (Av96 / 192)

CAUTION: The formulas above doesn't acknowledge any limits to the width or narrowness of your camera's aperture. Attempting to exceed the limits of your model may damage the aperture motor or mechanism.

Used to set the Speed Value (ISO) with an APEX96 value. The Speed Value is the sensitivity of the camera's image sensor. Typically: higher sensitivity used for fast action shots at the expense of detail versus lower sensitivity used for slow/static shots with higher detail, but requiring longer exposure times.

uBasic Syntax: set_sv96 x

LUA Syntax: set_sv96(x)

Note that you can determine the APEX96 value for ISO XXX by first setting your camera to ISO XXX then running a script which calls get_sv96 and prints the result. To set your iso: when chdk is not loaded: press set, then up to the top line then right to select the iso value, then set again. (Not sure whether the APEX96 values versus ISO values match from camera to camera, so this method will always work).

If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX value multiplied by 96 (thus the 96 in the name). The simplified explanation for APEX is that the amount of light hitting the film/sensor is dependent on the aperture value and time value (shutter speed) and should be matched to the brightness value of the subject being photographed and the speed value of the film/sensor (ISO value).

Note that most of the set_XXX commands happen when they are supposed to happen during the camera shooting process. So they should be called before shoot or shoot_half is called, and likely will not read back what you set them to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

Directly sets the shutter speed (in apex96 units). Rounds the passed parameter to the nearest standard Canon setting for the camera ( e.g. 1/105 seconds rounds to 1/100 seconds - values are stored in each cameras shooting.c file). Works in any mode but will limit the minumum and maximum shutter speed to the min and max value defined in the table.

This is the recommended method of setting shutter speeds (Tv or Time Value). It uses an APEX96 value.

Note that set_tv96 (no "direct" in the name) will round Tv values to a standard camera value, while set_tv96_direct will set the exact value given. If you wish to stay within your camera's published shutter speeds (not required, but maybe you want to for other reasons) use set_tv96. For a generic list of standard values, refer to the table below - actual values are camera dependent.

uBasic Syntax: set_tv96_direct x

LUA syntax: set_tv96_direct(x)

Note that many less expensive Canon point-and-shoot cameras do not have a variable aperture and simply rely upon the ISO setting, a Neutral Density filter and the shutter speed set by this time value to determine the amount of subject light that is allowed to reach the image sensor. But don't be concerned; because of the increased sensitivity of digital image sensors (versus film), the results are still excellent after the cost reduction of removing aperture control.

If your exposures are not what you expect, try setting your camera to a fixed ISO setting (instead of auto ISO) when using set_tv96_direct. Alternatively, in your script, perform a get_sv96 at the beginning of your script after a shoot_half (which will grab the autoiso value the camera determines should be used, or the fixed setting if not autoiso), then perform a set_sv96 (with this grabbed value) coupled with set_tv96_direct before the actual shoot/shoot_half when taking shots.

If you are unfamiliar with APEX refer to the wikipedia article: http://en.wikipedia.org/wiki/APEX_system. The values used by Canon and CHDK are the APEX values multiplied by 96 (thus the 96 in the name).

Note that most of the set_XXX commands happen when they are supposed to happen during the camera shooting process, so they should be called before shoot or shoot_half is called, and likely will not read back what you set them to until after shoot or shoot_half has been activated. If no set_XXX has been called prior to shoot/shoot_half, the camera will default to determining the values automatically.

Non-standard Shutter speed tv96_direct values can be calculated with this formula:

Tv96 = -96 * ln(shutter time) / ln(2)

Answer must be rounded to nearest whole-number value.

Conversely,

shutter time = 2 ^ (Tv96 / -96)

Table of standard shutter speeds and the corresponding tv96 value (where " is shorthand for second):

Like set_user_av96 (above) except that the aperture setting used is taken from the aperture table for the camera in the CHDK shooting.c file. The actual value used from the table is determined by the index value passed as a parameter to the function.

Like set_user_av96 (above) except that the aperture setting used is taken from the aperture table for the camera in the CHDK shooting.c file. The actual value used from the table is the current value in the table the offset by the index value passed as a parameter to the function.

Like set_user_tv96 (above) except that the shutter speed setting used is taken from the shutter speed table for the camera in the CHDK shooting.c file. The actual value used from the table is determined by the index value passed as a parameter to the function.

Like set_user_tv96 (above) except that the shutter speed setting used is taken from the shutter speed table for the camera in the CHDK shooting.c file (comment: might be an idea to link to this table - SkepticaLee). The actual value used from the table is the current value in the table the offset by the index value passed as a parameter to the function.

Simply powers-down the camera. Useful for Remote USB scripts where the USB signal may wake up the camera, execute some script function, and then shut down the camera again when done, to save on power for lengthy remote-shooting needs.

Example, if x=(some calculation) then shut_down, or just used as a line on its own at the end of your script.

Note: in Lua, post_levent_to_ui('PressPowerButton') can also be used, which may prove to be more reliable as it will be treated by the camera firmware just like a real power button press.

Syntax: x=get_jpg_count, x=get_raw_count (acts as its own variable which may be assigned to other variables)

Returns the calculated value of how many JPG or RAW shot space is left available on the SD card. (JPG value is approximated and taken from an average of file-sizes, using Canon's own algorithm, the same as shots remaining left in your EVF/LCD display.) Use this command to detect when not enough space is remaining for your required script task to either end the script or shut_down the camera.

Between MX3's Motion-Detection options and this amazing USB cable-release method, there is no limit to the various ways you may control your camera by remote means. Any simple electronic circuit that can close a switch and feed a 3v to 5v DC signal to the USB port's proper contacts (observe proper polarity!) can now be used. There is also no limit to the length of wire that you may use, as long as you keep the final contact voltage at the camera-end between the 3vdc and 5vdc range. Use sound-sensitive circuits to record when sound-events happen. Use light or motion changing events to trigger shooting sessions. Use any CHDK intervalometer scripts or electronic intervalometer circuits to trigger shots. (There are thousands of simple circuits like these all over the internet.) Have your mouse or cat press a switch to record their vanity-quotient for a science-fair project! The sky (literally) is the limit to how many ways you may use these functions.

This tiny version of uBASIC includes some debugging help. When running a script with a bad command you might sometimes get a uBASIC:nn err statement printed in red in the top-left corner of your EVF or LCD display. This will alert you to why your coding didn't work, albeit in a very abbreviated format giving the line (nn) and error message.

There are now two ways you can test your CHDK scripts without needing to load them into the camera every time, finding the error and then changing a line, loading it into the camera again and again. The first way is to use the ubasic_test program, a simple batch program which only runs under Windows. The second way is to use the UBDebug program which runs under Windows or Mac OSX.

There's now an interactive development environment for uBasic scripts. Written in java with native support5 for both Windows and Mac OSX it lets you load a script and step through it line by line, inspecting and setting variables. You can also set the values to be returned by functions (such as get_usb_power) and alter the value of properties. A simple breakpoint mechanism is available. Scripts can be edited and saved to disk. For details see here

Download this small file http://web.archive.org/web/20070806121635/http://grandag.nm.ru/hdk/ubasic_test.rar (BEWARE - LINK TRIES TO INSTALL ADWARE ON YOUR COMPUTER! SUGGEST FINDING THE FILE ELSEWHERE). UnRAR (like UnZIP) it to your scripts working location on your hard-drive. You should have a file named ubasic_test.exe in your scripts-work folder now. You have to run this program from a Windows Command Prompt (the old time DOS window). Some people have a "Launch Command Prompt Here" on the right-click menu of Windows Explorer, so you can just right-click on the folder where your scripts and ubasic_test.exe file reside. (You can get this by installing "Open Command Window Here" Power Toy, available here.) Or you can go to Programs > Accessories > Command Prompt (where I have mine for some reason). And use the CD command to Change Directories until you get to where your scripts and ubasic_test.exe file reside. For example, if you start out in root directory C:\ and your scripts are on drive D: in a sub-folder called CHDK\Files\Scripts\, at the command prompt just type

cd D:\CHDK\Files\Scripts

and you'll be where you're supposed to be. (You might want to rename that little program to just test.exe to make it easier to type each time.)

To test one of your scripts in that folder, at the Command Prompt, just type "ubasic_test scriptname.bas" (without the quotes). Where "scriptname.bas" is the name of the script you want to test. It will use the default settings you have assigned to your variables. For testing you should change some of those values to make sure everything is working properly under new user-defined settings. (The reason I suggest you rename that ubasic_test.exe to just text.exe, is then all you have to type is "test scriptname.bas", saving you a few key-presses.)

The easiest way to run console programs is to use a file manager which has a command line. For example, Far Manager or Total Commander.

You can also test your scripts via drag&drop with a batch file. Here's how to do it:

Open a texteditor and put the following lines in there:

@ubasic_test.exe %1
@pause

Save this as "ubasic_test.bat" in the same folder where your ubasic_test.exe is. Now you can drag a script with your mouse onto this batch file and it will be executed. (This would also work without making a special batch file, but we need the "pause" command to read the output).

You may need to modify your BAT file to have the @ubasic_test.exe %1 line to include the full path to your ubasic_text.exe file, as well as enclosing the variable %1 in quotes, in case your script's filename includes any spaces. For example:

@H:\Tests\CHDK_Files\SCRIPTS\ubasic_test.exe "%1"
@pause

If you run into problems and this still doesn't work (using this drag & drop method):

1) Make sure your ubasic_test.exe file and scripts are not in any path that contains spaces. (Example: you can't have it in a sub-folder path of "D:\CHDK Files\Script Tests\ubasic_test.exe" Change those spaces to _ (underscores) in your actual folder-names if need be.)

2) Your BAT file association may have become corrupted. Here's a handy page of Windows® XP File Association Fixes Get the one for Batch Files. (Save them all, they may come in handy one day!)

(How did I find this out? I had all these problems going for me. :-) )

An alternative drag and drop method (WinXP):-

1) Rightclick on uBasic.exe and make a shortcut on desktop,
2) Find/search for your script.
3) drag your script to uBasic icon letgo and it runs!

You may have to adjust the 'Icon' properties to keep the result on-screen

The addition of a few extra print and rem statements will help debugging, also include values to replace the @defaults.