Canon Camera Hackers Manual

Canon Camera Hackers Manual

Camera hackers manual berthold daum
Table of Contents

Advertisement

Advertisement

Table of Contents
loading

Summary of Contents for Canon Camera

  • Page 2 The Canon Camera Hackers Manual...
  • Page 4 Berthold Daum The Canon Camera Hackers Manual Teach Your Camera New Tricks...
  • Page 5 Daum, Berthold, 1949- The Canon camera hackers manual / Berthold Daum. p. cm. Includes bibliographical references. ISBN 978-1-933952-58-1 (alk. paper) 1. Canon digital cameras--Automatic control. 2. Digital cameras--Modification. I. Title. TR263.C3D37 2010 771.3’3--dc22 2010005926 Distributed by O‘Reilly Media 1005 Gravenstein Highway North...
  • Page 6: Table Of Contents

    The warranty question ........Teach Your Camera New Tricks .......
  • Page 7 4.5.4 Processing RAW images ........4.5.5 In-camera RAW processing ........
  • Page 8 5.5.10 Camera state ........
  • Page 9 Canon EOS CHDK ........
  • Page 10: Introduction

    ICBNN). Both projects used Canon compact cameras for taking pictures. The MIT students used a Canon A470, the Italian group a Digital Elph SD 1100 IS (Ixus 80 IS). In addition, both cameras were equipped with the CHDK, the Canon Hack Development Kit.
  • Page 11 Introduction Chapter 3 deals with how to install the CHDK—both utility-augmented installation on a PC and manual installation by utilizing camera functions. Chapter 4 discusses the out-of-the-box functions of the CHDK. First, we examine how to tame the beast—at times, the information overflow can be overwhelming.
  • Page 12: Cameras And Operating Systems

    Most Canon cameras are equipped with an optical image stabilizer; usually, these cameras carry the suffix “IS” in their name. “Optical” means that a lens element is moved to counteract camera shake. With this tech- nique, it is possible to increase exposure times by a factor of 2–16 (1–4 f-stops) when shooting without a tripod.
  • Page 13 (section 4.8). Some editing will be required, however, for the soundtrack. The built-in audio facility (microphone and audio digitizer) that is used for the video soundtrack can be used for photos, too. Voice notes can be attached to photos, or the camera can be utilized as a dictating machine.
  • Page 14: Processors And Operating Systems

    VitalyB. Studying the disassembly of a firmware upgrade for a Canon Figure 2-1 IXUS camera, he was able to analyze the upgrade process and write a pro- The CHDK logo shows up during the gram that would boot from the card and take control of the camera. With boot process of the CHDK.
  • Page 15: How It Works

    This was first done for cameras with the VxWorks operating sys- tem; cameras with the DryOS operating system should follow later. For each camera (in fact, for each firmware version), it is necessary to read out the firmware from the camera and analyze it in order to link the additional functions to the original firmware (section A.4).
  • Page 16: What The Chdk Can Do For You

    CHDK version is required for each firmware version. The main task of migrating the CHDK code to a new camera is to find out the correct position of the required hooks (section A.4). 2.3.3 What the CHDK can do for you...
  • Page 17 Lua language, which is also used by Adobe Lightroom for automation purposes. With scripting, it becomes pos- sible to shoot long time series or to let the camera operate autonomously, as in unmanned aerial missions.
  • Page 18 This is particularly useful when shooting panoramas, for bracketing work such as HDR photography or focus stacking, or for shoot- ing 3D stereo images with a single camera. Unfortunately, this feature does not work in video mode where it could be useful for connecting different takes.
  • Page 19 C H A P T E R 2 Cameras and Operating Systems...
  • Page 20: Installing The Chdk

    Does a CHDK exist for my camera? Each camera model requires its own build of the CHDK. To be more precise, each firmware version of the camera’s operating system requires its own CHDK build. So, once you have established that your camera model is sup-...
  • Page 21: Downloading The Chdk

    Now go back to the CardTricks utility and press the Download CHDK button. This will launch your web browser and open the URL http://mighty-hoern- sche.de/. Find your camera and the firmware version, and click on the link to start the download. The website actually lists two downloadables for each camera and each firmware version—a complete bundle with CHDK, example scripts, fonts,...
  • Page 22: Manual Installation

    Remove the card from the card reader. Set the write protection by mov- ing the little slider away from the contacts. This will enable the AUTORUN feature. Don’t be afraid, the camera will still be able to write pictures to the card. The CHDK will see to that.
  • Page 23: The Warranty Question

    Playback Mode, press MENU, and select Erase… Then you can delete by selection, by folder, or all images. There is a hitch: the camera will Figure 3-5 only show JPEG images or folders containing JPEG images. RAW and DNG The CHDK submenu Miscellaneous.
  • Page 24 Reformat the card (or use a fresh card), and the CHDK is gone. The camera continues to run under its original firmware. In fact, before sending in the camera for warranty, you should remove any memory cards from the camera. A camera equipped with a CHDK-enabled card may disturb service technicians and make their job difficult.
  • Page 25 C H A P T E R 3...
  • Page 26: Teach Your Camera New Tricks

    <ALT> mode is indicated by a small <ALT> sign at the bottom of the display (blue in Recording Mode and white in Playback Mode). Now, where is this mysterious key? There is no key on your camera la- beled ALT. In fact, the actual key acting as the...
  • Page 27: Customizing The User Interface

    Visual Settings. Here you can change the language of the CHDK menus. (The language of the native camera menus is changed separately. Consult your camera’s user manual to do so.) You can change the OSD Codepage to allow for different national characters.
  • Page 28: Colors

    4.2.4 Organizing the screen The amount of information the CHDK is able to show on the display is amazing—almost any camera state can be displayed on the screen. There- fore, it becomes mandatory to select the information carefully and to ar- range its layout properly.
  • Page 29 C H A P T E R 4 Teach Your Camera New Tricks to get a completely clean screen is to switch off the CHDK OSD com- pletely (see above). Center Menu. Displays the CHDK menus in the center of the screen if switched on.
  • Page 30 0 to 100 percent. To use this function, first enable Show Battery Voltage. Now you can determine the voltage of a freshly loaded battery and the voltage of the battery shortly before the camera powers off due to battery exhaustion. When you have found out these values, you may want to dial them in under Battery MAX Voltage and Battery MIN Voltage.
  • Page 31: User Menus

    With digital compact cameras and their electronic viewfinders, grids can be easily shown on the camera’s display. Most of these cameras come with a few built-in grids. For example, my SD1100 offers the option of dis-...
  • Page 32 A grid for the paranoid. When activated, the grid darkens the screen showing only the words “STOLEN CAMERA!” The idea is that a person unaware of the CHDK will not be able to use the camera. A new memory card, however, would cure it.
  • Page 33: Miscellaneous Values

    Values, determines when these values are shown: not at all (Don’t), always (Always), or when the shutter button is half-pressed (Shoot). The entry Show values in video can be set to show these values while the camera is in video mode.
  • Page 34 ISO value ( Sv), and some cameras even allow you to select a fixed shutter speed ( Tv) or a fixed aperture ( Av). In such cases, the camera can easily derive the other values from the above formula.
  • Page 35: Customizing The Dof Calculator

    The option Canon Subj. Dist. as Near Limit uses the distance determined natively by the camera as the near limit. Based on this value, the subject distance and the far limit are both computed by the CHDK. My observa-...
  • Page 36: Other User Interface Options

    4.2 Customizing the user interface If this option is not set, the distance determined natively by the camera is used as the subject distance, and the near and far limits are com- puted. The result seems only slightly too large.
  • Page 37: Exposure

    As already mentioned, the CHDK allows overriding aperture, exposure time, ISO speed, and flash power. This works in all camera modes, auto- matic and manual. So, for example, if the camera is in automatic mode and you override the exposure time only, the camera will automatically choose the right aperture;...
  • Page 38 Aperture-priority (Av) exposure mode All of the Overrides are combined in the submenu Extra Photo Opera- tions. The first entry of that submenu is used to switch the camera between native mode and override mode.
  • Page 39 The same applies for ISO and aperture settings. For example, dialing in an ISO value of 6400 will have no effect if your camera only supports ISO 1600: the sensor speed, will be set to 1600. Remember, too, that in the case of the ISO speed, the Override value is the “real”...
  • Page 40: Custom Auto Iso

    Of course, both of these automatic ISO modes are predefined by the manufacturer. The photographer has no chance to customize how they work. Since the camera does not know how steady your hand is or the minimal shutter speeds required, it can only make worst-case assumptions that may result in less-than-optimal ISO settings.
  • Page 41 35mm cameras. To adapt this rule to the optics of a digital camera, you need to specify the lens factor. To find out that factor, first switch the display of the focal length to EFL (35mm equivalent).
  • Page 42: Histogram

    10, so, for ISO 800, dial 80. In Min ISO you should set the minimum ISO physically possible for your camera. Again, the values dialed in here are multiplied by 10, so, for ISO 100, dial 10. 4.3.3 Histogram Your camera probably does have a histogram, at least in Review Mode.
  • Page 43 C H A P T E R 4 Teach Your Camera New Tricks Figure 4-21 The different histogram styles RGB Y R_G_B RGB all Y all Blend Blend Y...
  • Page 44: Zebra

    4.3 Exposure Ignore Boundary Peaks allows clipping a specified number of pixels (0– 32) at the left and right side of the histogram. Typically, this situation arises when the subject matter is small and placed on a monotonous background, as in night shots. A large black area would result in a high peak at the left side of the histogram, and the remaining information would vanish because of scaling.
  • Page 45: High-Speed Photography

    32 (high sensitivity). The next two options only apply to the Zebra blink modes. When a Zebra pattern is drawn, both the Canon indicators and the CHDK indica- tors (for example, the DOF calculator) are erased by the pattern. To re-...
  • Page 46 4.3 Exposure The other shutter type is the leaf shutter located in the camera lens. Here, several leaves quickly open the lens and then return to their original position. Because of this movement reversal, shutter speeds cannot be very short. For cameras with interchangeable lenses, each lens must be equipped with a shutter, and an auxiliary focal plane shutter is needed to cover the light-sensitive area during a lens change.
  • Page 47: Night Photography

    Merging several RAW images (section 4.5.6). This can be an option when you take a series of photos with your camera mounted on a tripod. This feature cannot register the images with each other, but it saves post-...
  • Page 48 4.3 Exposure Longer exposure times (section 4.3.1). How long depends on the camera model , but the minimum is 64 seconds. Many cameras allow for up to 2147 seconds. Dark Frame Subtraction (DFS) (section 4.5.2). DFS can be useful when you’re shooting with long exposure times at low ISO speeds.
  • Page 49: Flash

    Once again, the CHDK comes to the rescue with an override. There is an option to enforce manual flash even when the camera is in automatic mode, and the flash power can be controlled in three steps: weak (0), medium (1), and strong (2).
  • Page 50: Using Curves

    4.3 Exposure when you need lots of light: for example, when you want to shoot with an ultrashort exposure time (section 4.3.5). By the way, if you enforce the manual flash but it doesn’t work, don’t blame the CHDK; you might just need to charge the battery. 4.3.8 Using curves Custom Curves are another option in the CHDK to control the outcome of a shot.
  • Page 51 Save Point. This will create a .CTC file that is a plain text point list. For usage in your camera, you must compile the curve with Create Curve. This will produce two files: a .CV file and a .CVF file. Copy these files into the folder CHDK/CURVES/ on your memory card.
  • Page 52 You may wonder why the curve editor supports two green curves (Green-1, Green-2). The reason is that the camera’s sensor cells are divided into Red, Figure 4-29 Green-1, Blue, and Green-2, resulting in two green channels. Four sensor The photocells of the camera sensor cells can be nicely arranged in a 2x2 pattern.
  • Page 53 RAW. Image editing programs such as Photoshop or Paintshop Pro allow for such modifications of the tonal range. However, using curves in the camera may help you to realize your visualization of the scene earlier and to redo a shot when the outcome does not match your expectations.
  • Page 54: Focus

    Focus The focal system of Canon compact cameras is dominantly based on an autofocus system. Only some cameras in the higher price range allow manual focusing. The autofocus system is augmented by special focus Figure 4-32 modes such as Macro or Infinity, which can be set manually.
  • Page 55: Shooting Raw

    CHDK. 4.5.1 Basics RAW images are nothing more than the unmodified sensor data produced by the camera. JPEG images, in contrast, are the result of a development process: the color temperature is estimated and applied, the image is Figure 4-33 sharpened, noise is removed, and the contrast is compressed.
  • Page 56 Also, a PC-based RAW converter usually does a better job than the proces- sor in the camera. This is particularly true for the small consumer cameras for which the CHDK was developed. The small processors in those cameras cannot run sophisticated interpolation algorithms in the short time after a shot.
  • Page 57: Dng

    As many panorama stitcher and ste- reo programs don’t accept RAW files, JPEG is the preferred option here. Disable RAW @ Auto Mode. You probably have your camera switched to Auto Mode for casual shots. You would hardly need RAW images here.
  • Page 58 > BADPIXEL.LUA 2. Press the shutter button. The display will go dark, and the camera will take two pictures. After 20–30 seconds, the display will reappear and the camera will wait for input. If the bad pixel test was not successful, the script will ask you to run the test again.
  • Page 59: Other Raw Parameters

    Dark Frame Subtraction is a common technique for removing unwanted artifacts from an image. When an image is taken, the camera will make two exposures: one with an open lens, the other with a darkened lens. The second exposure will only show noise and hot pixels.
  • Page 60: Processing Raw Images

    The only exceptions are the bad pixels. When creating the DNG file in camera, bad pixels can be removed (section 4.5.2). This is not the case when you create a CRW file and convert it to DNG with DNG4PS.
  • Page 61: In-Camera Raw Processing

    4.5.5 In-camera RAW processing You don’t necessarily need a PC to process RAW files. With the CHDK it is possible to develop RAW files within the camera. The selected RAW file will be converted into a JPEG file. Why should you do this? The advantage is that you can apply some...
  • Page 62: More Raw Processing

    3. Navigate to the image folder (e.g., CANON101/), find the image (using date and time for orientation), and press FUNC/SET. 4. The camera will now ask you to switch to Recording Mode. To do so, press again. If the camera is in Playback Mode, switch to Recording Mode.
  • Page 63 Make sure that the single images are perfectly aligned and that there are no moving objects. Mounting the camera on a sturdy tripod and using the series function (section 4.6.2), an intervalometer script (section 5.7.1), or a remote control (section 4.9) is a must.
  • Page 64: Bracketing

    Lua script (section 5.5.9), which allows automating such superimposition tasks completely. Bracketing Bracketing is a camera function that produces a series of photos with vary- ing settings. Traditionally, bracketing was used to obtain an image with perfect exposure. First, an image with the measured exposure was made, then an image half an f-stop overexposed, then an image half an f-stop underexposed, then the same with a full f-stop.
  • Page 65 The last two options are often used for focus stacking. Clear Bracket Value on Start. If this option is enabled, the bracketing values will be reset to default when the camera is powered up. Add RAW Suffix. When this option is enabled and you shoot RAW images, a suffix is added to the names of the resulting RAW files, for example, IMG_2041_01.DNG, IMG_2041_02.DNG, IMG_2041_03.DNG.
  • Page 66: Hdr And Tone Mapping

    The camera does not have this ability. It must record an entire scene in one step and therefore should be able to capture all the contrast in a scene.
  • Page 67 –4 f-stops, +6 f-stops, and –6 f-stops. Given a camera sensor con- trast range of 8 LV (which should be a reasonable value for a compact camera), we can capture a scene brightness range of 12, 16, or 20 LV with this method.
  • Page 68 4.6 Bracketing After you have taken the individual images, the image series must be post- processed and combined into one single image. If you produced RAW im- ages, you should develop them with a RAW developer (section 4.5.4). Even if your HDR image composer is able to accept RAW files, a RAW developer will give you superior results because of the corrections that can be applied to lens and sensor imperfections.
  • Page 69: Focus Stacking

    ( ND) filter in case the scene is too bright. So the camera is always working at maximum aperture with the lowest possible depth of field (DOF).
  • Page 70 (PC65), too. You will probably get a reading that is a little too short, but that is better than a reading that is a little too long. Then put your camera on a tripod, point the camera at the closest point of your subject, focus, and note...
  • Page 71 Figure 4-39 Magnolia. Canon Digital Elph 1100SD (Ixus 80 IS). 1/60 sec, f/2.8, ISO 160. f=6.2 mm (~38 mm). Top left is the first shot in a series of nine images; top right is the last. At a near distance of 142 mm, the measured DOF was 15 mm.
  • Page 72: Edge Overlay

    The zoom level is saved with the edge overlay as well, so when you re- load an edge overlay (Load Edge Overlay), the camera is optionally set to the stored zoom level if option Load+Set Zoom is enabled.
  • Page 73: More Video Options

    So, you can in fact get a better quality than what the native video mode provides. In particular, close-ups and out-of-focus objects will look more natural. However, it may well be that the camera or the memory card is unable to handle such a large amount of data. In this case, the CHDK shows a warning sign (!) on the display.
  • Page 74 Digital Zoom. Digital Zoom is not a bad thing when re- cording video; it is silent, and the quality does not suffer much because the camera sensor has a much higher resolution than what is needed for video. Still, in combination with the Optical Zoom, you can get those long-range zooming shots.
  • Page 75: Remote Control

    IR remote control. Such controls, however, have a few disadvantages: The dis- tance between the IR sender and the camera is limited, and the IR sender must usually be positioned in front of the camera.
  • Page 76: Building A Simple Remote Control

    A USB cable release is relatively easy to build. A small battery is needed to supply a voltage of not more than 5V (Warning: the USB specification al- lows for a maximum of 5V. Your camera might be damaged if you use a higher voltage.) The minimum voltage required depends on the camera.
  • Page 77: Sdm Functions

    CHDK. These functions require a Ricoh CA1 or a compatible remote control. Enable Remote. This entry enables the SDM functionality in scriptless mode. The camera can now be controlled through the Ricoh CA-1. Enable Synch. Allows synchronizing two or more cameras through linked remote controls.
  • Page 78: Extra Hardware

    Enable Remote Zoom. Allows controlling the zoom of multiple synchro- nized cameras through the remote control on cameras with a single zoom switch or rocker. To do so, the camera must first be brought into remote zoom mode. This is done by manually clicking the zoom switch quickly.
  • Page 79: Utilities

    PC screen, along with some of the tricks the CHDK is famous for, such as grids, automatic bracketing, and overlays. If you own an older Powershot model, you may want to try Canon’s own remote control software, Remote Capture, that comes for free. Unfortu- nately, Canon has discontinued this software;...
  • Page 80: Text File Reader

    4.10 Utilities functions from the context menu. This is invoked by pressing the LEFT but- ton. Another click on the LEFT button closes the context menu. Figure 4-47 The functions of the context menu apply to marked files only. Here, two files are marked (appearing here as grayed).
  • Page 81: Getting Information About The Camera

    Show build info. Shows the current version of the CHDK in use and re- lated information. Show memory info. Displays free memory available in the camera RAM and the space used by the CHDK. More information is found in the Debug submenu. Most of this informa- tion supports CHDK developers, but some of it may be useful for “normal”...
  • Page 82: Novelty

    4.11.1 Games Games on a camera? Why not! If you can take photos with a Nintendo Gameboy, why not play games with your camera? So, the CHDK offers four games: Connect4, Mastermind, Reversi, and Sokoban. You’ll find all of these games in the submenu >...
  • Page 83: Flashlight

    FUNC/SET: Next row/Restart game; MENU: back to the Games sub- menu. While trying to beat your camera, you should now and then have a look at the battery level displayed in the lower part of the info section. Maybe you’ll still need some battery power when the shooting light turns perfect.
  • Page 84 4.12 The CHDK configuration file Figure 4-49 The CHDK Config File Editor in action. A double-click on an entry opens a specific editor for the selected entry value.
  • Page 85 C H A P T E R 4 Teach Your Camera New Tricks...
  • Page 86: Scripting

    Many of these scripts have only been tested with a few camera types. So, before using such a script, try it out and estab- lish whether it works properly with your camera. In particular, older scripts written for the DIGIC II cameras need some adaptations to run on DIGIC III or DIGIC IV cameras, and vice versa.
  • Page 87 Pressing the shut- ter button another time will interrupt the script execution immediately. The next time you turn on the camera and the CHDK is activated, the selected script will be loaded automatically. To execute it, it is sufficient to switch to the <ALT>...
  • Page 88: Ubasic

    (A more systematic introduction into uBasic is given in the fol- lowing sections.) The following script implements an electronic magnify- ing glass by switching the camera into the Digital Macro mode and setting a predefined magnification level. Also, most of the info texts are hidden from the display.
  • Page 89 End users are free to supply a value or to accept the default value. The @default instruction specifies this default value. Because the script needs some time to set the camera up, we use that time by giving the user something to read—for example, the usage of the camera buttons during loupe mode: print "Press MENU to cancel"...
  • Page 90 = -32248 gosub "mode" Then we start to set up the camera. First, we save the current display state into variable o, so that when leaving the script we can reset the previous state. We assign the desired display state (No Info = 1) to variable d. The...
  • Page 91 We do this by assigning the saved values for the zoom level and display state to the transfer variables s and d, and then calling the subroutines zoom and display again.
  • Page 92 These are the subroutines for user interaction. They simulate button presses and wait (sleep) for some milliseconds to give the camera time to perform the task. Zooming in and out is quite simple this way. Focusing is a bit more demanding. First, we have to half-press the shutter button. In- stead of using the click command that simulates only a short click, we use a press command to hold the shutter button half-down.
  • Page 93 The subroutine display asks the camera for the current display state. The necessary clicks are performed only if it differs from the desired state. It then sleeps for a while to let the camera adjust to the new settings. This is done repeatedly until the desired result is reached.
  • Page 94: Ubasic Primer

    5.3 uBasic primer Finally, the subroutine restor is used to restore the initial mode. It simply does the opposite of subroutine mode: instead of stepping right in the mode menu, it steps left. The number of steps is stored in variable p. uBasic primer After this initial hands-on contact with uBasic, we are now going to explore the language systematically.
  • Page 95: Output

    C H A P T E R 5 Scripting 5.3.3 Output The print command can be used to show information on the camera dis- play. A print command can have an unlimited number of parameters. Pa- rameters are separated by commas or by semicolons. During output, the commas appear as space;...
  • Page 96: Case Structures

    5.3 uBasic primer Relational operators allowed in uBasic are: = (equals) > (greater than) < (less than) <> (not equal) <= (less than or equal) >= (greater than or equal) It is possible, too, to connect several conditions using the operators and, or, xor, and not.
  • Page 97: Loops

    C H A P T E R 5 Scripting select x case 3,4,7; print "3, 4, or 7" case 10 to 20; print "10 to 20" case_else print "neither" end_select The first case statement specifies a list of values that can be of arbitrary length.
  • Page 98: Labels And Gotos

    5.3 uBasic primer Another loop construct is the while ... wend construct. Here, you have to organize your counters by yourself. while ... wend loops run until an arbitrary logical condition fails. i = 1 while i <= n sleep 10000 print "Shot", i, "of", n shoot i = i + 1...
  • Page 99: Subroutines

    C H A P T E R 5 Scripting Of course, such a label needs to be defined—and this is the syntax: restart: print "script restarted" While goto statements seem to be very convenient and flexible, they im- pose dangers, too. GOTOs are considered harmful in professional program- ming because programs tend to become incomprehensible and difficult to maintain if there are many of them jumping all over the place.
  • Page 100: Comments

    Then, the main processing section performs the task that was intended by the script. Finally, at the end of the script, the initial camera state is restored. If the script does not run to the end by itself (because it runs in a loop), you...
  • Page 101: Lua Primer

    C H A P T E R 5 Scripting should always offer a button to end script execution gracefully. Pressing the shutter button to interrupt a script should only be done in case of emergency, because it is not possible to restore the initial state. The final command in a script is the end command.
  • Page 102: Strings

    5.4 Lua primer 5.4.2 Strings Strings are enclosed in single (‘...’) or double (“...”) quotes, or in dou- bled square brackets ([[...]]). With this latter form, it is possible to define strings that stretch across multiple lines. Strings can contain most of the escape sequences used in other programming languages such as C or Java: \f for a form feed, \n for a new line, \r for the carriage return.
  • Page 103: Assignments

    C H A P T E R 5 Scripting Such dictionary tables should not be accessed via indices because no as- sumptions can be made about the order in which the elements are stored. Note that keys must not contain white space. 5.4.4 Assignments Assignments look very similar to those in uBasic, except that the let com- mand is not used:...
  • Page 104: Blocks

    5.4 Lua primer The CHDK functions cls() and print_screen() work exactly the same as the equivalent commands in uBasic. There is one exception: print_screen(false) can be used to disable output to a log file. 5.4.6 Blocks Blocks are statement sequences that are enclosed by do ... end. Their main purpose is to allow the definition of local variables that are only valid within the block.
  • Page 105: Loops

    C H A P T E R 5 Scripting it is possible to write: if a < 0 then b = -1 elseif a > 0 then b = 1 else b = 0 which is easier to read and to understand. Lua does not feature a select statement (section 5.3.5), but a sequence of elseif clauses can be used for the same purpose.
  • Page 106 5.4 Lua primer for i = 1,10,3 do print(i) would print the values 1, 4, 7, 10. A second form of the for statement—called the generic for state- ment—allows iteration over a series of values, such as the elements of a table.
  • Page 107 C H A P T E R 5 Scripting i = 1 while i <= n do sleep(10000) shoot() i = i + 1 does exactly the same as the first for loop shown at the beginning of this section. The construct repeat ...
  • Page 108: Functions

    5.4 Lua primer 5.4.9 Functions Instead of subroutines as in uBasic, Lua features more versatile functions. Each function consists of a function header, with a function name and parameters, and a function body. The whole function definition is enclosed by the pair function ... end. The list of parameters is enclosed in paren- theses and separated by commas.
  • Page 109: Error Handling

    C H A P T E R 5 Scripting hello = function() print('hello') end The function can later be invoked via hello() 5.4.10 Error handling Another big advantage of Lua over uBasic is the ability to run pieces of code in protected mode.
  • Page 110: Comments

    5.4 Lua primer instruction can therefore be sure that the condition holds. Using assert frequently can considerably improve the safety and robustness of a script. 5.4.11 Comments Anything behind a -- token (including the -- token) is regarded as a com- ment and has no influence on processing.
  • Page 111 C H A P T E R 5 Scripting Some standard libraries are already included in Lua, such as: Basic library for some core functions Input and output library Operating system facilities library String manipulation library Mathematical functions library. The CHDK version of this library differs substantially from the standard version because all functions dealing with floating point numbers have been removed (section 5.4.1).
  • Page 112 5.4 Lua primer IO functions The Lua IO library provides access to file input and output. Using these functions, it is possible to read and write files located on the memory card. We will only give a short overview of the most important IO functions. Ex- amples for the application of these functions are found in section 5.7.1.
  • Page 113 C H A P T E R 5 Scripting value1,... = file:read(format1,...) For each of the specified formats, read() will return a numeric or string value read from the input file. If the specified format cannot be satisfied, nil is returned instead. The following formats are available: "*n"...
  • Page 114 5.4 Lua primer ret,msg,no = file:write(value1,...) writes the values passed in the parameters to the specified file. Only numeric or string values are allowed as parameters. In case of an error, ret is nil, and an error message is given in msg, an error code in no. Operating system functions Only some of the standard Lua OS functions are supported in the CHDK.
  • Page 115 C H A P T E R 5 Scripting Abbreviated weekday name (e.g., Thu) Full weekday name (e.g., Thursday) Abbreviated month name (e.g., Sep) Full month name (e.g., September) Date and time (e.g., 09/24/09 23:57:10) Day of the month (e.g., 24) Hour, 24-hour clock (e.g., 23) Hour, 12-hour clock (e.g., 11) Minute (e.g., 57)
  • Page 116 5.4 Lua primer r, msg, no = os.mkdir(dirname) creates a new directory with a specified path name such as “A:/CHDK/ WORK”. Please note that the path name must not end with a slash. If the function succeeds, true is returned. If it fails, nil is returned, followed by an error message and an error number.
  • Page 117 C H A P T E R 5 Scripting lists the contents of the specified directory. The result is returned as a table of file names. If the function fails, nil is returned, followed by an error message and an error number. If the optional parameter showall is true, the list will contain the entries “.”, “..”, and deleted entries, too.
  • Page 118 5.4 Lua primer String Quoted string. The string is formatted so that it can safely be read back by Lua. %. No argument expected. i,j = string.find(s1, s2, k) Searches for the substring s2 in string s1 and returns the indices for the first and the last character of s2.
  • Page 119 C H A P T E R 5 Scripting A modifier character describing how often a character of that class is expected can follow a character class sequence: none Exactly one occurrence At least one occurrence Any number of occurrences; works greedily (tries to consume longest sequence possible to succeed) Any number of occurrences;...
  • Page 120 5.4 Lua primer table.insert (table, pos, value) Inserts value at the specified position into the table, shifting existing elements at and behind that location one position towards the end of the table. If pos is omitted, the value is appended at the end of the table. m = table.maxn (table) Returns the maximum positive index of the table.
  • Page 121: Chdk Commands

    CHDK commands In sections 5.3 and 5.4, we looked at the language features of uBasic and Lua. None of these language features are able to invoke specific camera functions. For that purpose, the CHDK implementations of uBasic and Lua provide extra commands enriching both languages. The names of the com- mands are the same in both languages.
  • Page 122 Only for PowerShot G7 and SX100IS. Turns the multi-control wheel one stop to the right or to the left. r = get_video_button uBasic r = get_video_button() Returns 1 resp. true if the camera has a video button (S-series, TX1). shoot_half shoot_full Figure 5-2 zoom_out...
  • Page 123: Exposure-Related Commands

    When using CHDK Overrides, however, the user can set each of those entities to a fixed value. Depending on the camera, exposure control then works in aperture priority mode or exposure time priority mode.
  • Page 124 5.5 CHDK commands get_user_tv96 x uBasic x = get_user_tv96() set_user_tv96 x uBasic set_user_tv96(x) Retrieves and sets the value of the internal exposure time set by the user (96 units per f-stop). set_tv_rel x uBasic set_tv_rel(x) Modifies the current exposure time. A negative x makes the exposure time longer, a positive x makes it shorter (3 units per f-stop).
  • Page 125 C H A P T E R 5 Scripting Table 5-1 Index Tv96 Speed Index Tv96 Speed Continued 0"5 1056 1/2000 0"4 1088 1/2500 0"3 1120 1/3200 1152 1/4000 1184 1/5000 1216 1/6400 1248 1/8000 1/10 1280 1/10000 1/13 1312 1/12800 1/15 1344...
  • Page 126 5.5 CHDK commands get_user_av_id x uBasic x = get_user_av_id() set_user_av_by_id x uBasic set_user_av_by_id(x) Retrieves and sets the index of the aperture index set by the user (3 units per f-stop). get_user_av96 x uBasic x = get_user_av96() set_user_av96 x uBasic set_user_av96(x) Retrieves and sets the internal value of the aperture set by the user (96 units per f-stop).
  • Page 127 C H A P T E R 5 Scripting Sensor speed ( Sv) get_iso x uBasic x = get_iso() set_iso x uBasic set_iso(x) Retrieves and sets the ISO speed (Sv) index (Table 5-3). The index values > 0 are mapped to ISO values of 50 and above. The index values –1 and 0 have a spe- cial meaning and stand for HiISO and AutoISO.
  • Page 128: Focus-Related Commands

    They also allow setting the subject distance to a fixed value and then locking the autofocus system. On cameras with an explicit manual focus mode, the camera must be switched manually to that mode before the focus can be set via a script command. On cameras without an explicit manual focus mode, no action is required.
  • Page 129: Zoom-Related Commands

    When the AF lock is set, the AF LED is switched off, too. 5.5.4 Zoom-related commands s = get_zoom_steps uBasic s = get_zoom_steps() Returns the maximum number of zoom steps. This may differ among camera models. get_zoom z uBasic z = get_zoom uBasic...
  • Page 130: Flash-Related Commands

    Retrieves and sets the current image resolution (0 = L, 1 = M1, 2 = M2, 3 = M3, 4 = S, 5 = RAW (on G9), 6 = Postcard, 8 = W). o = get_orientation_sensor uBasic o = get_orientation_sensor() Returns the camera orientation (portrait, landscape) in degrees.
  • Page 131: Time-Related Commands

    Specifies how long the script will wait in milliseconds. The timer resolution depends on the camera model and is in the range between 10–30 milliseconds. s = get_day_seconds uBasic s = get_day_seconds() Returns the number of seconds since midnight.
  • Page 132: Image Management Commands

    Returns the size of the memory card in kilobytes. s = get_free_disk_space uBasic s = get_free_disk_space() Returns the free space of the memory card in kilobytes. c = get_exp_count uBasic c = get_exp_count() Returns the number of images taken since the camera was switched on.
  • Page 133: Camera State

    Develops the specified RAW file into JPEG on the next shot (section 4.5.5). If the pa- rameter is omitted or nil, the pending development task is canceled. Development will be performed under the camera settings at the time of development. set_curve_state(n) (Lua only) Sets the development curve state for post-processing (section 4.3.8): 0 = None,...
  • Page 134 Returns true if the parameter i is a valid CHDK shooting mode number (section 5.6) m = get_drive_mode uBasic m = get_drive_mode() Returns the camera’s drive mode: 0 = single shot, 1 = series, > 1 = timer. m = get_IS_mode uBasic m = get_IS_mode() Returns the mode of the image stabilizer (IS): 0 = continuous, 1 = when shooting, 2 = panning, 3 = off.
  • Page 135: Low-Level Commands (Lua Only)

    = get_usb_power() Sets variable u to a value > 0 if the camera detects a signal on the USB V+ pin. The returned value is the duration of the signal in units of 10 milliseconds. Typically, this command is used to implement advanced remote control functions (section 5.7.5).
  • Page 136: The Library Capmode.lua (Lua Only)

    Lua table that maps mode names to CHDK shooting mode numbers. index = capmode.get() Returns the CHDK shooting mode number (section 5.6). Returns 0 if the camera is in Replay mode. name = capmode.get_name() Returns the current shooting mode name (section 5.6). Returns PLAY if the camera...
  • Page 137: Property Cases

    Digic III and all Digic IV cameras, and vice versa. This is okay if you write a script for your own camera, but if you plan to publish your script in the CHDK community you should identify which cameras are supported.
  • Page 138 Not all of the property IDs and their values have been decoded yet—this is an ongoing community effort. In addition, not all findings have been veri- fied for all camera types. So, the following table must be treated with some caution.
  • Page 139 We list here only the most common shooting modes. A complete list of shooting modes is found in library modelist.lua in folder CHDK/LUALIB/. Some of the Canon shooting mode numbers (in front of the equality sign) dif- fer from camera to camera. The latest findings are listed on http://chdk.wikia.
  • Page 140 5.6 Property Cases Vx Works DryOS Description Hi-speed continuous mode 1 = OFF 0 = ON METERING_MODE Metering mode 0 = Eval 1 = Spot 2 = Center Macro 0 = Normal 1 = Macro 2 = Super Macro Focus mode 0 = Normal 1 = Macro 3 = Infinity...
  • Page 141 C H A P T E R 5 Scripting Vx Works DryOS Description Flash slow sync 0 = OFF 1 = ON FLASH_SYNC_CURTAIN Flash sync curtain 0 = First 1 = Second ISO_MODE ISO value 0 = ISO-AUTO 1 = ISO-HI >...
  • Page 142 4 = Top left > top right > bottom left > bottom right DIGITAL_ZOOM_POSITION Digital zoom steps 0 = NONE >0 = number of steps. Digital zoom steps are camera-dependent. DIGITAL_ZOOM_STATE Digital zoom state 0 = OFF 1 = ON/default Other values are camera-dependent.
  • Page 143 0 = Not fired 1 = Fired FLASH_FIRE Fire flash 0 = do not fire 1= fire OPTICAL_ZOOM_POSITION Zoom step Camera-dependent Color temperature WB_ADJ 1 unit = 6 °K Video frames per second (FPS) Video x resolution 0 = 160 1 = 320...
  • Page 144 5.6 Property Cases Vx Works DryOS Description Video y resolution 0 = 120 1 = 240 2 = 480 Video play mode 0 = LP 1 = SP Time-lapse movie shoot interval In milliseconds Intervalometer 0 = Intervalometer not active >0 = Number of current shots in sequence File numbering 0 = Continuous...
  • Page 145 19/20 = Korean 20/21 = Thai 21/22 = Arabic –/23 = Romanian 22/24 = Japanese Selected movie mode SHOOTING Ready to shoot Changes to 1 when camera is ready to shoot (focus and exposure set); changes back to 0 when shutter closes.
  • Page 146 5.6 Property Cases Vx Works DryOS Description “MyColors” mode 0 = OFF 1 = Vivid 2 = Neutral 3 = B&W 4 = Sepia 5 = Positive film 6 = Lighter skin tone 7 = Darker skin tone 8 = Vivid red 9 = Vivid green 10 = Vivid Blue 11 = Custom...
  • Page 147 You can do this with the help of the script propdump.lua, which you will find on the book CD. Execute the script once (section 5.1) to create a first Property Dump. Then modify the camera setting and execute the script a second time. By setting parameter I, you can compare the second property dump with the first one.
  • Page 148: Example Scripts

    (section 5.1). Changing camera settings by setting property values can be sometimes problematic because only part of the camera may be affected by a specific property case. For in- stance, a property case may influence the camera optics while leaving the user interface untouched.
  • Page 149: Time Machines

    For example, I found it good fun to set up the camera at a party, load a motion detection script, and let the camera do the work. The resulting pictures are quite different from pictures taken manu- ally: full of action and often hilarious.
  • Page 150 Two more parameters allow control of focusing and display. If parame- ter f is set to 1, the camera will focus only once and then leave the focus unchanged. Otherwise, the autofocus process will be performed before each shot. If parameter d is set to 0, the display is darkened to save battery life.
  • Page 151 C H A P T E R 5 Scripting environment such as a PC, the operator / denotes a floating-point division. Because an integer division is what we want, and because it is more conve- nient to debug scripts on a PC, we use idiv() instead of / throughout the script.
  • Page 152 10 msec after each line of code. This is not the case for Lua—probably the main reason why Lua scripts are so much faster. After focusing has finished, we lock the autofocus system and release the shutter button. The camera will not try to refocus until the lock is re- leased. function focus() press("shoot_half")
  • Page 153 Now we can initialize the main loop. We get the start time in milliseconds (since camera start) and initialize the variable next_event with that value. Within the loop we shoot an image, then increment the variable next_ event with the computed delay. If the display is active, we print a log entry to inform the user about the progress.
  • Page 154 Time-lapse movies Time-lapse scripts are often used to create time-lapse movies. Of course, your camera probably offers a built-in function to create time-lapse movies, but it is rather limited. Let’s see what’s possible with a time-lapse script. First, with a script you don’t work in video mode but in photo mode.
  • Page 155 Also, be careful about the Digital Zoom. When shooting HD movies, you should avoid the Digital Zoom altogether or only use it up to approximately a factor of 2. Otherwise, you can use any camera feature and any CHDK feature that you would use when shooting manually. You can allow the camera to determine the exposure and focus for each new shot, or you can use Overrides (section 4.3.1) to set fixed exposure values and/or a fixed...
  • Page 156 1 (e.g., frame_1.jpg, frame_2. jpg, frame_3.jpg, ...). IrfanView allows you to do batch renaming of photos. Alternatively, you could easily rename the images within the camera before transferring them to the PC. The following Lua script is all you need. Renaming files The following script can be used for renaming files.
  • Page 157 C H A P T E R 5 Scripting In case of success, we increment the image counter s. function renameFile(path, file) oldname = path..file local t = os.stat(oldname) if t["is_file"] then newname = path..prefix..s..suffix t = os.stat(newname) if t then error( oldname.."...
  • Page 158 5.7 Example scripts wait_click(5000) if is_pressed("set") then break elseif is_pressed("display") then i = nil break elseif is_pressed("left") then i = i - 1 if i <= 0 then i = #files elseif is_pressed("right") then i = i + 1 if i > #files then i = 1 If the user selected a subfolder, the members of the subfolder are fetched and the renameFile() function is executed on each member.
  • Page 159 F causes the camera to determine the subject distance immediately and then lock the focus, so the autofocus is switched off during the subsequent shots. A removes the focus lock and allows the camera to autofocus again with each new shot. I sets the focus to infinity.
  • Page 160 The display is switched dark. 3. After one minute, the camera takes 10 shots with an interval of 15 sec- onds between shots. 4. Finally, at MET 00:05:00, the camera switches back to autofocus and takes another 10 shots starting with an interval of 15 seconds and end- ing with an interval of 5 seconds.
  • Page 161 C H A P T E R 5 Scripting pcall(function() require("chdklib") schedules = "SCHED" The functions set_display_mode() and sleep_until() are not really new. They are simply copied from the Accurate Time Lapse script at the begin- ning of section 5.7.1. props = require "propcase"...
  • Page 162 5.7 Example scripts function focus(f) if f == "F" then press("shoot_half") repeat until get_shooting() set_aflock(1) release("shoot_half") elseif f == "A" then set_aflock(0) else set_aflock(1) set_focus(f) You probably missed parameter value I, which stands for infinity. This is taken care of in function parseFocus(), which analyzes the focus subclause as specified in a schedule file.
  • Page 163 C H A P T E R 5 Scripting if e > a then t = t + tonumber( string.sub(s, a, e - 1)) a = e + 1 return t * 1000 function parseDisp(token) t = string.upper(token) d = string.find("IND",t) if d then return d - 1 end The function parse() parses a whole line.
  • Page 164 5.7 Example scripts met = parseTime( string.sub(line, a, e - 1)) a = e + 1 e = string.find(line, " ", a) if e then local t = string.sub(line, a, e - 1) disp = parseDisp(t) if not disp then n = tonumber(t) if disp or (not n) then return focus,met,1,0,0,disp...
  • Page 165 C H A P T E R 5 Scripting Finally, the function tohms() is already known from the Accurate Time Lapse script: function tohms(ticks) local ts = idiv((ticks + 50), 100) local t = ts % 10 ts = idiv(ts, 10) local s = ts % 60 ts = idiv(ts, 60) local m = ts % 60...
  • Page 166 5.7 Example scripts elseif is_pressed("right") then i = i + 1 if i > #files then i = 1 end If a file was selected, we can now read the file and parse each line. But be- fore we do so, we save the current display mode in order to restore it when the script has finished.
  • Page 167 C H A P T E R 5 Scripting if met then local next_event = start_ticks + met for k=1, n, 1 do if sleep_until(next_event) then print "Aborted" next_event = nil break shoot() h, m, s, t = tohms( next_event-start_ticks) print(string.format( "Frame %u, MET %u:%u:%u.%u", frame, h, m, s, t))
  • Page 168: Bracketing

    Unfortunately, we cannot use them in this script. When the camera is in normal focusing mode, values for the near and far limits that would fall into the macro range are returned as –1 (infinity). And vice versa—when the camera is in macro mode, values outside the macro...
  • Page 169 C H A P T E R 5 Scripting focal distance 1 focal distance 2 focal distance 3 far 1 far 2 DoF 1 near 1 DoF 2 near 2 DoF 3 near 3 total DoF of stacked images The following script accepts four parameters: two for the near limit and Figure 5-3 two for the far limit of the composite sharpness range.
  • Page 170 So, we store the current flash mode into variable m and then call subroutine fmode. The desired flash mode (2 for off) is set to transfer variable M.
  • Page 171 The focus is set and the script is paused for a while to give the camera some time to adjust the optics. The amount of time needed may depend on the camera model.
  • Page 172 The subroutine prep is used to wait until the camera is ready to shoot—i.e., until the command get_shooting returns 1. The subroutine wait works the other way around; it waits until the camera has processed the current shot:...
  • Page 173: Motion Detection

    5.7.3 Motion detection Motion detection is one of the great features of the CHDK. This feature makes use of the camera’s hardware motion detection facilities. The cam- era provides such facilities for its own purposes: to enable image stabiliza- tion and to adjust exposure time in regard to subject movements. The CHDK uses them to trigger events—in most cases, to fire a shot.
  • Page 174 (see variables i, j, k, l, m). A fine grid enables the camera to detect the motion of small objects, but the camera will also react more slowly to move- ments.
  • Page 175 C H A P T E R 5 Scripting An additional command allows for a finer analysis of the detected motion: Basic md_get_cell_diff i,j,k k = md_get_cell_diff(i,j) Here, the variable k will contain the change in the i-th cell and the j-th row. The value of k will range from 0 to 255.
  • Page 176 We have also added an additional value option to parameter f (threshold or sensitivity). If f is negative, the threshold will be dynamically derived from the brightness value measured by the camera. Even then it is possible to influence how the threshold is derived from the brightness value: the more negative f is, the smaller the threshold will be, and the more sensitiv- ity motion detection will register.
  • Page 177 C H A P T E R 5 Scripting @default j 2 @param k First row mask @default k 2 @param l Last col mask @default l 3 @param m Last row mask @default m 3 @param o Subsampling (pixel) @default o 6 @param p Delay (0.1s) @default p 1...
  • Page 178 5.7 Example scripts The function adapt() is used to compute the threshold (sensitivity) de- pending on the scene brightness value measured by the camera. We get this value with the CHDK function get_bv96(). The following formula is heuristic and was found acceptable during trials. It may be changed if re- quired.
  • Page 179 DISP button to be clicked. The function wait() simply waits until the camera has completed the processing of a shot. When this happens, the function get_shooting() re- turns false. The function wake() is invoked in the case of a timeout when no motion is detected.
  • Page 180 5.7 Example scripts -- Program definition labels = {"Parameters", " Lightning", "Fast", "Small Objects", " Macro", " Hat" -- add additional labels here programs = { function() --Parameters end, function() --Lightning a,b,c,d, e,f, i,o,p,t,z = 4,4,1,55,1,10,0,6,0,2,1 if u == 0 then u = -1 end end, function() --Fast a,b,c,d, e,f, i,j,k,l,m,o,p,t,z...
  • Page 181 A threshold of 0 would be nonsense; the camera would fire without any motion: -- Inhibit bad mask bounds if m > b then m = b end if m <...
  • Page 182 --Inhibit zero threshold if f == 0 then f = -1 end We now retrieve the drive mode from the camera. This is done by using the commands get_drive_mode() to detect Continuous Mode (1) and get_ mode() to detect Video Mode. After this piece of code is executed, we have...
  • Page 183 Then we wait until the camera is ready to shoot again. In the case of a timeout (cells==0), we perform the subroutine wake to stop the camera from pow- ering down.
  • Page 184 This concludes the implementation of the motion script. Now let’s see how the scene programs differ from each other and how to use them. When using the script, you should set the camera’s native time-out for power- down to at least one minute.
  • Page 185 Fortunately, practically all lightning flashes are preceded by a smaller preflash. This preflash is sufficient to trigger a lightning sensor and a con- nected camera. If the camera is fast enough, it will capture the main flash. Such lightning sensors are not cheap. Fortunately, most CHDK users don’t need one;...
  • Page 186 Because conditions may change rapidly, we set the time-out to 30 seconds so that the camera can more frequently adapt to altered conditions.
  • Page 187 The camera is placed some- where, the script is started, and a hat is placed over the camera to hide it. When something interesting happens, we lift the hat and the camera fires.
  • Page 188 5.7 Example scripts Now start a motion detection script on your camera and point the cam- era to the screen (a tripod is recommended). If you use the script developed in this section, choose the lightning scene program. If properly configured, the script will react every time the table cells become visible again.
  • Page 189: Exposure Control

    The following table, corr, contains correction values for shutter speeds of 1/1000 sec or shorter. Often, such short shutter speeds are not really precise. If desired, camera owners can calibrate their cameras by making test shots at 1/1000, 1/2000, 1/4000, and so on. The resulting values go into table corr.
  • Page 190 Sv96 is computed. Then the Bv96 value is read by half-pressing the shutter button, waiting until the camera signals “ready to shoot”, and reading out the Bv96 value. Next, the ND filter is switched out, the Tv96 value is read, and the Av96 value is read, too.
  • Page 191: Remote Control

    ISO value or is below the minimum possible ISO value. If yes, a recalculation is performed. Finally, the Sv96 value is set, the camera is fired, and when the processing is done, the shutter button half-press is released: sv = av + tv –...
  • Page 192 The following script uses that functionality to allow zooming and shooting with a simple remote control as shown in section 4.9. A short click on the button of the remote control will fire the camera. For zooming, there are two modes that can be selected via parameter m: In Step mode, the remote button must be pressed longer than half a second to advance the zoom to the next position.
  • Page 193 If the duration is shorter than 500 msec or if zooming had been disabled by setting parameter s to a value <= 1, the camera is fired. Other- wise, the subroutine zoom is executed. Afterwards, the script loops and...
  • Page 194 5.7 Example scripts a matter of fact, it is essential that the camera’s native time-out interval for power-down is set to a value of one minute or more. :wakeup r = get_day_seconds if r > e then click "set" click "set"...
  • Page 195: Configuration Switching

    It also allows you to select one of the copies and make it the current configuration. After a restart of the camera, the selected configuration becomes the active configuration. Of course, every time the configuration is switched, a backup of the former configuration is made—just to be safe.
  • Page 196 5.7 Example scripts and cnt with the current count of saved configurations. It writes two text lines that should look like this: cnt = 1 cur = CONF1.CFG To be safe, the new file is first written to file CONFSW.INI.NEW. If this is suc- cessful, the old INI file is renamed to CONFSW.INI.BAK (existing files of that name are deleted first), and file CONFSW.INI.NEW is renamed to CONFSW.INI.
  • Page 197 C H A P T E R 5 Scripting Next is the definition of the table parser_funcs containing two functions. These functions will be used for parsing the entries of the INI file using regular expressions. The function with the key “count” checks to see whether a text line passed in the variable line has the syntax “cnt=…”...
  • Page 198 5.7 Example scripts function copy_file(from, to) local new = to..".NEW" local ffile, msg = io.open (from, "rb") if not ffile then error(msg) end local tfile, msg = io.open (new, "wb") if not tfile then ffile:close() error(msg) local ret = true while ret do local s = ffile:read (256) if not s then break end...
  • Page 199 C H A P T E R 5 Scripting local ret = false while true do local s1 = f1:read (256) local s2 = f2:read (256) if not (s1 or s2) then break elseif s1 ~= s2 then ret = true break f1:close() f2:close()
  • Page 200 5.7 Example scripts When showing a configuration to the user, we display not only its name, but also its modification date. This makes it easier for the user to identify the configuration: -- config selection files, msg = os.listdir( configs,false) if not files then files = {} end if #files >...
  • Page 201 C H A P T E R 5 Scripting i = i+1 else print( "No configs to choose from") Before we switch to the selected configuration, we check to see whether the current configuration CHDK/CCHDK.CFG is different from the configura- tion remembered in the INI file.
  • Page 202 "Please restart camera") shut_down() elseif new_name then write_ini(new_name, ccounend This script is far from trivial, but it is developed with safety in mind. If something goes wrong, you can still retrieve a working configuration from the .BAK files.
  • Page 203: Script Development

    PC, move the memory card to the camera, reboot the camera, run the script and find the next syntax error, move the card back to the PC, correct the error, and so on.
  • Page 204 5.8 Script development Figure 5-7 The UBDB debugger in action. Here, we step through the script from section 5.7.2. With a double click, we set a breakpoint on line 72. Clicking Step button, we advance one more line. Figure 5-8 To allow the script to continue, we must now change the value of variable r to 2 so that the script can leave the...
  • Page 205 C H A P T E R 5 Scripting However, all of these problems can be solved so that Lua scripts can be tested comfortably within a PC environment: The missing CHDK commands can be added as extra libraries to the PC environment.
  • Page 206: Advanced Techniques

    But special equipment is not really necessary to produce good panora- mas. The stitching programs that exist today are so powerful that you can easily create your own panoramas with your Canon. All you need is a freshly loaded battery, sufficient free space on your memory card, patience, disci- pline, and a few tips like these: A tripod and a remote control (section 4.9) are recommended, but I have...
  • Page 207 The adapter allows you to shift the camera forwards and back- wards. Set up the camera and tripod so that you have both a far and a near object in the viewfinder. When you turn the camera, the distance on the screen between both objects must not change.
  • Page 208 6.1 Panoramas images precisely, especially when shooting panoramas hand-held: Edge overlay shows the edges of the previous image on top of the current viewfinder content (section 4.7 and Figure 4-40). Stitching programs usually accept TIFF and JPEG files. Shooting JPEG is just fine.
  • Page 209: Hdr Panoramas

    C H A P T E R 6 Advanced Techniques The same features in Autopano Pro are available in PTGui—one of the pioneers of panorama technology. Hugin, which doesn’t lack in power, is the free Open Source alternative for panorama stitchers. It supports HDR panorama stitching and can also be used for nonpanoramic purposes, such as perspective correction of architectural shots.
  • Page 210 After you set up the camera in this way, you can take the images for the panorama (don’t forget to set a fixed ISO value and a fixed white balance).
  • Page 211 Figure 6-1 consists of nine single shots, three shots in three rows. The camera was a Canon Digital Elph SD1100 at a wide-angle setting (equiv. 38 mm). Because the contrast range was rather high, I decided to use HDR bracketing as well, with three images per shot, and a Tv Bracketing value of 2 EV.
  • Page 212: Hdr Videos

    HDR videos Some users have created HDR time-lapse videos with their Canons. The technique is quite sim ple: set the camera to bracketing mode and config- ure the Custom Timer as discussed in section 6.2. Then use any time-lapse script that can press the shutter button in defined intervals, such as the script developed in section 5.7.1.
  • Page 213 C H A P T E R 6...
  • Page 214: The Stereo Data Maker (Sdm)

    As the name sug- gests, it provides additional functionality for stereo (3D) photography such as camera synchronization. But in fact, the SDM is not used dominantly for that kind of photography. Because of its excellent remote control features and its integration with external devices, it is quite popular in the KAP (Kite Aerial Photography) community.
  • Page 215 CONFIGS/config_eng/L/CHDK.CFG into folder CHDK/ on the memory card used for the left camera. The file CONFIGS/config_eng/R/CHDK.CFG goes into folder CHDK/ on the memory card for the right camera. If your cameras will be mounted on a U-frame (section 7.7.4), copy file CONFIGS/config_eng/L_horizontal/CHDK.CFG into folder CHDK/ on the...
  • Page 216: Restrictions

    Now, remove the card from the card reader, switch on the write-protec- tion, and insert the card into the camera. When you start the camera, you should see the SDM splash screen.
  • Page 217: Operation

    Finally, a recently introduced feature of the SDM is the sup- port of Digiscoping, i.e., connecting a camera to a telescope. Operation Using the camera under the SDM is quite similar to using it under the CHDK. There is an <Alt> mode which you can enable via the button (chapter 4).
  • Page 218: Remote Control

    (1) When the button is half-pressed, the camera focuses. (2) When the button is fully pressed, the camera mea- sures the exposure. The blue LED indicator is lit when the camera is Switching between these two modes requires at least a half-press of the...
  • Page 219 The blue LED indicator will be lit when the camera is ready to shoot. (3) Release the button to shoot. It is possible to combine steps (1) and (2) by pressing the button for lon- ger than half a second, waiting on the blue LED, then releasing the button.
  • Page 220: Communications

    7.6 Communications Communications In this section, we will discuss the camera uplink to a PC as well as serial communication with an external device. 7.6.1 USB upload Because the USB port, by default, is reserved for the remote control, you must explicitly disable the option >...
  • Page 221: Stereo Photography

    Of course, it is also possible that an external device will send more data to the camera’s USB port than a simple receipt. Such data can be encoded with pulses of varying width and interpreted with the help of the script command get_usb_power (section 5.5.10).
  • Page 222: Stereo Photography With A Single Camera

    If the subject matter doesn’t move, you can obtain good results by using a single camera: take the first shot, move the camera a bit to the right, and take the second shot. This method is particularly suitable for macro stereo photography. In macro photography, the shift between the left and the right image must be quite small—so small that it’s impossible to mount two cameras side by side...
  • Page 223 Camera Spacing, dial in the distance that and Edge Overlay. you want the camera to shift between both pictures. Typical values here are 60–70 mm for mid-range work and 10–20 mm for close-up work. In the same menu, set the Twin-Cam position to L (left) and the Cam orientation to H (horizontal) or V (vertical), depending on the camera orientation.
  • Page 224 Object o2 is so close that it is only seen by camera c2. It will appear as a ghost. In both cases, reducing the distance between the cameras or increasing the subject distance will help.
  • Page 225 Unfortunately, this method does not work in all cases. Especially in macro mode, your camera might not be able to focus at close distance while the lens is in telephoto position. The SDM, on the other hand, can only capture distances in telephoto position.
  • Page 226: Producing And Viewing Composite Stereo Images

    Yes, we can—focus-stacked 3D is possible and does, in fact, enhance the 3D impression. First set up your camera (or your cameras) for stereo work. If your camera has a manual focusing mode, switch it on. Then go to >...
  • Page 227: Synchronized Cameras

    Your best option is to buy a camera of the same type (it’s always good to have a backup). The advantage is that taking stereo photos with two cameras is much more convenient than with a single camera, and you can take stereo images of moving objects, too.
  • Page 228 180°. The advantage of this frame is that—because most cameras are asymmetrically built—the lenses can be mounted closer together, resulting in a lower near limit. Typically, Z-frames are built with a special camera model in mind so that the lens centers are aligned.
  • Page 229 Registering two cameras is, of course, a bit different than working with a single camera. For example, you will not be able to use the Edge Overlay or to view the result as a composite anaglyph on the camera display. The two cameras simply cannot exchange their image data.
  • Page 230: Synchronized Flash

    The left camera does not show a deviation indicator. 7.7.5 Synchronized flash When working with a twin camera set-up, it is also possible to use the built-in flash units of both cameras. To enforce identical exposure settings on both cameras, it is necessary that both cameras do fire the flash. All you have to do is: Set up both cameras as twin cameras as usual.
  • Page 231: Digiscoping

    Release the button after the blue LED indicates “ready to shoot”, and the camera will fire. Only the flash of the right camera is fired with full power. The power of the left flash is reduced by four f-stops in order to avoid double shadows.
  • Page 232 Exit <Alt> mode and set the camera to Continuous mode or to Custom timer (with an appropriate number of shots). Of course, the scope must be mounted on a sturdy tripod. The camera must be mounted on the same tripod, so you need some kind of a bracket (digi- scoping adapter) on which both scope and camera can be mounted and adjusted.
  • Page 233: Scripting

    C H A P T E R 7 The Stereo Data Maker (SDM) use the Custom timer with a few seconds delay to fire the camera (obvi- ously not an option for action shots). Anything else will lead to shattered or unsharp images.
  • Page 234 7.9 Scripting The SDM has also found a way around the slow speed of uBasic scripts. In the CHDK, each script line (except comment lines) is executed in a new time unit (10 msec). With the SDM, you can control the speed of execution. The command: set_script_speed s accepts a value between 1 and 5, determining the number of script lines to...
  • Page 235 Used to set the step width for exposure (Tv) bracketing in 1/3 EV (f-stops). auto_focus_bracketing Sets up the camera for a focus bracketing sequence to take a sequence of images starting at a defined subject distance and ending at infinity. The steps increase with distance.
  • Page 236 Starts and ends a bracketing series when the camera is in Continuous mode. start_custom_timer_sequence Starts a Tv or focus bracketing series when the camera is in Custom Timer mode. The series will end after a given number of images have been taken. The number of im- ages is specified in the Custom Timer under Shots.
  • Page 237 The camera waits until the specified time of day (h = hours, m = minutes). During that time the screen is darkened. time_lapse a, b, c, d, e, f, g, h, i, j, k, l, m, n, p, q, r, s, t, u Starts a time-lapse series.
  • Page 238 By default, USB download (upload) is disabled, so that the camera can react to a USB remote control. By enabling the USB upload and switching to Playback mode, a peer program running on a PC (such as the WIA loader) will start and open a connection.
  • Page 239 Identical to playsound 4 (section 5.5.8). Camera state-related commands lcd_on_off Toggles the on/off state of the camera display. This does not work on all cameras. turn_backlight_off turn_backlight_on Identical to set_backlight 0 and set_backlight 1 (section 5.5.8). Works on all cam- eras.
  • Page 240: Kites, Balloons, And Multikopters

    Kite Aerial Photography In Kite Aerial Photography (KAP), a camera is lifted by a kite and takes pho- tographs autonomously or when triggered by a remote control. Small, lightweight cameras such as the Canon Digital Elph SD (Ixus) series are ideal for KAP.
  • Page 241: Balloon-Based Photography

    In this case, there are additional requirements: the equipment must be protected against cold temperatures, and you must provide a way to safely retrieve the camera, such as a para- chute and a tracking device.
  • Page 242: Motorized Flying Platforms

    Other unattended operations The remote operation of a camera is not limited to kites and other airborne vehicles. Any kind of remote-controlled vehicle can be used as a camera platform—on land, sea, in the air, or in space. Often such vehicles are used to take pictures in areas where humans can’t go or areas that are too dan-...
  • Page 243 Basically, there are two options to solve the problem. If the camera can be connected to the USB port of a nearby PC, the images can be downloaded to the hard disk of the PC by using the SDM in connection with the WIA loader (section 7.6).
  • Page 244: Look Across The Fence

    The success of the CHDK seems to have a ripple effect. Owners of other cameras start to ask: w hy can’t I get something like that for my camera? In fact, quite a few similar projects exist by now—projects that are targeted at cameras other than the compact models from Canon.
  • Page 245: Pentax Hacks

    The software is readily available for the 5D, and a new version for the 7D has been announced. Pentax hacks The Pentax Hack project (http://pentax-hack.info) is still in the early stages of analyzing the camera’s native firmware. The project is targeted at the Pentax K10D/K20D and Samsung GX10/GX20 cameras.
  • Page 246: Appendix

    Using cards with more than 4 GB capacity Using very large memory cards can sometimes be necessary when doing video or time-lapse work where the camera runs unattended, and it is in- appropriate to change the card frequently. The simplest option is to launch the CHDK manually after each camera start with the function Firm update…...
  • Page 247 Make card bootable to enable the AUTORUN function. This will make the first partition bootable. 11. Write-protect the card and switch the camera on again. It should now perform an AUTOSTART from the first, small partition. When the CHDK detects a second partition formatted with FAT32, it will switch all ac- cess functions to the second partition.
  • Page 248: Troubleshooting

    This happens, for example, shortly after start-up when the display is in the “no information” mode. It also happens in Replay Mode when you change the orientation of the camera, or when you switch camera modes. In all of these cases, the native firmware re- paints the screen and the CHDK menu is destroyed.
  • Page 249 Solution: First check to see if the bug persists in the newest version of the CHDK. If yes, and if you have access to another camera, find out if the bug is specific to a certain camera model or not. Then file the bug in the Mantis bug tracking system (http://chdk.kernreaktor.org/mantis).
  • Page 250: Web Links

    CHDK for balloon photography: http://www.francescobonomi.it/ballon- photography-CHDK Documentation about a balloon-based space mis- sion with a CHDK-enabled camera. MikroKopter: http://www.mikrokopter.de/ucwiki/en/MikroKopter Official site for the MikroKopter flying camera platform. dng4ps: http://code.google.com/p/dng4ps2/ Home of the DNG4PS (DNG for Powershot) converter. Magic Lantern Firmware Wiki: http://magiclantern.wikia.com...
  • Page 251: Contributing To The Chdk

    Besides the camera itself, the first thing required for porting the CHDK to a new camera is a dump of the native camera firmware. This may be easy to obtain by using CardTricks (section 3.2) for dumping directly from the camera.
  • Page 252: Bibliography

    A.5 Bibliography Bibliography [Lua51Ref] R. Ierusalimschy, L. H. de Figueiredo, W. Celes; Lua 5.1 Reference Manual; http://www.lua.org/manual/ [UserGuide] http://chdk.wikia.com/wiki/File:CHDK_UserGuide_April_ 2009_A4.pdf [Gulbins2009] Juergen Gulbins / Rainer Gulbins; Photographic Multishot Techniques; Rocky Nook; 2009 [Howard2008] Jack Howard; Practical HDRI; Rocky Nook; 2008 [Bloch2007] Christian;...
  • Page 253 A P P E N D I X...
  • Page 254: Index

    APEX 24, 25, 114, 182 calendar 9, 70, 207 138, 196, 215, 221 assignment 85, 94 Camera Spacing 214, 216, 218, 220 Auto DR 42 card reader 11, 12, 13, 51, 205, 207 auto focus, see AF CardTricks 11–13, 242...
  • Page 255 I N D E X file browser 9, 14, 19, 24, 49, 53, 56, 63, 70–71, 77 image stabilizer 3, 32, 125, 137, 231, 233 onion skinning 63, 207 Firm update 14, 237, 238 IO functions 103 On Screen Display, see OSD firmware version 6, 7, 11, 12, 13, 14, 205, operating system functions 105 optical zoom 3, 4, 8, 65...
  • Page 256 I N D E X string 85, 92, 94, 101, 102, 103, 104, 105, 106, 108–110, 127, 144, 153, 154, 155, warranty 14, 15 158, 189, 224 WIA-Loader 70, 211, 229, 234 string manipulation functions 108–110 write protection lock 14 subroutine 81, 82, 83, 84, 85, 88, 90, 91, 99, 161, 162, 163, 173, 174, 184, 185 24, 25, 114, 118, 134, 180, 181, 182...
  • Page 257 Back cover image data Hamburg Docklands SUBJECT Canon SD1100 IS CAMERA 6121 SHUTTER SPEED 1/19 f/2.8 APERTURE 6.2 mm (equiv 38 mm) FOCAL LENGTH Shot handheld with six single exposures as DNG images. Superimposed with PhotoAcute. Berthold Daum Book Website www.photozora.org/cchm...

This manual is also suitable for:

Powershot sx10 is

Table of Contents