Home

Chameleon AVR User Manual Ver 1 ().

image

Contents

1. int main void initialize and set SPI rate SPI_Init SPI_DEFAULT_RATE give Prop a moment before sending it commands the boot process is about a second if you like you can speed it up by removing the Prop driver s LED blink sequence in the driver or speed it up but commands that are sent before the Prop driver is done booting will be ignored therefore if you have a lot of set up work to do then you don t require a delay but if you jump right into commands then you need a good 1 5 2 second delay _delay_ms 2500 clear screens VGA_ClearScreen enter infinite loop print on VGA terminal screen Color 0 Term Print Hello world slow things down bit so we can read the text _delay_ms 10 end while end main First it should be amazing to you that in a few lines of code you are generating a VGA color text display Reviewing the code the program starts waits for the Propeller to boot don t forget to do this then the call to clear the screen and we enter the main while loop Here a redundant call to set the color is made and the text is printed to the VGA terminal with VGA Term Print that s it Summary This demo shows how easy it is to get VGA terminal like text output going on the Chameleon 218 2009 NURVE
2. _ T Tom v noa lt b gt gH creen 5 Le 179 E zu JN Q31 ngeq snieis di ES 38 a HE see Pr o BB 85 fas HERE I n 92 so dno aen I 2 s E saros 1 S He T T e porum 4 55 oc 20 oos Hollis ad Aiddng urew 008 pue an za EET ES 130a o an la m E Ed npe T K E E p D pe d Ajddns 009 MA donosd vos dona ode xB Ce x coe NOHd33 preoquo 27 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Www CHAMELEDN DEV COM vu hy n 0 2 A b A b lt r GVO Y Ss ecieeee 8 6 6 fais OND OND ISU AS ONDUIN 155 by LY CLs Od M IM D 2 Sd aba Bd E EE 0000000509005 IOA SET Bia 162 s v o OOC WAVY SSW 7
3. MAIN int main void initialize and set SPI rate SPI Init SPI DEFAULT RATE give Prop a moment before sending it commands the boot process is about a second if you like you can speed it up by removing the Prop driver s LED blink sequence in the driver or speed it up but commands that are sent before the Prop driver is done booting will be ignored therefore if you have a lot of set up work to do then you don t require a delay but if you jump right into commands then you need a good 1 5 2 second delay delay ms 2500 clear screens NTSC_ClearScreen NTSC Color 0 enter infinite loop print on NTSC terminal screen NTSC Term Print Status LED ON NTSC Term Char OxOD send command to turn on LED slow things down a bit so we can read the text delay ms 250 NTSC Term Print Status LED OFF NTSC Term Char OxOD send command to turn off LED slow things down a bit so we can read the text delay ms 250 end while end main The Arduino version simply has loop instead of main and the extra setup function as well as the different header file syntax T
4. 184 22 4 API Functional Declarations R 186 23 0 SOUND LIBRARY MODULE 2 2 194 23 1 Header File Contents Overview tense een ss sns se 195 23 2 API Listing Reference 195 23 3 API Functional Declarations RRR 195 24 0 KEYBOARD LIBRARY MODULE PRIMER 197 24 1 Header File Contents Overview 197 24 2 API Listing Reference osse 198 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 24 3 API Functional Declarations R 199 25 0 MOUSE LIBRARY MODULE PRIMER exor Dorn s n ix 200 25 1 Brief Mouse uui 201 25 2 Header File Contents Overview S 201 25 3 APL Listing 201 25 3 API Functional Decl
5. 257 APPENDIX B ATMEL AVR 328P PINOUT rir sei c cri 259 APPENDIX C BOARD LAYOUT AND I O HEADERS 260 APPENDIX D USING THE AVR IN STAND ALONE eene 261 APPENDIX E USING THE PROPELLER IN STAND ALONE MODE 261 APPENDIX F PORTING HYDRA AND PARALLAX DEVELOPMENT BOARD APPLICATIONS TO THE CHAMELEON 262 APPENDIX RUNNING ON THE MAC AND nnna 262 APPENDIX OVERCLOCKING THE AVR AND 263 H 1 Overclocking the Propeller Microcontroller e eres eee ee eese eene nennen net satin sat ens setas etna e tnun 263 H 2 Overclocking AVR328P Microcontroller cereis eee eee nete tn netta ses saeua s tasses sena 263 APPENDIX I ASCII BINARY HEX OCTAL UNIVERSAL LOOKUP TABLES 264 APPENDIX J ANSI TERMINAL CODES edades oda ee Re clle aS Ea i RE Rd erg 266 locuntur 267 10 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 0 0 Introduction and Origins Welcome to the Hardware Programming Manual for the Chameleon AVR 8 Bit
6. 1 PCINT20 XCK TO PD4 2 23 H PCO ADCO PCINTS PCINT19 OC2B INT1 PC1 ADC1 PCINTS Pe gt jee PCINT20 XCK TO PDA PCO ADCO PCINT8 vec GND GND 5 20 H AREF Ri vece 19 AROS PCINTG XTAL1 TOSC1 6 AVCC PCINTE XTALI TOSC1 PBS 17 18 PCINT7 XTAL2 TOSC2 PB7 PBS SCK PCINTS PCINT7 XTAL2 TOSC2 PB7 8 O Ce SCK PCINT5 PCINT21 OCOB T1 PDS MISO PCINT4 SERERE TR PCINT22 OCOA AINO PDS MOSV OC2A PCINT3 CPO ooo PCINT23 AIN1 PD7 PB2 SS OC1B PCINT2 a 8 5 8 5 8 8 PCINTO CLKO ICP1 PBO PB1 OC1A PCINT1 ce6ccamso Ezzbpbp5 09 8259659022 a at Q 2 AS SSoROO 2 06 Oz 5 g E 259 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix Board Layout and I O Headers This appendix has a high resolution grayscale image of the Chameleon AVR s PCB so you can identify the header I O pins easily for your projects Www CHAMELEON DEV COM P ONYO 4 AVM Y IVA VF OND OND Led AE s AS OND 055 955 SY by EU By Ly ay JEJCICICILILICILICILILIC CLs Oo SAMOS iS NESTON Yy ni E4 AU Da SPI MUX EE S PRETE PROP PORT DIGITAL YO cia VID EZPROM MELEONMEGAAWR S ELT cia c DIGITAL Ta POP GPE E 83 CHA
7. y 4 4 4 4 1 1 NC aq lt a 1 1 20 uC lt 4 54 1 meeer en SS eoo BI GoLOR LED BREAK AWAY SCORING You should have the following items in your kit referring to Figure 1 2 Chameleon AVR 8 Bit System Board DVD ROM with all the software demos IDE tools and this document White solderless experimenter board to be affixed to break away experimenter prototyping area on Chameleon if desired 1 Bi color Red Green LED Not Included power supply with tip ring 2 1mm barrel Mini B USB cable to go from PC to Chameleon AVR AVRMKIIISP Programmer The Chameleon will run off the USB cable so you do not require a wall adapter for development Also the Chameleon AVR is pre loaded with the Arduino bootloader therefore if you use the Chameleon in Arduino mode only you will not need an Atmel AVR ISP MK II programmer but we recommend one so that you can use AVR Studio to write more advanced C C and ASM programs and to have more control over the platform Additionally if you inadvertently damage the FLASH ed bootloader you will have to reload it Thus you need an AVR ISP MK II or similar programming hardware tool in the event you need to re FLASH the bootloader 15 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 1 2 Chameleon AVR Quick Start Demo Figure 1 3 The Console dem
8. s Color int col b8 ef 92 push r14 91 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit ba ff 92 push r15 bc 93 push r16 be 1f 93 push r17 c0 8c 01 movw r16 r24 sets the color of the character means different things under different drivers send driver set color command 0 col 0 7 SPI Prop Send Cmd GFX_CMD_VGA_PRINTCHAR OxOC 0x00 C2 88 0 r24 0x08 4 90 e0 r25 0x00 2 0 r22 c8 70 e0 r23 0x00 ca 40 e0 r20 0x00 Gee 50 0 ldi r21 0x00 94 3d 12 11 0 247 0 247 milliseconds can be achieved void count asm volatile d2 80 e4 ldi r24 0x40 94 e8 2e mov 14 r24 d6 86 0 ldi r24 0x06 d8 f8 2e mov r15 r24 da c7 01 movw r24 r14 dc 01 97 sbiw r24 0x01 1 f7 brne 4 delay us SPI PROP DELAY SHORT US SPI Prop Send Cmd GFX CMD VGA PRINTCHAR col amp 0x07 0 07 70 andi r16 0x07 e2 10 70 andi r17 0x00 B e4 88 0 r24 0x08 e6 90 0 r25 0x00 e8 b8 01 movw r22 r16 ea 40 0 r20 0x00 ec 50 0 r21 0x00 ee Oe 94 3d 12 call 0 247 0 247 f2 c7 01 movw r24 r14 f4 01 97 sbiw r24 0x01 f6 1 f7 brne 4 delay us SPI PROP DELAY SHORT US return success return 1 end VGA Color
9. Xcham_avidocs cham_avi_test propelle diver 7 14 these are just examples C3 development 15 advanced hydra programming 18 RAM Usage 7FFF apple mini 17 This drivers supports the follouing capabilities 19 0 COG B runs SPI channel message dispatch and MCP meste t Pi H 613 Lo 20 1 COG 1 runs ASSEMBLY language virtual SPI interface t 2 x ngs m se 21 2 NTSC video 1 COG simple terminal or more advanced Variable 423 Longs I DES 22 3 VGA video 1 COG Stack Free 3 152 Longs E am avr test a e 23 4 Multi channel audio 1 COG propeller driver d B 5 Keyboard or mouse 8 1 COG BHED menufactuing 5 1 0 to the Propeller Local 1 0 8 bit port Uses COG Of KTALI PLIEX toos 3 BG chen ric 27 Total COGS 5 8 Clock Freq 80 000 000 Hz padde 28 XIN Freq 5 000 000 Hz m 29 From the AYR PIC side you can write lot of interesting pr 2 36 follow the documentation tutorial on how to modify this dril 31 ran Parallax Dbjact Exchange ather sources Hex oaa Re SE Open BnaryFie save EEPROM Eie 38 ARCHITECTURAL OVERVIEW This systen works by the host AVR PIC sending 95 biet SPI interface to the virtual 34 SPI driver running launched by this object then as commands come thru the SPI data stream they are parsed and dispa
10. m oaas von M van sewn cz c Q30A Yos voam A vou LINY EE wey 2514 sto ed ope Hs 2 ga o lt vio ssed Wd as i 23 lt vai asn LM sio us inoss aen ssn ios as 3 HES E a waysig een ed lt gt oa pieogfeyesnoy Z Sd lt gt lt gt 25484 X1 unsny eamnupazoddns 6000992210 aue 49919 USMY GTI FANN ebay I 210 LL T 51 onaiqnedwios eco oe 524 585 uad snansuve mw ets HSE EL 9 lt gt ores Bo 6 mn
11. pe Bono we X T 88 83 d NECS n 9 5 I 5 1 oe 4 5 n He T T 2 5 5 zn E ieu ara ws E PN SOA Ajddng pue za a cone uiers s een auo moa u 2 in Ajddns 009 pose 0508 uersu lt gt occus Mp uow osos cont je E cusan x Te x T Z Sd come INOHd33 preoquo 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix B Atmel AVR 328P Pinout These images show the Atmel AVR644P DIP and QFP packages Figure B 1 Atmel AVR 328P pinouts TQFP Top View PDIP ea 20 0 EEG zz 222290856 seca 5 af 8 Y C aan 2 xuoaazon lt lt lt lt PRERRLLE 1ELELELELELEL TI PCINT14 RESET PC6 PC5 ADCS SCL PCINT13 PCINT16 RXD PDO 4 ADC4 SDA PCINT12 Qa PCINT17 TXD PD1 PC3 ADC3 PCINT11 FOINTISOCOBINTT EDS PCINT18 INTO PD2 PC2 ADC2 PCINT10
12. 640 480 B Horizontal Timing Diagram Red Green Blue c D gt HSYNC kB A gt Time 31 77 us 3 77 us 1 89 25 17 0 94 us C Vertical Timing Diagram 480 Horizontal Refresh Cycles Red Green Blue lt lt 5 gt VSYNC PI Parameters 0 P 0 R Time 16 6 ms 64 us 1 02 ms 15 25 ms 0 35 ms To begin with the VGA standard as implemented is 640x480 pixels across as shown in Figure 2 13 a The image is rendered left to right top to bottom similarly to the NTSC PAL signals and thus a similar syncing scheme is used that is composed of both a horizontal sync pulse each line and a vertical sync pulse each frame However there are no color burst signals serrations pre equalizations pulses etc the interface is nearly digital as noted The dot clock used in a basic VGA generation system is 25 175 MHz all timing can be derived from this base frequency Typically designers like to run the system dot clock at this frequency and compute all events as a number of clocks for example getting ahead of myself take a look at Figure 10 3 b the Hsync pulse which is labeled B in the table and a 41 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit negative polarity its 3 77us therefore at a dot clock of 25 175 MHz or inverting this to get the period t
13. HAY oe 260 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix D Using the AVR in Stand Alone Mode The nice thing about the Chameleon is that its two systems in one You are free to use the AVR as you wish and not worry about the Propeller chip However whatever driver that is on the Propeller will run and function independently even though you aren t sending it commands over the SPI channel Thus if you truly want to turn off the Propeller you might want to load a NULL program that does absolutely nothing such as CON These uS are for 5 MHZ XTALS _clkmode 11 1116 enable external clock and pll times 16 _xinfreq 5_000_000 set frequency to 5 MHZ PUB Main repeat forever loop This will start up a single processor and just sit and do nothing Of course without the Propeller you have no access to the physical peripheral headers such as the A V headers VGA or the PS 2 header But you still have access to the USB serial port as well as the FLASH memory And of course all the headers connected to the AVR around the board you still have access to Just make sure to keep the serial select switch in the DOWN position so the AVR has access to the USB serial port Appendix E Using the Propeller in Stand Alone Mode The Propeller in stand alone mode is much more interesting that the AVR The Propeller in stand alone mod
14. ave ccc Processor Message Find in Files Breakpoints and Tracepoints 28 Simulator Auto CAP NUM OVR Referring to Figure 15 21 and selecting View Toolbars from the Main Menu you can select de select various tools that you wish enabled in the IDE More or less enable all of them especially AVR GCC shown last in the list we need this tool so we have access to the source tree of our project You might want to do without the Processor and I O displays since they really only matter for simulation and debugging support but it s up to you When you select the AVR GCC tool you should see the file list control on the left side of the IDE as shown in the figure this is important The reason of course this file list is where we will add remove files for the current project in the Source Files folder as shown in Figure 15 22 below Figure 15 22 The AVR Studio GCC Source Files folder AVR Studio File Project Build Edit View Tools Debug Window Help Du dag vs BAGH BW 6 9 External Dependencies 4 Other Files 88 WARNING 15 1 4 1 Setting up the Project Options 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit We will get to adding files to the project in a moment right now we need to perform more setup to get the tool chain where we need it The next step is to launch the Configuration Opti
15. 21 Summary mouse 010 NS sound drv 052 likhz 16bit CHAM GFX DRV 001 TB 001 tl 3 Floppy w 0 O art Dev Cpp development advanced hydra programming apple mini arduino chameleon cham avr 3H docs cham avr test 173 propeller driver cham default2 drv 111 spin CHAM GFX DRV 001 TB O01 SPIN keyboard_010 spin mouse_010 spin deo TChit enin Propeller Source spin Mel Insert 3 cham default2 drv 111 spin 4 AUTHOR Andre L Look in My Recent Documents Desktop CJ My Documents M 38 ly Computer C3 propeller driver gt amp ex E3 cham default2 drv 111 spin a 5 CHAM GFX DRV 001 TB 001 5 1 GD keyboard_010 spin Type Propeller Source Code BJ mouse 010 spi Date Modified 9 2 2009 12 18 AM 2 Size 51 2 KB WB NS_sound_drv_052_11khz_16bit spin i VGA D10 spin E VGA Text 010 spin cham drv 111 spin Propeller Source spin M File name Files of type from the Parallax Object Exchange or other sources nam to be fas p version more gar bre commar don t you can alter anc 33 ARCHITECTURAL OVERVIEW This sustem works bu the host RVR PIC sending commands gt Once the source code is loaded into the tool you simple have to download it into the Chameleon AVR Make sure that you hav
16. Function Prototype long atoi2 char string Description atoi2 has a built in parser that can parse strings in decimal hexadecimal and binary formats The sentinels and are used for hex and binary representations with omission of sentinel meaning decimal conversion This function is convenient for text input and conversion algorithms so users can use any of the popular numeric bases as their inputs The function returns the value as a long thus all inputs have to fit into a signed long result Returns 0 if the function can t perform a conversion Example s Conversion examples from all bases char decimal string 12345 char hex string FFFF 65536 char binary strng 101 5 long result decimal conversion result atoi2 decimal_string hex conversion 144 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit result atoi2 hex_string binary conversion result atoi2 binary_string Function Prototype int Reset_Master void Description Reset Maslter causes a soft reset on the AVR chip basically re booting it Always returns 1 Example s Reset the AVR Reset Master Function Prototype int Reset Prop void Description gt Reset causes a soft reset on the Propeller chip basically re booting it Always returns 1 Example s Reset the Propeller then the AVR r
17. 238 X Modem Protocol z eie doce snes o ante Fee ee e tt ee EE eve 239 Sending X Modem Files from the PC ac eet ette e Pert e et eet dedu 243 32 1 Native Mode Bootloader eee eese eese eene eene etate sss snas essa essa seen sse 248 33 1 Developing Your Own Propeller Drivers 1 eeeeee eee e eee eene eene en seen sse en ss tesa eno 249 33 1 1 Adding SPIN Driver Support for the Status 250 31 1 2 Adding AVR Support at the Client Master 514 252 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 34 1 Advanced Concepts and deat sccsssccsssssssccsssecsssecsssscsssscsssssscssscsssscsssscssssssssessssscossscsssscnsssssesssccssscssssosssscssssesoeseoes 254 35 1 Demo Coder Applications Games and 255 35 11 Chameleon BASIC David nodo d etw ee dt eta ge ea e n eed 255 35 T2 Cr te It by JT Cooks 255 Epilog From Intel 4004 to the Multiprocessing Multicore Chameleon ceres sees eene eene een netta netta set en sse 256 APPENDIX A SCHEMATICS
18. OxFF Leaving programming mode OK This tab is where you command the tool to program the chip s FLASH or EEPROM memories In our case we are only going to program the FLASH memory with the HEX files generated by AVR Studio and AVR GCC Reviewing the Program tab at the top under Device make sure both check boxes are checked we definitely want to erase the device each programming cycle and verify it after programming to make the download was error free Additionally you can click Erase Device gt if you wish to simply erase the AVR chip and do nothing more 101 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Moving on the next area of interest is the Flash section of the tab This is very important and what we will be using to program the AVR chip Make sure the second radio button Input HEX File is selected then you must navigate on your hard drive in your project directory to the HEX file you wish programmed in each time Now this is an area that people make a lot of mistakes so please read the warning below very carefully WARNING Considering the warning make sure that the input file is set correctly To do this navigate with the button to the right of the control and locate your project directory for our work project named avr work Of default inside this directory you will find the HEX file that AVR Studio and GCC generated select the file an
19. Referring to Table 14 2 we see that each cycle the PWM the PHASE_ACC is incremented by 1 and the next element in the 256 element sine table is accessed thus the table is cycled thru at a rate of 256 000 256 1 000 Hz Perfect Now let s try another example where the frequency is higher than what we could sustain with our more crude approach at the beginning of the section with only a counter and not using the accumulator and fixed point approach Let s try to synthesize a 2550 Hz signal Co no o 3 4 4 5 PHASE_INC 65536 2550 256 000 652 8 Now this is a decimal number which will be truncated during the fixed point math to 652 but this is fine that s only an error or 73 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Truncation error 100 0 8 652 8 0 12 think can live with that Table 14 3 shows the results of the synthesis algorithm running once again Table 14 3 Test of PWM algorithm at 2500 Hz with PHASE_INC of 652 Iteration PHASE INC PHASE ACC PHASE ACC upper 8 bits 652 o C1 652 652 1304 652 1956 7 652 2608 10 652 3260 12 3912 652 4564 C1 N N 652 65000 As you can see in this case each cycle the sine table is accessed by skipping an entry or two causing a bit of distortion but since the table has 256 entries the amount of distortion is 1 2 a
20. after the array declaration This instructs the compiler to place the array in FLASH rather than SRAM However this isn t without side effects Now that the data is in FLASH you have to use special functions and techniques to access the FLASH data but this is more of an inconvenience that anything else For example later in the code when the logo is displayed the following function reads the data displays it on the terminal and makes some sounds draw WAR GAMES with characters from FLASH for index 0 index lt 52 5 index read the image from FLASH memory with special function call that uses ASM instruction to read FLASH pgm read byte amp title string flash index based data convert to character and send to UART i 29 Sound_Play 0 UART Print String else if js 1 Sound_Play 2000 UART_ ut end f Cindex 52 UART Print stringC Rar _delay_ms 50 end for have highlighted the special function needed to access FLASH based storage the pgm read byte function This is all you need to get to the bytes of the FLASH with a pointer The remainder of the main program is more or less printing strings with timing and a bit of conditional logic however there is one function that is the workhorse of the program and that s the Get String function When programming most programmers are completely oblivious to the
21. y 41 5A gt il Avs N ny 61 7A N w ar HD keypress and keystate keystate only So when you read a key from the keyboard driver its these keycodes that are going to be translated for you into ASCII The API listing for the Keyboard module CHAM KEYBOARD DRV 010 is listed in Table 24 1 categorized by functionality 198 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 24 1 Keyboard module API functions listing Function Name Description Keyboard Driver Control int Keyboard_Unload void Unloads the keyboard driver on the Propeller int Keyboard_Load void Loads the keyboard driver on the Propeller Keyboard Reading Functions int Keyboard_GotKey void Tests if a key is queued up int Keyboard_Key void Reads the next key from the queue int Keyboard_State int key Tests if a particular key is down The following lists each function a description comments and example usage of the function Function Prototype int Keyboard_Unload void Description Keyboard Unload unloads the keyboard driver on the Propeller and frees up a processing core Typically you will make this call before loading the mouse driver or to simply free a core for another process Returns 1 Example s Unload the keyboard driver to save power Keyboard unload O Function Prototype int Keyboard Load void Description gt Keyboard L
22. 112 15 2 3 1 Runnin ssthe Arduino imd E reo HO dp ra dere PE EH HUE 114 15 2 3 2 Eoadime the Hello World Sketcli 2 2 tdt o rob mee ebat md ee tu Hb i He Hd 118 15 2 3 3 A Couple Notes About the Arduino Version of Hello 121 15 3 INSTALLING THE PARALLAX PROPELLER 121 15 3 1 Launching the Propeller Tool eee eese eee eee een e eene einn tensa etna essa etes s stesse senate tasa senses en see snae 124 16 0 CHAMELEON INTER PROCESSOR ARCHITECTURE OVERVIEW 128 16 1 Master Control Program M QP ee eene eee eene sett en asset sn tasse teens esee tease 129 16 2 Selecting the Drivers for the Virtual Peripherals eese eese eese eene 131 16 2 1 Complete Data Flow from User to 132 16 3 Remote Procedure Call Primer Theory eee eee eee ee eee eese tasse etas esee toss 133 16 3 ASCILor Binary Encoded ep Rb MD 134 16 32 Compressing RPE fot More Band
23. W GPU GFX RAM 16 R GPU GFX RAM PORT16 W GPU GFX RASTER LINE R gpu configuration registers e 1ne efine GPU GFX SET AUTO INC R GPU GFX SET AUTO INC 164GPU GFX BASE ID 174GPU GFX BASE ID 18 GPU GFX BASE ID 194GPU GFX BASE ID 20 GPU GFX BASE ID 214GPU GFX BASE ID 224 GPU GFX BASE ID 234GPU GFX BASE ID 244GPU GFX BASE ID 254GPU GFX BASE ID 264 GPU GFX BASE ID 274GPU GFX BASE ID 284GPU GFX BASE ID 294 GPU GFX BASE ID 30 GPU GFX BASE ID 31 GPU GFX BASE ID 324GPU GFX BASE ID 33 GPU GFX BASE ID 344GPU GFX BASE ID 35 GPU GFX BASE ID 36 GPU GFX BASE ID Reads current fine horizontal scroll register 0 7 NOTE NOT implemented yet Writes current fine horizontal scroll register 0 7 NOTE NOT implemented yet Reads current fine vertical scroll register 0 7 Writes current fine vertical scroll register 0 7 Reads screen width value 0 16 tiles 1 32 tiles Writes screen width value 0 16 tiles 1 32 tiles 2 264 tiles etc 2 64 tiles etc Reads 16 bit source address for GPU operations Writes 16 bit source address for GPU operations Reads 16 bit destination address for GPU operations Writes 16 bit destination addres
24. print on NTSC terminal screen NTSC Term Print sbuffer NTSC Term Char OxOD print on VGA terminal screen Term Print sbuffer Term Char OxOD slow things down a bit so we can read the text delay ms 500 end for index The comments should explain everything that is going on but make sure to pay attention to the highlighted lines of code that compute frequencies using the pow function Basically to compute the nth adjacent note on a standard diatonic scale you multiply the key note frequency by 2 72 taken to the nth power Once the chord frequencies are computed they are issued to the sound driver to play on 3 different channels leaving one left 224 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Summary This demo shows how to play music using the sound API However be aware the sound driver running on the Chameleon s Propeller chip can do a lot more than we expose with the API so if you want more features you can add them by modifying the Propeller s master driver 30 1 Input Device Demos The following demos illustrate the input devices supported on the Chameleon the keyboard and mouse The demos drive either the NTSC VGA or both But if you want to add support for the other its simply a matter of adding a couple lines of code The examples typically consist of the primary source file for the demo as well as The System AP
25. 35 determines if mouse is present and returns type of mouse define MOUSE CMD define MOUSE define MOUSE CMD START 33 CMD_ general data readback commands define READ_CMD 36 sound commands define SND CMD PLAYSOUNDFM 40 plays a sound a channel with the sent frequency at 90 volume define SND CMD STOPSOUND 41 stops the sound of the sent channel define SND_CMD_STOPALLSOUNDS 42 stops all channels define SND CMD SETFREQ 43 sets the frequency of a playing sound channel define SND CMD SETVOLUME 44 sets the volume of the playing sound channel define SND CMD RELEASESOUND 45 for sounds with infinite duration releases the sound and it enters the release portion of ADSR envelope propeller local 8 bit port I O commands define PORT CMD SETDIR 48 sets the 8 bit I O pin directions for the port 1 output O input define PORT CMD READ 49 reads the 8 bit port pins outputs are don t cares define PORT CMD WRITE 50 writes the 8 bit port pins port pins set to input ignore data general register access commands Propeller registers for the SPI driver cog can be accessed ONLY but the user can leverage the counters and even the video hardware if he wishes most users will only play with the counters and route outputs inputs to from the Propeller local port but these generic access commands model how you would access a general register based system remotely so good exampl
26. M V V SDA NI x X X SCL X SN N N BM N 1 2 7 8 9 START SLA R W A START condition is always followed by the unique 7 bit slave address along with a single bit signifying the Data Direction either read or write The Slave device addressed acknowledges the Master by holding SDA low for one clock cycle If the Master does not receive an acknowledgement the transfer is terminated Depending of the Data Direction bit the Master or Slave now transmits 8 bits of data on the SDA line The receiving device then acknowledges the data Figure 19 5 shows what happens during data transmission following the initial START and addressing phases Figure 19 5 Timing waveforms for I2C data transmission Data MSB Data LSB ACK N N SDA X X X X X N i N _ Ce O i Data Byte STOP Multiple bytes can be transferred in one direction before a repeated START or a STOP condition is issued by the Master The transfer is terminated when the Master issues a STOP condition A STOP condition is defined by a low to high transition on the SDA line while the SCL is high Confusing isn t it If a Slave device cannot handle incoming data until it has performed some other function it can hold SCL low to force the Master into a wait state for as long as it needs to All data packets transmitted on the bus are 9 bits long consist
27. 207 210 211 212 213 214 215 216 217 01001000 01001001 01001010 01001011 01001100 01001101 01001110 01001111 Bin 10000000 10000001 10000010 10000011 10000100 10000101 10000110 10000111 10001000 10001001 10001010 10001011 10001100 10001101 10001110 10001111 Bin 11000000 11000001 11000010 11000011 11000100 11000101 11000110 11000111 11001000 11001001 11001010 11001011 11001100 11001101 11001110 11001111 Dec 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 130 132 133 134 135 137 Oct 220 221 222 223 224 225 226 227 230 231 232 233 234 235 236 237 Oct 320 01011000 01011001 01011010 01011011 01011100 01011101 01011110 01011111 Bin 10010000 10010001 10010010 10010011 10010100 10010101 10010110 10010111 10011000 10011001 10011010 10011011 10011100 10011101 10011110 10011111 Bin 11010000 11010001 11010010 11010011 11010100 11010101 11010110 11010111 11011000 11011001 11011010 11011011 11011100 11011101 11011110 11011111 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 104 105 106 107 108 109 110 111 Dec 160 161 162 163 164 165 167 168 169 170 171 172 173 174 175 68 69 6A 6B 6C 6D 6E 6F 150 151 152 153 154 155 156 157 Oct 240 241 242 243 244 245 246 247 250 251 252 253 254 255 256 257 Oct 340 01101
28. NTSC GFX driver module CHAM GFX 010 is listed in Table 22 2 categorized by functionality 184 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 22 2 GFX module API functions listing Function Name Description Pa ea GPU sub functions a eee int GFX_GPU_Fill_Mem16 unsigned int dest_ptr unsigned int value unsigned int num bytes Fills memory 16 bits at a time int GFX Copy Memt 6 unsigned int dest ptr unsigned int src ptr unsigned int num bytes Copies memory 16 bits at a time int GFX GPU Fill Mem8 unsigned int dest ptr unsigned int value unsigned int num bytes Fills memory 8 bits at a time int GFX GPU Mema8 unsigned int dest ptr unsigned int src ptr unsigned int num bytes Copies memory 8 bits at a time SX CM MM VM SRI Palette pointer access functions unsigned int GFX_Read_Palette_Ptr void Reads the tile map palette pointer unsigned int GFX_Write_Palette_Ptr unsigned int palette_ptr Writes the tile map palette pointer ee Tilemap pointer access functions en ee unsigned int GFX Read Tilemap Ptr void Reads the pointer to the top of tilemaps unsigned int GFX Write Tilemap Ptr unsigned int tilemap ptr Writes the pointer to the top of tilemaps Bo a EMEND O Bitmap pointer access funtions CR unsigned int GFX Read Bitmap Ptr void Reads the pointer to
29. display devices define DEVICE NTSC 0 define DEVICE VGA 1 PROP SPI driver media and IO command set SPI commands define CMD_NULL 0 NTSC commands define GFX_CMD_NTSC_PRINTCHAR 1 define GFX_CMD_NTSC_GETX define GFX_CMD_NTSC_GETY 3 define GFX_CMD_NTSC_CLS 4 commands define GFX_CMD_VGA_PRINTCHAR 8 define GFX_CMD_VGA_GETX 9 define GFX_CMD_VGA_GETY 10 define GFX_CMD_VGA_CLS 11 keyboard commands define KEY_CMD_RESET 16 define KEY_CMD_GOTKEY 17 define KEY_CMD_KEY 18 define KEY_CMD_KEYSTATE 19 define KEY_CMD_START 20 define KEY_CMD_STOP 21 define KEY_CMD_PRESENT 22 mouse commands define MOUSE CMD RESET 24 resets the mouse and initializes it define MOUSE CMD ABS X 25 returns the absolute X position of mouse define MOUSE CMD ABS Y 26 returns the absolute Y position of mouse define MOUSE CMD ABS 7 27 returns the absolute Z position of mouse 7 5 define MOUSE CMD DELTA X 28 returns the delta X since the last mouse call define MOUSE CMD DELTA Y 29 returns the delta Y since the last mouse call define MOUSE DELTA Z 30 returns the delta Z since the last mouse call define MOUSE CMD RESET DELTA 31 resets the mouse deltas define MOUSE CMD BUTTONS 32 returns the mouse buttons encoded as a bit vector ie starts the mouse driver loads a COG with it etc ET STOP 34 stops the mouse driver unloads the COG its running on
30. function always sets serial to N81 so just need the baudrate to max UART Init 115200 Function Prototype int UART Shutdown void Description UART Shutdown shuts down USARTO s interrupts Call it when you are done with the UART Note that you can still use the manual transmit and receive functionality of the UART but the interrupt driven system is disabled after this call Returns 1 always Example s Shutdown the UART interrupts UART Shutdown Function Prototype int UART putc unsigned char ch Description UAHRT putc places a character into the outgoing transmit circular buffer from there the ISR will continue to process the characters and send them out the UART as the transmitter buffer empties This function is non blocking and returns immediately Returns the character sent if successful else O if fails Example s Send an ASCIIZ encoded string out to the UART int length char string This is a test compute length length strlen string loop and send each character for index 0 index lt strlen index UART putc string index Function Prototype void UART_Transmit unsigned char ch Description _UART_Transmit sends a single character out the UART The function takes as a parameter the character to send and the function blocks until the transmitter is free Use this function is you don t care about using the transmitter inte
31. here is the problem Processor B can t perform another function until it completes the last requested command thus we need a mechanism that blocks processor A and makes it wait for processor B when this set of conditions occur That s what the code above does So if processor A the AVR ask for too much too fast processor B the Propeller says hold on a minute let me finish the last thing 165 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The function that actually sends the command is listed below this function is used to send SPI commands to the Propeller slave processor long SPI Prop Send cmd2 int cmd int data int status long status_low status_high status_busy set CS to SPI select select Prop SPI channel 2 qu SPI CS PORT 1 lt lt SPI CS1 0 lt lt SPI CSO send command byte and retrieve low byte of result 2 status low SPI WriteRead cmd 3 delay us SPI PROP CMD DELAY US send command byte and retrieve high byte of result 4 status high SPI writeRead data DE _delay_us SPI_PROP_CMD_DELAY_US send command byte and retrieve busy byte of result 6 status_busy SPI_WriteRead status 7 delay_us SPI_PROP_CMD_DELAY_US set CS to SPI select channel 0 null 8 SPI_CS_PORT 0 lt lt SPI_CS1 0 lt lt SPI_CSO _delay_us SPI_PROP_CMD_DELAY_US 10 return status_busy lt lt 16 status_high lt lt 8 st
32. interface Atmel created generalized hardware that supports the format but isn t designed specifically for it In any event TWI TWI for our purposes but the registers 152 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit in the AVR 644 are all TWI prefixed and suffixed so don t get confused Finally SPI has nothing to do with this so SPI is called SPI SPI stands for Serial Peripheral Interface originally developed by Motorola Its one of two very popular modern serial standards including which stands for Inter Integrated Circuit by Phillips SPI unlike which has no separate clock is a clocked synchronous serial protocol that supports full duplex communication However only takes 2 wires and a ground Where SPI needs 3 wires ground and potentially chip select lines to enable the slave devices But SPI is much faster so in many cases speed wins over and the extra clock line is warranted The advantage of 12C is that you can potentially hook hundreds of devices on the same 2 bus lines since devices have addresses that they respond to SPI bus protocol on the other hand requires that every SPI slave has a chip select line Figure 19 1 The SPI electrical interface Figure 19 1 shows a simple diagram between a master left and a slave right SPI device and the signals between them which are SCLK Serial Clock output
33. www atmel com and check out the AVR page accept the terms of the InstallShield The license screen is the usual you would expect simply press lt Next gt to continue This brings up the installation target directory as shown in Figure 15 4 below 78 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 4 AVR Studio installation directory selection InstallShield highly recommend you select a shallow installation directory for the files In other words don t put the installation in a long path with many sub directories would install the software right off the root of one of your drives This way it s easy to type the path for command line applications Moreover use AVR in the suffix of the path for convention purposes makes it easier to find the installation Finally avoid spaces in your directory names and suggest not using drive the less you put on your OS drive the better You ever wonder why Windows gets slow after a while The reason is that there are so many files on the install drive DLLs in the Windows directory etc that the performance of Windows grinds to a halt So anytime you can put apps on another drive or partition that s your best bet My Programs is cute for soccer moms but to be avoided as an installation target for serious programmers Once you have selected the desired installation directory go ahead and press Next to contin
34. 0 47 9 4 oO wO a7E0r z wO 0750 1 wO m 5750 fn eT x I 1 0 XU 5 ro e n Arb x 2 6 m 0750 1 oO amp 7 1 40 0 6 O 0 eb O 1 O m O samt Ld amp 7 oO o eO mf mim mO eb a O rors bx 4 7Z0 Z mf Compiling and Running the AVRStudio Version Demo Version Description NTSC version prints Hello World to screen Main Source File CHAM AVR NTSC PRINT DEMO 01 211 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Additional Files Required CHAM_AVR_SYSTEM_V010 c h CHAM AVR SPI DRV VO010 c h CHAM AVR DRV VO010 c h General Requirements Video port connected to NTSC TV monitor Controls Required None Compiling and Running the Arduino Version Demo Version Description NTSC version prints Hello World to screen Main Sketch Source File CHAM AVR NTSC PRINT DEMO Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR SPI DRV 010 CHAM AVR DRV 010 General Requirements Video port connected to NTSC TV monitor Controls Required Non
35. Application Flash Section OxO4FF OxO4FF OxOFF OxO8FF Boot Flash Section OxOFFF Ox1 FFF Ox3F FF Referring to Figure 1 6 Program Memory is composed of both a Boot FLASH Section and the Application Section The boot section holds boot ROM code and can be different sizes or disabled The application section then holds the actual run time code for the application The Data Memory is stored in SRAM of course and is 2048 bytes in length However due to register space allocation there is a shift in the addresses the first 256 byte addresses are used to access registers and system I O then from address 0100 08FF is the 2K block of free memory Not shown in the 21 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit memory map is the stack which will need to go somewhere when you run your code the C C compiler sets this up for you When programming in pure ASM you would have to set the stack pointer appropriately The AVR C C compiler is based on the GNU GCC tool chain and thus is not the best optimizing compiler on the planet but isn t bad Hence our approach will be to use C primarily for our coding and any time critical performance code you will want to write in assembly language if you need to But we want to rely on C as much as possible for ease of use ASM should be used for drivers when necessary via APIs that can be called from C Additionally the Arduino tool chain uses C C as well E
36. CHAM AVR KEYBOARD DRV 010 CHAM AVR FLASH DRV 010 General Requirements NTSC or VGA display connected local PS 2 keyboard connected X Modem download program running on PC N81 2400 baud Controls Required Local PS 2 keyboard simply use menu also PC running X Modem uploader Technical Overview The program is probably the most complex of all since it has to do so much We need a NTSC VGA menuing system that allows the user to enter menu options then we needed the X Modem function to receive files which a project in itself and finally the FLASH memory call to display and save the FLASH data So a lot of parts but with a little imagination you can use this program as the basis of a MP3 or video player You can download files into the FLASH with the X Modem function then write code that decompresses video or audio and presto Anyway we have already seen the X Modem receive file listing earlier in the overview and the complete program is rather long too long to list Therefore am just going to verbalize the FLASH aspect of it the program Forgetting about the X Modem support accessing the FLASH memory is trivial with the API all you need to do is call Flash then you can read data with the Flash Read function When you re done call Flash Close and that s it If you want to write to the flash memory then in addition to the Flash Open call you must make sure that the blocks or sectors you want to w
37. Hello World Hello World Hello World Hello World Hello World ello World Hello Compiling and Running the AVRStudio Version Demo Version Description version prints Hello World to screen Main Source File CHAM_AVR_VGA_PRINT_DEMO_01 C Additional Files Required CHAM AVR SYSTEM V010 c h CHAM AVR TWI SPI DRV V010 c h CHAM AVR DRV VO010 c h General Requirements VGA port connected to VGA monitor Controls Required None Compiling and Running the Arduino Version Demo Version Description version prints Hello World to screen Main Sketch Source File CHAM_AVR_VGA_PRINT_DEMO Additional Library Files Required imported automatically by sketch CHAM_AVR_SYSTEM_V010 CHAM AVR TWI SPI DRV 010 CHAM AVR V010 General Requirements VGA port connected to VGA monitor Controls Required None Technical Overview The demo simply uses the VGA API to print Hello World on the screen When the printing reaches the bottom of the screen the terminal scrolls the screen image up one line The program is so short let s take a quick peek at only the contents of the main or loop in the Arduino version 217 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit MAIN
38. If interesfing modify this d sources virtual SPI Interface ASM language pr If the Propeller tool can t find the Propeller chip then try unplugging the USB cable from the Chameleon hit the reset switch make sure that the serial select switch is in the UP position Once the firmware is downloaded into the Propeller chip on the Chameleon board it will immediately start generating NTSC and VGA video If you hit RESET on the Chameleon you will see the images shown in Figure 15 68 on the NTSC and VGA monitors respectively Figure 15 68 The NTSC and VGA monitors showing the Chameleon AVR s output after installing the Propeller driver firmware Chameleon SPI Driver2 V1 11 Chameleon SPI Driver 58 pPriver Initialize NTSC Driver Initialized 9 E VGA Driver Initialized eUbSara aver Sound Driver Initialized Ready for commands Keyboard Driver Initialized Ready for commands chanelSsonPEF RGIME Nurve Networks LLC 20 126 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Also when you hit reset each time you will see the LED D3 under the Video port blink 3 times shown in Figure 15 69 this is part of the testing firmware to confirm the Propeller chip is functioning correctly as well as to verify the LED is good Finally you will HEAR the Chameleon make sounds as it boots up a ser
39. Program You should see a progress bar at the bottom of the IDE interface as highlighted in Figure 15 40 below Figure 15 40 Programming the Chameleon AVR and the progress bar at the bottom of the IDE is proof Io E m Last Modified 9 22 69 43 Header Files a E CHAM AVR NTSC DRV VO10 h Description NTSC UGA demo of Hello World P CHAM AVR SYSTEM V010 h Wi E CHAM_AVR_TWI_SPT_DRV_VO10 h Overview Simply prints out He AVRISP mkil in ISP mode with ATmega328P oR CHAM_AVR_VGA_DRV_VO10 h a External Dependencies Sy Other Files Erase Device INCLUDES 7 7 Erase device before flash programming Verify device after programming __AUR_ATmega328P___ __AUR_ATme Us Caren Simulator AUR_ATmega328P vei v Input HEX File rcecham avr work lNdefaull cham avr work 01 include everything lt stdint h gt Verify lt stdio h gt lt stdlib h gt EEPROM lt string h gt ca ERR TIE emda ctype h om h gt Program Verify Read AVR GCC Processo E D development chameleon cham_avr source cl IE L Production Fie Format El Build x eee Input ELF File Device atmega328p Fuses and lockbits settings Program Save must be specified before Program 2016 bytes 6 2 Full saving to ELF text
40. With that in mind there are a number of C and H files that make each up class of library functionality for the Chameleon API At this point we are going to drill down and list each of the files with a short description Then we are going to discuss the key data structures and header files for each library module list the functions one by one with examples Finally all source files can be found on the DVD at location DVD ROM CHAM_AVR SOURCE Of course you should have already copied this to your hard drive into your project s working directory To save space we are not going to list the contents of each source file since that would take hundreds of pages however key elements will be listed for reference Nonetheless you should have your editor pointed to the source directory so you can review the complete contents of each file as we discuss them The System library module consists of a single C source file and its header The System modules must be included in every Chameleon AVR program since its contains some top level defines types and other pertinent elements that other API modules depend on Additionally the C source file contains a few utility functions that will continue to grow in the future The System source files are named below CHAM_AVR_SYSTEM_V010 c Main C file source for System module CHAM_AVR_SYSTEM_V010 h Header file for System module You should include the h file wi
41. bot gd 6d td 5d 9d d rere rik 2 i Bm GIA FING 260101610616 gH PN DUN Luc rh tH evod S ANOA WIA LEE EI ee 6 28 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 2 0 5 0V amp 3 3V Power Supplies Figure 2 1 The Chameleon AVR power supply design VIN 5 0V 500 mA Main Supply 5VCC REG U1 TITLV1117 50 PWR IN 9 12V 33VCC GND D2 LED 3 3V 500 mA Main Supply Main Power Switch and Supply Summer 5VCC U2 33VCC Sw1 TITLV1117 33 PWR SWITCH 5VCC REG 5VCC USB_SVOUT The Chameleon AVR system has a duel 3 3V 5 0V power supply system that is feed by a single 9V DC unregulated input from a wall adapter or feeds from the USB port header The supplies design is shown in Figure 3 1 for reference The supplies are straight forward the only interesting thing is the coupling of the USB power and the regulated power at node 1 of the power switch SW1 This allows the system to use power from either the regulated supply or the USB port The Chameleon AVR is a mixed voltage system to support 5V AVR and 3 3V Propeller chip Both supplies are independent and can each supply up to 500 mA for all your needs Additionally the power supplies are exported to the expansion header J7 for external interfacing 3 0 Reset Circuit Figure 3 1 The Chameleon AVR reset circuit 5vcC USB DTR Reset Sig
42. lt aur sleep h gt lt util delay h gt lt aur interrupt h gt This should bring up the AVR programmer selection tool as shown in Figure 14 34 below Figure 15 34 The AVR programmer selection tool Select AVR Programmer Platform Port STK500 or AVRISP USB m JTAG ICE 2 JTAGICE mkll EE AVRISP mkll ance AVR Dragon Baud rate 5 00 15200 gt To auto connect to the programmer used last time press the Programmer button on the toolbar Baud rate changes are ih active immediately Note that a tool cannot be used for programming as long as it is connected in a debugging session In that case select Stop Debugging first Disconnected Mode At this point make sure the AVR ISP MK Il is plugged into a USB port on the PC and the programmer itself is plugged into the Chameleon AVR s ISP port as shown in Figure 15 34 Pay attention to the pin out the red line should be at the top Finally make sure the Chameleon s power cable is plugged in and the unit is powered up and ON This tool selects which Platform you want to use for your programming debugging left list box and then in the right list box for the tool selected it lists the available communication devices in this case only USB is listed go ahead and select AVRISP and USB as shown in the figure and then click connect Make sure you have the AVR ISP USB cable connected t
43. 06 OK The control panel might launch starting with another tab so go ahead and select the Main tab as shown in Figure 15 36 so you can follow the setup steps This control panel sets up the AVR ISP programmer and can perform many 100 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit tasks Additionally this tool can actually damage the AVR chip if you don t set it up correctly For example you can force the wrong part fuse bit settings etc and then download garbage to the chip locking it up therefore this tool must be set up correctly and care taken when using it Let s begin with the Main tab as shown in the figure This tab allows you to select the type of device you want to program read the device signature a unique id that indicates what the device is as well as set the type of programming mode ISP or JTAG along with the frequency of programming Let s talk about each selection in brief Device and Signature Bytes These two controls select and indicate the device and respective signature read manually In our case we want to select the ATmega328P as shown in the figure additionally you can click the lt Read Signature gt button and the tool will read the device signature out of the Chameleon AVR and check it against the device you have selected in the above list box For example the AVR Mega329P should have the signature Ox1E 0x95 Programming Mode
44. 07 0c 07 02 LONG 07 Oc 07 02 LONG 07 Oc 07 02 LONG 507 0c 07 02 palette index LONG 07 0c 07 02 palette index palette index LONG 07 Oc 07 02 palette index palette index palette index palette index HO LONG 07_0C_07_02 palette index LONG 07 0c 07 02 palette index 10 LONG 07 0c 07 02 palette index 11 LONG 07 OC 07 02 palette index 12 LONG 07 0c 07 02 palette index 13 LONG 07 07 02 palette index 14 LONG 07 Oc 07 02 palette index 15 As you can see the palettes are defined at the label tile pallete map and each entry is s a LONG The register you access the palettes from in the global register interface is called palettes base ptr parm You can read or write this pointer and thus modify palette entries Now let s talk about the format of each color The color format is always the same the 32 bits of each palette entry represent 4 possible colors that are indexed by the 2 bit pixel data the colors are encoded as a single byte each in the following way Where each color byte is encoded as follows Composite Video Color Byte Format Luma 0 7 Modulation Enable 0 disable chroma color modulation 1 enable chroma color burst modulation Color phase shift for color burst signal 0 15 this selects 1 of 16 phase shifts which represent 16 colors equally spaced around the color wheel for NTSC PAL modes The color byte is use
45. 320x200 in 256 colors Mode 13h chunky graphics mode spent many years writing graphics algorithms and drivers for VGA cards to push them to the outer limit now my cell phone has better graphics However the VGA spec is great for baseline computer displays and any standard modern computer monitor will display old school 640x480 VGA modes and refresh rates However the Propeller chip can generate VGA modes at much higher resolutions and there are a number of multicore hi resolution drivers that you can employ that go all the way up to 1200x1024 or greater last time checked on the Parallax Object Exchange You can use any of these drivers with the Chameleon You just need to modify the Propeller driver module include the new VGA drivers make connections to it via commands and you are off and running 37 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 10 1 The Chameleon AVR VGA interface and support hardware VGA RGB 2 2 2 Summer Sync R19 VGA RED B1 gt 270 NC R20 560 VGA RED B0 gt NC NC R21 270 VGA_GREEN_B1 gt R22 VGA GREEN gt 560 NC CONN D15F R23 VGA BLUE B1 gt 270 R24 BLUE gt ze 560 R25 100 VGA_HSYNC gt R26 VGA_VSYNC gt 100 The VGA hardware for the Chameleon is very minimal since the Propeller chip is doing all the signal generation with direct control of the VGA signal via its bu
46. AC AC 00 00 format bc tc hv ww tc top overscan color bc bottom overscan color h horizontal scroll 0 7 v vertical scroll 0 7 ww width 0 32 tiles 1 64 tiles 2 128 tiles 3 256 tiles green overscan with AC So the format of this 4 byte value is bottom overscan color top overscan color horizontal and vertical smooth scroll playfield width The top and bottom overscan colors these are the colors on the top and bottom of your TV screen usually black are in a simple luma chroma format which we will discuss in the section below on color palettes The horizontal and vertical smooth scroll are encoded as 4 bits each but only vertical smooth scrolling works currently and the valid values are 0 7 Finally the playfield width is controlled with this register as well It can be 32 64 128 or 256 tiles wide a subset of powers of 2 Now this register is accessed via a number of separate shadow registers in the global register interface but wanted you to see this in the code so when we discuss the registers they are familiar Tile Map Entry Format Each tile map entry is a 2 bytes In the following format msb palette index tile index Clsb The low byte is the actual tile character index 0 255 and the high byte is the palette index 0 255 However in most cases you won t have this many tiles or palettes In fact initially there are only 16 palettes 0 15 and there are 144 bitmaps extracted fr
47. B E T 17 This drivers supports the follouing capabilities j iy Dev Cpp 9 COG runs SPI channel message dispatch and MCP master control development 20 1 COG 1 runs ASSEMBLY language virtual SPI interface that RVR usnm 2 NTSC video 1 COG simple terminal or advanced graphics Lh odo 2 3 VGA video 1 COG 23 4 Multi channel audio 1 COG cham 5 Keyboard or mouse 0 1 COG dos 5 1 0 to the Propeller Local 1 0 8 bit port Uses COG runs i cham avr test eo Total COGS 5 6 gt 28 chem div TT spin 28 From the RVR PIC side you can urite a lot of interesting programs t CHAM GFX DRV_001_TB_001 SPIN Q follow the documentation tutorial on how to modify this driver so Beaded 1 from the Parallax bject Exchange or other sources mouse_010 spin 32 NS_sound_drv_052_11khz_16bit spin 33 ARCHITECTURAL OVERVIEW This system works by the host RVR PIC sel VGA_010 spin 34 SPI driver running launched by this object then as commands comel VGA_Text_010 spin j to the proper drivers running on other COGS Here s a visual of uha Uses COG B runs in main thread for nou Propeller Communication the Programming EEPROM s function by the host RVR P interface then as commands come tea the SPI stream they are par Here s a visual of what s going on
48. Click Next to continue Select the radio button to install the software automatically and then click Next Unless something went wrong with the AVR Studio installation you should see the hardware being installed as shown in Figure 15 9 below Figure 15 9 Windows installation AVR ISP hardware and drivers Found New Hardware Wizard Please wait while the wizard searches mkll 81 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit When complete simply press Next then the drivers should install If all went well you should see the final splash screen shown in Figure 15 10 Figure 15 10 AVR ISP drivers successfully installed Found New Hardware Wizard Completing the Found New gt Hardware Wizard SS The wizard has finished installing the software for AVRISP mkll Click Finish to close the wizard Press Finish and the programmer should be ready to go 15 1 3 Installing WinAVR WinAVR is a complete open source Windows based installation of the GNU GCC compiler and tool chain that integrates into the installation of AVR Studio You can find out more here http winavr sourceforge net We are very lucky to have this without it we would have to use 3 party compiler which costs lots of On the other hand it s GNU GCC based which means very little support and documentation
49. During the active video you don t need to worry about the Vsync line since you would be 42 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit generating 480 lines of video when complete back to the Vsync timing region S the front porch for 0 35 ms and then the frame is complete The thing to remember is that unlike composite video a VGA signal needs to be driven by multiple signals for each of the constituent controls G B Hsync and VSync which in my opinion is much easier than modulating and mixing them all together as in NTSC which is a blood bath of crosstalk and noise Now that we have the horizontal and vertical timing for VGA covered let s review the actual video data portion of the signal during the active video and see what that s all about Table 10 4 The RGB signals and their relationship to VGA and the Propeller pins Prop Port Bit Chameleon Signal Description P23 VGA RED B1 Bit 1 of RED channel P22 RED Bit 0 of RED channel P21 VGA GREEN B1 Bit 1 of GREEN channel P20 VGA GREEN B0 Bit 0 of GREEN channel P19 VGA BLUE B1 Bit 1 of BLUE channel P18 VGA_BLUE_BO Bit 0 of BLUE channel P17 VGA HSYNC VGA HSYNC TTL level P16 VGA VSYNC VGA VSYNC TTL level 10 3 3 Generating the Active VGA Video Generating the actual RGB video pixels is trivial on any system there is no look up no math just send out bytes or words that represent the RGB values and that s it Of
50. Exploring the Chameleon AVR 8 Bit Technical Overview This demo really shows off the UART and bi directional communications Not only are we printing to the UART for display on the terminal on the PC but we are getting input from the terminal and processing it so it s a very complete two way communications demo Also there are some animations and fun techniques that are used to display the logon logo and other effects to sell the game For example the intro logo is an array of data that is used to print out WarGames the title screen bitmap as a matrix of byte stored in FLASH for fun then to render we will convert to characters BLOCK and SPACE notice the use of const and PROGMEM also to access the array we must use pgm read byte addr size of banner 52x5 const unsigned char title string flash PROGMEM O A 00 0 ili il Opal abo 2550 ala ak al 0 al il c dL al ib 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 1 1 0 1 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 0 1 0 1 0 1 0 1 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 a tarde rene Sega aad The interesting thing about this array is that its defined in FLASH memory rather than SRAM so this demo shows how you do that Notice the keyword
51. GPU GFX BASE ID GPU GFX BASE ID GPU GFX NUM COMMANDS 1 call single processing function g spi result gfx ntsc GPU GFX Process Command g cmd g_datal6 NTSC GFX TILE SPECIFIC COMMANDS LILLI we only expose a subset of the commands the driver supports you can add subtract more commands as desir some commands like PRINTCHAR for example internally support a number of sub commands that we don t need a expose at this level unless we want to add funcitonality GFX_CMD_NTSC_PRINTCHAR this command pipes right to the out function of the driver which supports the following sub commands already 00 clear screen 01 home 08 backspace 09 tab 8 spaces per 0A set X position X follows 0B set Y position Y follows 0C set color color follows 0D return anything else prints the character to terminal gfx ntsc Out Term g data GFX NTSC GETX return x position in spi buffer next read will pull it out on last byte of 3 byte packet g spi result gfx_ntsc Getx GFX NTSC GETY return y position in spi buffer next read will pull it out on last byte of 3 byte packet g spi result gfx ntsc GetY GFX CMD NTSC CLS eventhough this command is supported above we break it out as a seperate SPI command just in case we want add functionality on top of like overloading and handling manually notice we end up calling the 00 ee command but we have
52. The VGA specification is more of a base point than anything anyone actually uses anymore IBM released the VGA or Video Graphics Array technology in 1987 roughly It was touted to change the world definitely an improvement from CGA and EGA but it was doomed from the start with not enough resolution shortly after higher resolution monitors were available and the VGA specification was enhanced with the Super VGA standard but this was only a momentary hold on its execution what was needed was a more progressive standard that could change at any time and thus the VESA Video Electronics Standard Association graphics cards and drivers were created and the rest is history However the original specs for the VGA are shown below 256 KB Video RAM 16 color and 256 color modes 262 144 value color palette six bits each for red green and blue Selectable 25 MHz or 28 MHz master clock Maximum of 720 horizontal pixels Maximum of 480 lines Refresh rates up to 70 Hz Planar mode up to 16 colors 4 bit planes Packed pixel mode 256 colors 1 byte per pixel Mode 13h Hardware smooth scrolling support Some raster operations Raster Ops support to perform bitmap composition algorithms Barrel shifter in hardware Split screen support Soft fonts Supports both bitmapped and alphanumeric text modes Standard graphics modes supported by VGA are 640x480 in 16 colors 640x350 in 16 colors 320x200 in 16 colors
53. There are two very large tables at the end of the driver that define the keys in terms of scan codes and ASCII codes The tables are too long to list but here s a excerpt from the first table Lookup table Y ascii scan extkey regkey table word 0000 00 50008 01 F9 word 0000 02 50004 03 5 50002 04 50000 05 F1 word 00D1 06 2 word 00DB 07 F12 word 0000 08 word 00D9 09 10 50007 F8 word 00D5 OB F6 word 00D3 4 50009 Tab word 0060 OE word 0000 OF word 0000 10 word F5F4 Alt R Alt L word 00F0 1112 Shift L word 0000 13 word F3F2 14 Ctrl R ctrl L word 0071 15 q word 0031 16 1 0000 17 word 0000 18 word 0000 19 word 007A 1A word 0073 1B 197 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit word word word word word word word word word word word word 0061 0077 0032 F600 0000 0063 0078 0064 0065 0034 0033 F700 1 10 1 IF 21 120 23 24 25 26 27 Win L Win R N Then the next table shows the relationship between ASCII keys and keycodes a more easy to access method Key Codes ey 00 DF yet oil ie 09 Tab E OD Enter 20 Space i 21 N N N 38 N N
54. c m r4 5 lt 5 SIEI s DIES SEs 51 amp P27 CP 11 lt als als lt 0523 lt 0533 lt 0533 m 513 m 211 2 lt 0533 CP26 P10 8513813 215181818 Cos 511511896 511511896 51151181196 511511896 5 511518105 5151318 5151319 6 3 3 alo 8 8 i 82 2183122 8 822 yo C P8 gt 9 5 5 5 CP23 Pins 512x32 512 32 51232 512x32 512x32 51232 512x32 512x32 P22 C P6 CP21 P5 Processor Processor Processor Processor Processor Processor Processor Processor ae ws 05 P20 C P4 CP19 CP18 CP17 P1 CP16 CPO 22 mmn oe om ome ome Pin Inputs E 2 m System Counter 32 Data Bus 18 Address Bus Power Up WSS CLOCK System CVSS ms Reset Delay R Counter 50 ms Brown Out GOEN CLKSEL B192 X 32 RAM B192 X 32 RO RC Oscillator mm 5 Selector Loci Lock Bits 8 PLLENA Clock PLL 1x 2x 4x 8x 16x 16x must be Crystal 64 128 MHz poke Oscillator egister DC 80 MHz OSCENA 4 8 MHz OSCMODE 28 with Clock PLL Hub and Cog Interaction 23 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The Parallax Propeller chip is a low cost mul
55. f8 81 0 r24 0 01 90 e0 r25 0x00 1f 91 17 fe Of 91 pop r16 100 ff 90 pop r15 102 ef 90 pop r14 104 08 95 ret lt SPI_Prop_Send_cmd gt 64 1 Oxdc lt VGA_Color 0x24 gt 0x00 OON lt SPI_Prop_Send_cmd gt 1 Oxf4 lt VGA_Color 0x3c gt get 0 As you can see this particular function is compiled down to a set of functions calls thus mostly pushing parameters on the stack then making the function call with the ASM instruction CALL Hex File Example hex Here are a few lines from a hex file as seen in a hex compatible editor such as Visual C Notepad etc As you can see the data is simply a sequence or stream of bytes that are used to program the FLASH Encoded in the format are addresses starting locations and data so the entire FLASH need not be programmed if the final HEX file is only a few hundred bytes long 100000000C9434000C945A000C945A000C945A002E 100010000C945A000C945A000C945A000C945A00F8 100020000C945A000C945A000C945A000C945A00E8 100030000C945A000C945A000C945A000C945A00D8 100040000C945A000C945A000C94A8130C94E513C9 100050000C941E140C945A000C945A000C945A00E0 100060000C945A000C945A0011241FBECFEFD8E014 10007000DEBFCDBF14BE88E10FB6F8948093600058 10008000109260000 16 1000900002c005900D92A43BB107D9F717E0A4EB7D 1000A000B6E001C01D92A230B107E1F70E945107EE 10008
56. instead of 115 200 baud that we have been communicating at we are going to slow things down to 2400 baud This is to reduce the potential error rate to near zero So your final setup should look something like the dialog shown in Figure 31 4 below 243 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 31 4 Setting up Absolute Telnet for X Modem transfers Connection Properties Appearance Connection Proxy VT Options Transfer Me Global The currently selected tab will be the connection type used The connection type is currently Direct to COM Tenet 8 ssH1 WS ssH2 Dialup Direct to Pot Configure Port Per Second 2400 Parity None Stop Bits 1 Data Bits 8 Enable Bubble Help The settings should be Data Format N81 no parity 8 data bits 1 stop bit Baud Rate 2400 Handshaking None Terminal Mode VT100 doesn t really matter though since we aren t using the terminal Screen Size 80x24 or larger 120x50 is a good choice Local Echo Off Make sure that you have the serial selection switch in the DOWN position on the Chameleon AVR mode Notice the terminal mode VT100 etc doesn t really matter nor does echo really since we aren t going to type anything The PC is going to do the transfer itself in an automated fashion Moving on once you have Absolute Telnet setup then you are going to make the connection t
57. libraries and the Arduino environment here http arduino cc en Reference Libraries Renaming the main Function and setup The Arduino environment builds a final C C program with your source sketch along with a number of other files In fact your program does need a main The Arduino build provides a and inside of it calls a couple functions one as setup the other as the main loop which more or less replaces This is best illustrated with an example below are two complete programs for Hello World One will compile with AVRStudio the other will compile with the Arduino tool AVRStudio Version INCLUDES define __AVR_ATmega328P__ include everything include lt stdint h gt include lt stdio h gt include lt stdlib h gt include lt string h gt include lt ctype h gt include lt avr eeprom h gt include lt avr io h gt include lt avr sleep h gt include lt util delay h gt include lt avr interrupt h gt include lt avr pgmspace h gt include inttypes h include compat twi h gt include lt avr wdt h gt include headers required for demo 20
58. 10 end while end main 227 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit have highlighted the little scanner that looks for the sequence Try typing it in and see if it works Summary This demos shows off how easy it is to access the PS 2 keyboard If you have done work with embedded systems reading a PS 2 keyboard is always a challenge since its such a slow device Thus the best solution is to use interrupts to detect bits sent by the keyboard However this usually means that any other processes that are running on a high speed interrupt will be interrupted which is tricky However with the Propeller doing all the work on a separate processing core reading the keyboard is trivial and requires no processing load at the master s end 30 1 2 Mouse ASCII Paint Demo This demo uses the mouse API to communicate with a local PS 2 mouse plugged into the PS 2 port via the Propeller s mouse Make sure to plug your mouse into the Chameleon and get a good connection This crude ASCII Paint demo allows you to draw with the mouse The right mouse button changes the ASCII drawing character and the left mouse button clears the screen The program displays simultaneously on both the NTSC and VGA displays Figure 30 2 shows the demo in action Figure 30 2 Mouse ASCII Paint demo in action PS 2 Mouse Test ChamPaint Left button to clear screen Right t
59. 11 Palette 2 Color 0 00 1 01 2 10 3 11 The GFX NTSC tile engine is relatively simple as tiles engines go The single driver file contains both Spin and ASM language The driver file name is CHAM_GFX_DRV_001_TB_001 SPIN highly recommend you sit down and read it line by line if you want to understand how it works However it has 2 major parts to it the SPIN message dispatcher and the ASM code graphics driver When the driver is started it loads the ASM code into a Propeller core and that starts drawing graphics on the NTSC screen immediately Then the SPIN code has a lot of functionality to print characters strings numbers and emulation of the crude VT100 like terminal that all the other NTSC and VGA terminal drivers require In addition to the terminal functionality there is a set of virtual registers that are used to communicate with the ASM driver with These registers control everything from the top and bottom overscan tile map pointers fine scrolling etc We will see some of these constants in the following sections when we look at the header files But for now the whole point is that when the GFX driver is started the SPIN code launches the ASM driver it starts immediately drawing the tiles in the 32x24 tile map Then we can make changes to the tile map using the high level terminal functions or the low level graphics functions which is what this section is all about 176 2009 NURVE NETWORKS LLC Explori
60. A0 200 NINE mov 00 tmp reg mov tmp reg BO mov CO n t mov CO tmp reg n t r value 0 value As you can see there is a lot of pontification with syntax If you are 80xxx coder and have used the VC inline assembler or Borland for that matter you should be appalled at the above syntax Hence personally avoid the inline assembler but if you want to write some inline ASM you can However recommend against this since it makes it hard to port Better to simply add an external S ASM file and then put your ASM functions in there and call them from C This way you use straight C and straight ASM and both are easily portable to other compilers and assemblers by other vendors Anyone that has used the GNU GCC inline assemblers knows they would rather poke dull forks in their eyes Figure 1 8 The Parallax Propeller Chip block diagram Cog 0 Cog 1 Cog 2 Cog 3 Cog 4 Cog 5 Cog 6 Cog 7 DDH D D gt gt gt gt Pin Directions D D D D D D Pin Outputs 32432 S CN CN a ESI 15 CP30 P14 Bes E 519115 alal l gll El alal l 8 alal i ell El alal al ell El al eg al ell El CP28 a S c a 7 c m c c r4 g c
61. ASCII art characters The main while loop within the main itself is shown below this is where all the action happens main event loop whi 1 1 read the mouse event if one compute position event x event x 10 event y event y 10 left button hit Clear screen if Cevent buttons 0x01 1 clear the surface NTSC ClearScreen ClearScreen end if right button hit update cursor character if Cevent buttons 0x02 update the cursor character if G cursor gt 32 144 cursor 33 3 end if motion clamping if Cevent x lt 2 event x 2 else if Cevent x 2 event x 2 if Cevent y lt 2 event y 2 else if Cevent y 2 event y 2 update position X event x y event y draw on both screens NTSC SetXY NTSC_Term_Char cursor VGA_SetxY x y 2 VGA_Term_Char cursor slow things down a bit 229 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit _delay_ms 5 end while have highlighted the single call to the mouse read function One thing to note is that the mouse read function takes a pointer to an gid event structure this is a generic structure that can potentially be used for other input devices such as game controllers track balls etc Summary This demo once again shows how easy it is to interface peripherals to the Chameleon with the Pro
62. B0 RLOAD Bi 0 0 Therefore from the D A s perspective with both bits on the circuit looks like that shown in Figure 10 2 for any particular channel or B Noting that the Propeller is a 3 3V device with both channel bits HIGH that means that we have 270 Ohm in parallel with a 560 Ohm and this combination in series with the intrinsic impedance of 75 Ohms of the VGA thus we can do a simple computation to compute the voltage at the 75 Ohm VGA input realizing we have a voltage divider configuration IN RED 3 3V 75 Ohm 270 Ohm 560 Ohm 75 Ohm 0 95V Which is what we desire performing similar math for all 4 combinations of inputs we get the results shown in Table 10 2 for codes Table 10 2 VGA input voltages for all 2 bit inputs B1 BO Code VGA Voltage Description 0 0 0 0 0V Black 0 1 1 0 30V Dark Gray 1 0 2 0 64V Gray 1 1 3 0 95V White Considering there are 4 shades of each channel R G and B that means that there are a total of 4 4 4 z 64 colors available in VGA mode without any tricks Not bad For reference the VGA connector has the following pin out shown in Table 10 3 The VGA port on the Chameleon AVR is a female HD15 High Density which is standard on the back of video card hardware It will connect to any VGA monitor but be careful when making connections it s a special low profile connector and not that sturdy so hold it when you plug the VGA cable into it
63. Bit Figure 15 45 The Arduino Hardware directory amp hardware File Edit Favorites Tools Help amp 2 Search gt Folders Address D development chameleonicham_avrisourcetar EJ Go msn 45 O bootloaders File and Folder Tasks cores libraries Other Places tools boards txt arduino 0017 programmers txt My Documents 3 Shared Documents 5 objects My Computer This is probably one of the most important directories if not the most important directories of the Arduino installation It contains a lot of goodies including two TXT files that describe the boards and programmers being used So this is where you would add new boards and programmers Also there is a directory called BOOTLOADERS this is very important its where all the HEX files for the bootloaders are kept for all the flavors of Arduino If you do happen to erase the Arduino bootloader accidentally or purposely and want to restore it you will go into BOOTLOADERS and pull the 328p bootloader HEX file out and use that to program the AVR chip to restore it However right now we are interested in the LIBRARIES directory This is where all the Arduino libraries are kept Technically both the source C C file and the object files are in this directory This is how the MAKE file for Arduino finds things it scans the LIBRARIES directory and each directory name within i
64. Bit delay 1 250 in milliseconds rate 8 A 2 4 17 in seconds ri 20 Defaults to 10 9 characters per second and a 500ms delay If a command byte byte with high bit set is received instead of an option byte this command is cancelled Enable Keyboard cause the keyboard to clear its output buffer and last typematic key and then respond with an ACK The keyboard then begins scanning Default w Disable resets keyboard to power on condition by clearing the output buffer resetting typematic rate delay resetting last typematic key and setting default key types The keyboard responds with an ACK and waits for the next instruction Set Default resets to power on condition by clearing the output buffer resetting typematic rate delay and last typematic key and sets default key types The keyboard responds with an ACK and continues scanning PS 2 Set All Keys to Typematic keyboard responds by sending an ACK clearing its output buffer and setting the key type to Typematic Scanning continues if scanning was enabled This command may be sent while using any Scan Code Set but only has effect when Scan Code Set 3 is in use PS 2 Set All Keys to Make Break keyboard responds by sending an ACK clearing its output buffer and setting the key type to Make Break Scanning continues if scanning was enabled This command may be sent while using any Scan Code Set but only has effect when Scan Code Set 3 is in use PS 2 Set
65. C C code along side This way you can see how the compiler works and what it s doing in various situations This is one of the best ways to learn optimization am always shocked at how many programmers know nothing about this tool So don t be another statistic Hex File This is embedded system specific and contains the final AVR compatible binary hex file that the programmer tool needs to FLASH the AVR s memory In 99 of the cases we want to generate this file so we can program the AVR with our code Since these files are so important and understanding what s in them is equally important let s take a quick peek at each explored my latest compile and extracted some bits of each file so you can see what s in them Map File Example map The MAP file is typically rather large and has all kinds of interesting information By reading it you will see all the details and get a real respect for what goes on behind the scenes of a linker loader Here s a small excerpt of one section of a MAP file Allocating common symbols Common symbol size file g uart buffer tx 0x20 CHAM AVR UART DRV V010 0 g uart buffer rx 0x20 CHAM AVR UART DRV V010 0 Memory Configuration Name Origin Length Attributes text 0x00000000 0x00020000 xr data 0x00800060 0x0000ffa0 rw x eeprom 0x00810000 0x00010000 rw x fuse 0x00820000 0x00000400 rw x lock 0x00830000 0x00000400 rw x signature 0x00840000 0x00000400 rw x de
66. Chameleon AVR socket Table 12 3 lists the signals for reference the descriptions of the signals are as follows DATA Bi directional and used to send and receive data CLOCK Bi directional however the keyboard nearly always controls it The host can pull the CLOCK line LOW though to inhibit transmissions additionally during host gt keyboard communications the CLOCK line is used as a request to send line of sorts to initiate the host gt keyboard transmission This is used when commands or setting need to be sent to the keyboard VCC GND Power for the keyboard or mouse Specifications state no more than 100mA will be drawn but wouldn t count on it and plan for 200mA for feature rich keyboards with lots of lights etc When both the keyboard and the host are inactive the CLOCK and DATA lines should be HIGH inactive Table 12 3 Pin out of PS 2 6 Pin Mini Din Pin Function DATA bi directional open collector NC GROUND VCC 5 100 mA CLOCK NC 12 1 1 Communication Protocol from Keyboard to Host When a key is pressed on the keyboard the keyboard logic sends the make scan code to the host computer The scan code data it is clocked out by the keyboard in an 11 bit packet the packet is shown in Figure 12 3 The packet consists of a single LOW start bit 35 us followed by 8 data bits 70us each a parity bit and finally a HIGH stop bit Data should 55 2009 NURVE NETWORKS LLC Exploring the Chameleo
67. Controls Required None Technical Overview The demo simply uses both the NTSC and VGA terminal API functions to print Hello World on both screens and scroll Here s just the main loop excerpt since this demo is nothing more than a copy of the NTSC and VGA versions respectively and merged int main void run over and over again initialize and set SPI rate SPI Init SPI DEFAULT RATE clear screens NTSC Clearscreen ClearScreen enter infinite loop while l1 print on NTSC terminal screen NTSC_Color 0 NTSC Term Print Hello world MOS print on VGA terminal screen VGA Color 0 Term Print Hello world TE slow things down a bit so we can read the text delay ms 10 end while end main The demo simply uses the same basic commands but send them to both the NTSC and VGA monitors Summary This demo shows how easy it is to get both NTSC and VGA terminal like text output going on the Chameleon 28 1 6 VGA Star Field Demo The default2 VGA driver isn t as impressive as the NTSC driver In fact its pretty boring Its good for displaying text and acting as a terminal output but that s about it However with a little ingenuity we can make it do some cool things This little demo draw stars on the VGA screen on the last display line this causes the screen to scroll and presto animated star field Then on top of the star field a little characte
68. DC component will be blocked In other words say that the input was a sine wave or square or square wave with a peak to peak voltage of 1V but it was riding on a 2V signal this would look like Figure 14 2 top graph in blue However after going thru the AC coupling capacitor the signal would look like that shown in Figure 14 2 bottom graph in red So all C15 does is block the DC Now let s talk about the some more hardware related concepts about making sounds with a couple specific techniques used for many of the Propeller audio drivers Of course you don t need to know this material since you are simply going to use a driver someone else writes like the default drivers we provide however it can t hurt to have an understanding of how the sounds are generated typically by these drivers 14 1 1 Pulse Code Modulation PCM The most common method to make sound on a game console is to use PCM or Pulse Code Modulation This is really nothing more than storing a series of samples of the sound in some resolution 4 8 12 16 bit along at some playback rate A WAVE file for example is PCM data you simply output the data at the proper rate to a D A converter with an amplifier 67 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit connected to a speaker and you will hear the sound There are a number of issues with this first it takes huge amounts of memory even with compression secondly you need a D A digital to analog converte
69. DC2 PCINT10 PCINTO CLKO ICP1 PCINT1 OC1A PCINT2 SS OC1B PCINT3 OC2A MOSI 4 PC1 ADC1 PCINT9 PCO ADCO PCINT8 SCK PCINTS PCINT14 RESET PC6 PCINT16 RXD PDO PCINT17 TXD PD1 PCINT18 INTO PD2 PCINT19 OC2B INT1 PD3 PCINT20 XCK TO PD4 GND PCINT6 XTAL1 TOSC1 PB6 PCINT7 XTAL2 TOSC2 PB7 PCINT21 OCOB T1 PD5 PCINT22 OCOA AINO PD6 PCINT23 AIN1 PD7 PCINTO CLKO ICP1 PBO 1 2 3 4 5 6 7 8 PC5 ADCS SCL PCINT13 PC4 ADC4 SDA PCINT12 ADC3 PCINT11 PC2 ADC2 PCINT10 PC1 ADC1 PCINT9 PCO ADCO PCINTS8 GND AREF AVCC 5 PB4 MISO PCINT4 MOSI OC2A PCINT3 PB2 SS OC1B PCINT2 PB1 OC1A PCINT1 18 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 1 5 The Atmel Mega AVR 328P architecture block diagram a o z o gt A Watchdog Power debugWIRE Timer Supervision BOD amp RESET LOGIC 1 1 1 1 1 1 1 1 Oscillator Circuits l Clock Generation 1 1 1 1 1 1 EEPROM 8bit T C 0 8bit T C 2 AVCC AREF GND DATABUS RESET XTAL 1 2 PD O 7 PB 0 7 PC 0 6 ADC 6 7 1 3 The Atmel Mega AVR328P Chip The Atmel AVR 328P P stands for Pico Power comes in a number of packages including 28 pin DIP duel inline package We are using the Mega AVR 328P D
70. Direct connection via USB serial Pee ec Arduino bootloader allows serial protocal to program AVR328P chip 105 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit As you can see the Arduino setup is very similar to the AVRStudio setup except that the Arduino tool along with the bootloader allows us to program the AVR without the external programmer which is very convenient The only downside is you must use the Arduino tool IDE and setup This isn t too bad but if you are a serious programmer you will immediately feel limited by the over simplified Arduino programming tool and its limitations But if you are a newbie then you will probably really like the Arduino tool since it insulates you from the complexities of what s really going on Referring to Figure 15 41 here s what s going on First there is a JAVA application that acts as the IDE for the Arduino hardware or compatible like the Chameleon This JAVA application is nothing more than a GIU it has very little functionality just enough for a crude text edit and a couple menus But the reason its in JAVA is that it will work on Windows Linux and Mac OS X that s why they decided to use JAVA Additionally the application has the exact same look and feel on each machine since it always uses the JAVA gui elements library which is nice Movi
71. Exploring the Chameleon AVR 8 Bit Figure 15 64 The final Propeller tool installation dialog B The Propeller Tool v1 05 5 Installer X se PROPELLER by Parallax Inc Propeller Tool v1 05 5 Installation Completed The Propeller Tool 1 05 5 has been successfully installed Click 5 At this point the Propeller tool should be installed and ready to go Let s test it out 15 3 1 Launching the Propeller Tool The Propeller tool communicates to the Propeller chip over a single 2 line serial connection with the standard RS 232 TX RX pair along with DTR data terminal ready as a reset line The Chameleon s USB serial port is used for the communications channel for the Propeller chip However if you recall the USB serial port can be used by the AVR or the Propeller The device that gets connected to the port is controlled by the serial selection switch next to the RESET button Simply place the switch in the UPPER position to select the Propeller chip to have access to the USB serial port This is shown in Figure 15 65 below Figure 15 65 Placing the Chameleon into Propeller serial mode 4 lt n m ee ia A er SP ae INO REE Power On left 124 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit You already installed the Propell
72. FF tile numbytes parm We will see how to call all these in the API section below but the point is want you to see the big picture and see how all this stuff works not so much so you can use it but so that you might use this template model or pattern to create better faster drivers In any event when a message is sent with GPU GFX SUBFUNC STATUS W then we assume that a GPU command is being issued and the first data byte of the SPI message is used as the sub function ID lower 8 bits and the upper 8 bits or second byte is used as the operand or data Now the GPU functions are too complex to request in a single SPI message so we have to set them up Thus we have to initialize pointers to the source destination and length of bytes or words to process then we call the GPU command to actually do the work For example the sub function GPU GFX SUBFUNC FILLMEMT16 requires a pointer to the destination and the number of WORDS to write along with data WORD So how do we set all those Easy we use other GFX messages to set the destination address pointer data WORD and number of bytes for operation then the GPU sub function uses those data for the operation Simple At this point you should have a good idea of how the enhanced NTSC tile engine works and the entire communication paths from the AVR PIC to the Propeller driver itself So let s move onto the itself default baud rate define UART DEFAULT BAUDRATE 1
73. NETWORKS LLC Exploring the Chameleon AVR 8 Bit 28 1 5 Dual NTSC VGA Printing Demo One of the cool things about the NTSC and VGA terminal tile drivers is they have the exact same base features Which means that porting your code to work on NTSC or VGA is usually a matter of changing API prefix function names with from NTSC to VGA and vice versa Of course the advanced gaming tile engine support is only for the NTSC driver however no one is stopping you from using or making a more advanced VGA drivers on the Propeller simply choose not to this time around In any case this demo is just a Hello World demo that prints both on the NTSC and VGA monitors at the same time to show you how easy this is Figure 28 5 shows the demo in action Figure 28 5 Dual NTSC VGA terminal printing demo llo 1 Hello World World Hello World World Hello World rid Hello World Hello World Hello World Hello Worl Hello World Hello 1 6750 ron ar 0 T 2750 0750 O 0 1 0 O 0 Ll eb EDI LL mh emo wf 6750 Lo O mA O 0750 oO 2750 1 0 m0 AB7Z0 I LIE O wO UI 6 0 Ld G7 DOME O 9 Ld 07rz0 I ello World Hello World lo World Hello World World Hello World Hello World Hell
74. Now the algorithm is fairly simple we need to index thru the sine table a rate such that we complete a single cycle of our sine wave at the desired output signal frequency As a quick and dirty example let s say that we use a PWM frequency of 256 KHz and we want to play a 1 KHz sine wave then this means that each second there are 256 000 PWM pulses we want to index into our table and play 1000 iterations of our data which has a length of 256 entries thus we need to index into our table at a rate of 256 000 1000 256 1 Interesting so every cycle we simple increment a counter into the sine table and output the appropriate duty cycle in the table lookup This is shown in Figure 14 6 As another example say we want to synthesis a 240 Hz signal then let s see what we would need 256 000 240 256 z 4 16 In this case we would increment a counter until it reached 4 then we would increment our index into our sine table But this example as well as the last should bring something to your attention there is a max frequency we can synthesis and our signal synthesis is going to be inaccurate for anything but integral divisors so that s an issue we need to address in a moment First let s look at the maximum signal frequency if you want to play back all 256 sine samples then the maximum signal frequency is always 71 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Maximum Synthesis Frequency PWM frequency
75. PAL VGA graphics plays sounds reads mice and keyboards and more However to really explore the power of the Chameleon you will definitely want to play with the Propeller chip and modify its kernel driver s and so forth This is actually quite easy to do with a single tool that interfaces to the Chameleon AVR over the USB port Its called the Propeller IDE and Figure 1 10 below shows a screen shot of it Figure 1 10 The Propeller IDE in action Propeller Tool cham default2 drv 111 cham default2 drv 111 cham default2 111 Text 010 FulSouce 7 Condensed Summary Documentation x VGA 010 7 7 1 keyboard 010 2t mouse 010 3 cham default 111 spin Object Info NS sound div 052 11khz 6bit 4 AUTHOR Andre LaMothe CHAM GFX DRV 001 TB 001 5 LAST MODIFIED 8 19 09 E cham defautt2 111 6 VERSION 1 11 VGA Test 010 vea 010 8 COMMENTS This is the Chameleon generic driver Default 2 9 good example of interfacing to multiple drivers on the Prop mouse 010 10 my HEL tile engine to augment the graphics on the NTSC scre NS sound drv 052 llkhz 1 amp bit 11 this driver is the same as the Defaultl driver This driv 0 CHAM GFX DRV 001 TB 001 12 commands that work on the NTSC Default driver work here Th 3 uou should use the higher performance Default2 version
76. Prop driver s LED blink sequence in the driver or speed it up but commands that are sent before the Prop driver is done booting will be ignored therefore if you have a lot of set up work to do then you don t require a delay but if you jump right into commands then you need a good 1 5 2 second delay _delay_ms 2500 clear screens ClearScreen enter infinite loop 1 1 draw next star set color Color 0 position star at bottom to cause scroll VGA_SetxY rand 32 14 Term Print draw our little ship at set color to green with a little forcefield Color 4 position at top of screen and draw with ASCII art VGA_SetxY ship x ship y 221 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Term Print add some logic here to move the ship slow things down a bit _delay_ms 10 end while end main This demo should bring back memories of BASIC programming on your C64 Atari 800 Apple if you ever did any text only games and had to resort to things like lt gt as your space ship Summary This demo shows that with a little creativity even the vanilla VGA terminal driver can be used for games 29 1 Sound Demos The following sound demo s illustrate how to make calls to the sound driver on the Chameleon running on the Propeller o
77. RING RCA AUDIO Referring to the circuit we see that the signal AUDIO P24 pin 31 on the Propeller is an input into the network This signal is passed thru a low pass filter consisting of a resistor R14 1K ohm and a capacitor C15 0 1uF Note these reference designators may change in the future but the point is there is an R C network here Moving 65 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit on there is also another AC coupling capacitor C14 10uF to the final RCA output The circuit has two sections and they each serve different purposes Refer to Figure 14 1 for the following explanation The signal Vin t comes in at the port and the ow pass filter made up of R14 and C15 pass low frequencies but block high frequencies This is what s called a single pole RC filter The gain of the filter or the transfer function describes the relationship between the output and the input signal thus a signal with a gain of 1 at the output call it Vout t would be equal to the input with some possible phase variance but this is irrelevant for our discussion The single pole RC filter acts like a voltage divider but we have to use more complex math to describe it based on imaginary numbers and or differential equations This is a tough but there is a trick based on the Laplace Transform which transforms differential equations into algebraic equations called the S Domain then we can work with the ci
78. SO HOLDn SPI_SS2n SPI_SS3n gt SPI_SCK lt T gt sP 74 138 VCC 5VCC The Chameleon uses SPI serial peripheral interface communications as the electrical communications interface to the Propeller chip as well as the on board 1MB FLASH memory The idea was we wanted to interface the AVR with both the Propeller and the FLASH The Propeller has no communications peripherals so we could use anything we wanted 2 lines 4 lines etc and any kind of protocol we wished However since the FLASH memory was SPI and there are 1000 s of SPI devices out there we decided to create a virtual SPI interface driver for the Propeller and let it act as a SPI slave device With this design decision then we can communication with the Propeller FLASH and any other external SPI devices all with the AVR s built in hardware very fast and we have a nice clean communications bus for everything The only challenge was supporting enough SPI devices so the design uses a couple AVR I O pins as chip selects for a multiplexer Referring to Figure 2 10 the idea is you place a 2 bit code on a pair of I O pins AIN2 AIN3 which are fed into a 74138 decoder this gives us 4 active low chip select signals SPI SSOn SPI SS3n which we can export out to 4 SPI devices on the bus Referring to the schematic SPI SS3n chip selects the FLASH And if you look back a page or two at the Propeller schematic on the left hand side locate the SPI signals you will see
79. Scaling 2 1 E7 command If 2 1 scaling is enabled the mouse applies the following mapping as shown in Table 12 5 the counters before sending their contents to the host in the data packet Table 12 5 Mouse scaling reported data mapping when in 2 1 mode Actual Movement Reported delta Movement BEER MENU So the scaling operation only takes affect when the actual movement delta is greater than 1 and for delta 5 the reported movement is always delta 2 Now let s look at the actual data packet format for the mouse state 12 2 2 Mouse Data Packets The PS 2 mouse sends the movement information to the host which includes the position counters button state overflow flags and sign bits in the format show in Table 12 6 59 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 12 6 Mouse data packet format Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Byte 1 Y overflow bit X overflow bit Y sign bit X sign bit Always 1 Middle Button Right Button Left Button Byte 2 X Movement delta Byte 3 Y Movement delta The movement counters are 9 bit 2 s complement integers since the serial protocol only supports 8 bits at a time the upper most sign bit for each 9 bit integer is stored in Byte 1 of the overall movement packet Bit 4 holds the 9 bit of the X movement and Bit 5 holds the 9 bit of the Y movement Typically you don t need to worry about the 9 bits since that would be a lot of motion i
80. Sync Interface Composite signals are the most commonly used analog video interface for NTSC PAL Composite video is also referred to as CVBS which stands for color video blanking and sync or composite video baseband signal It combines the brightness information luma the color information chroma and the synchronizing signals on just one cable The connector is typically an RCA jack This is the same connector as that used for standard line level audio connections S video of course is slightly cleaner since the analog mixing of chroma and luma does NOT take place A typical waveform of an all white NTSC composite video signal is shown in Figure 11 5 a 47 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 11 5 a NTSC composite video waveform White Level 100 IRE Active Video 52 6 us Black Level Setup 7 5 IRE Blanking Level 0 IRE Color Burst 40 IRE p p Syne Tip 8 10 cycles 3 58Mhz Front Porch Color Burst Back Porch 1 5us 2 5us 1 6us Sync Tip 4 7 us Breezeway 0 6us This figure depicts the portion of the signal that represents one horizontal scan line Each line is made up of the active video portion and the horizontal blanking portion The active video portion contains the picture brightness luma and color chroma information The brightness information is the instantaneous amplitude at any point in time The unit of measure for the amplitude
81. Term Print Port Data ON NTSC Term Char OxOD turn on the LED pin 7 HIGH pin 6 LOW repeat pattern down port PropPort write 0b10101010 slow things down a bit so we can read the text delay ms 250 print on NTSC terminal screen NTSC Term Print Port Data OFF NTSC Term Char OxOD turn off the LED pin 7 LOW pin 6 HIGH repeat pattern down port PropPort write 0b01010101 slow things down a bit so we can read the text delay ms 250 end while end main 232 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit have highlighted the port I O commands The program starts by setting the direction bits to all 1 s which mean output Then the program immediately enters into the main loop and starts toggling the I O pins on a 500ms total cycle The output is mimicked to the NTSC screen you can add VGA support yourself with a few lines of code Just don t forget to add the library and header files to your program Now once thing you might wonder is how fast I control these pins This is a good question since you might want to do something like talk to a SPI or I2C device So the real bottleneck is the SPI interface from the AVR PIC chip to the Propeller we can only send commands and thus toggle the I O pins as fast as this interface Thus if you want to do something more complex then suggest that you add commands
82. There is a library for the Arduino called Processing which allows you to use Processing language like commands and functions Bottom line the Arduino is programmed nothing more The Arduino guys have simply created libraries so the system feels like the Processing language which you can read about here http processing org 15 2 1 Installing the Arduino Toolchain in Windows There isn t really an installer for the Arduino tool you more or less just copy the files unzip untar etc the Arduino files into a directory on your hard drive and that s it With Windows Linux and Mac OS there are some slight differences but more or less its all the same We will concentrate on the Windows version here the Linux and Mac installs are nearly identical and you can read about them on the Arduino site itself However the adjustments we make the installation directories are not on the Arduino site thus read this section no matter what even if you are not installing on Windows The first step is to download the latest version of the Arduino development package for Windows The latest files at the printing of the manual are located on the DVD here DVD ROM CHAM_AVR TOOLS ARDUINO WINDOWS arduino 0017 zip 106 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit There are also directories for Linux and Mac which have their respective files But before copying the above file to your desk want you to
83. VGA SVGA XGA also differ substantially with the primary difference in the scan frequencies and resolutions These differences do not cause as much concern because most computer equipment is now designed to handle variable scan rates multisync monitors are now the de facto standard This compatibility is a major advantage for computer formats in that media and content can be interchanged on a global basis Table 11 2 lists some of the more popular formats along with comparisons of their specifications Table 11 2 Typical Frequencies for Common TV and Computer Video Formats High Definition Video Extended Standard Definition Graphics Graphics Digital Television Format Array PC Array PC Television Format Television Format Description for North America for Most of Europe and Japan and South America Vertical Resolution Approx 480 525 Approx 575 625 1080 or 720 or 480 penat total lines total lines 18 different formats ES 76S lines per frame Horizontal Determined by Determined by poe bandwidth ranges bandwidth ranges 640 1024 line per from 320 to 650 from 320 to 720 REN 15 734 15 625 33 75 45 31 5 60 kHz Vertical Frame Rate Hz 29 97 25 30 60 60 80 60 80 aghe 4 2 5 5 25 15 3 40 7 Frequency MHz Of course not listed in the table are HDMI video modes These are whole other ballgame but are very similar to XGA modes and higher 11 2 3 Composite Color Video Blanking
84. WinAVR 20080610 Setup Wok Welcome to the WinAVR 20080610 Setup Wizard This wizard will quide you through the installation of WinAVR 20080610 It is recommended that you close all other applications before starting Setup This will make it possible to update relevant system files without having to reboot your computer Click Next to continue Cancel Click lt Next gt and the famous GNU GPL license agreement should display on your screen Read it and then click lt Agree gt to continue as shown in Figure 15 13 below Figure 15 13 WinAVR s GPL license WinAVR 20080610 Setup uo License Agreement Please review the license terms before installing WinAVR 20080610 2 Press Down to see the rest of the agreement WinAVR Licensing Information GNU Binutils is distributed under the GNU GPL License GNU Compiler Collection GCC is distributed under the GNU GPL License avr libc is distributed under a BSD License avrdude is distributed under the GNU GPL License avrdude qui is distributed under the GNU GPL License GNU Debugger GDB is distributed under the GNU GPL License Insight is distributed under the GNU GPL License SimulAVR is distributed under the GNU GPL License If you accept the terms of the agreement click I Agree to continue You must accept the agreement to install WinAVR 20080610 83 2009 NURVE NETWORKS LLC Exploring the C
85. all input and read the port PropPort SetDir 0x00 inputs PropPort_Read Function Prototype int PropPort_Write int data8 Description PropPort_Write writes data8 to the port I Os that are set as inputs ignore the bits in those positions Returns 1 Example s Write the binary patterns for 0 255 on the port at 10 millisecond intervals PropPort SetDir OxFF for data 0 data lt 255 data PropPort write data delay ms 10 end for data 204 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 27 0 Chameleon Hands On Programming Tutorials and Demos Either you spent the past couple days reading up to this section or you cheated and skipped here No matter how you got here finally it s time to see some actual code and the Chameleon AVR 8 bit in action First some ground rules Every tutorial was designed to show off some aspect of the Chameleon AVR s hardware or a particular library Tutorials are not designed to be mind blowing or amazing they are designed to show you how to use each system and are very simple to get you started Chameleon s AVR s API is far from bug free There are probably lots of little bugs that haven t found so beware However the APIs don t really do much but send messages to the objects running on the Propeller chip so ultimately if something doesn t work its probably the driver Each tutorial
86. and messages to control the Propeller s onboard counters then you can route them to the I O pins and generate any signal you want via control from the master AVR PIC chip Summary This demos shows off a really simple way to control some of the I O pins of the Propeller chip Also the code is so simple there is no processing core for it on the Propeller it runs right on the main message dispatcher loop and just does the pin I O on demand Something you should try is hooking up a SPI 12C or other device to the port and see if you can remotely control it all the way from the AVR PIC chip 31 1 2 Serial RS 232 Communications Demo This demo shows off the serial communications of the Chameleon There are three components to this hardware UART in the AVR 328P FTDI USB to Serial UART converter software driver running on the AVR Considering these three elements to get serial from the PC s USB port to the Chameleon first we need the FTDI USB to serial UART which we have been using Secondly to communicate with the AVR we need to use its internal UART the 328P has only a single UART by the way And finally we need to write software to control the AVR s UART and set it up This is what the CHAM AVR UART DRV 010 library module is for Although we have been using the USB to serial connection to the Chameleon we don t have to use the USB port the serial TX RX pins from the AVR are exported to the expa
87. are nearly identical the Arduino version has simply been converted into an Arduino Sketch Of course the demo needs many other driver and system files to link with but we will get to this latter when we discuss the installation of AVR Studio WinAVR Arduino and the tool chain in general for C C and ASM programming The demo took about a week to develop and was written by one of our Demo coder s JT Cook to see what he could do wit the Chameleon in a week and rely 100 on our drivers The results are pretty amazing and the cool thing is the game literally was ported to the PIC version in a matter of minutes So as an extra bonus by leveraging the Propeller to do all media processing the AVR PIC processor running the applications or games is usually in pure C C and since the interface APIs to the Propeller are the same you get the exact same experience when you port an applications from the Chameleon AVR to PIC and vice versa Of course the PIC version is faster and has more memory but use AVR users like it that way a challenge Hit the Reset button over and over and the demo will reset and reload immediately If the system ever locks up rare and always due to bad code then simply hit Reset a few times or cycle the power Playing Crate It Crate it is your standard block pushing game where you want to get the objects blocks from one side of the screen to resting positions on the other side The problem is that if a block hits u
88. bit operands set status to O If you recall SPI is a circular buffer system so each byte we send out we receive a byte back thus when you call this function 3 bytes are sent 3 bytes are received Currently the function returns 16 bit value representing the first two returned bytes the 39 byte is used internally for now Also since this is such an important function let s take a look at the source for it this function waits for any previous command to complete and then initiates a new command long SPI Prop Send cmd int cmd int data int status wait for previous command to complere while SPI_Prop_Send_Cmd2 CMD_NULL 0 0 amp 0x00ff0000 initiate the new command return SPI Prop Send cmd2 cmd data status amp 0x0000ffff end SPI Prop Send cmd As you can see the SPI Prop Sen function waits on a flag while calling a hidden function that actually does the work Let s talk about that for a moment In multiprocessor systems when once processor requests another processor to do something the whole point of multiprocessors is that the originating processor can continue to do more work in parallel Thus we need code to consider this such that say processor A the AVR sends a command to the processor B the Propeller Now processor A goes about its business while processor B executes the command But the processor A finishes something and then requests processor B to do something else
89. code void foo2 1 code DLL Library RPCs are a little different than using DLLs or libraries since they are passive entities that are loaded on demand RPCs are more like making calls to another running program and using its resources Subroutines Thus there is a client server relationship here and you can think of the RPC call as message passing as shown in Figure 16 4 There are various forms of the technology and it s more of a concept methodology than a specific algorithm For example in some RPC setups the RPC call mimics the actual binary foot print of the function call Assuming the C C programming language here s a solid example float DotProduct float ux float uy float uz float vx float vy float vz Looking at this function depending on the compiler directives the parameters are passed by value on the stack right to left so there are 6 floats each 4 bytes let s assume Also there is a return value another 4 byte float thus we need to pack the parameters up into a single record and pass it along and then wait for a single float 4 byte result 133 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit So we might do something like this to pack the parameters up into a contiguous memory space this is used as transport buffer for RPC calls CHAR RPC input buff 256 now pack the parms into the array one at a time memcpy input buff 4 Qux sizeof fl
90. compute its lenght but only the first buffer size number of bytes will be written to the file buffer function returns the length of the file in bytes This is a receiver oriented protocal so when you want to receive a file from the PC start the transmission on the PC end FIRST THEN run your xmodem download on this side The PC will wait a min or 2 before timing out but this funtion will immediately start sending NAKs and expect the sender to respond I leave it to you to make this function more robust I wrote it in about an hour note debug information only prints to NTSC currently xmodem protocal defines state machine define XSTATE INIT define XSTATE SEND NAK define XSTATE RECEIVE PACKET define XSTATE SEND ACK define XSTATE EOT control characters used in xmodem protocal define CHR_SOH 1 define CHR_EOT 4 define CHR_ACK 6 define CHR_NAK 21 define CHR_CAN 24 define CHR_CTRLZ 26 control debug output to NTSC screen this is handy if you try to add more features to the function define DEBUG_XMODEM 1 0 no output at all 1 display file data and file size 2 display everything int xstate xstate_running xbytes_read 0 ch index unsigned char xchecksum xchecksum_computed xpacketnum xpacketnumn start off in initialization state xstate XSTATE_INIT xstate_running 1 main loop whi le xstate_running 240 2009 NURVE N
91. demo follows the same outline the demo will be introduced a screen shot if applicable compilation instructions for both the Arduino mode of operation and straight AVRStudio Finally the tutorials are organized in order of various sub systems like keyboard sound graphics etc And each demo might have a couple versions with different video drivers and or VGA NTSC support will tend to review only one version of the demo since the others are usually variants However compilation files for each demo version will be included After experimenting with all the tutorial demos you will have a command of all the sub systems of the Chameleon AVR 8 bit as well as be able to use the provided APIs to get things done Then suggest you start with the demos as templates to get your own programs up and running before trying to do things from scratch To compile and run any of the tutorial demos you will need to have one of two things setup 1 An AVRStudio project open and ready to go along with an AVRISP MKII programmer to directly download to the Chameleon s AVR programming port 2 An Arduino Sketch project along with the Arduino bootloader previously FLASHED into the AVR 328P processor this is how the Chameleon AVR ships In a nutshell if you just got your Chameleon AVR it comes pre FLASHED with a the Arduino bootloader and you can use method 2 to run all the experiments If on the other hand you prefer a more robust tool like the Atmel A
92. don t have to send SPI messages yourself For sound we decided to re use a driver from the HYDRA development that was designed for both PWM and PCM samples with multiple channels The same sound driver is used in both Default and Default2 so the same idea apply to either driver you load on the Propeller CHAM DEFAULT1 DRV 112 SPIN or CHAM DEFAULT2 DRV 112 SPIN The actual driver object used for sound is NS sound 052 11khz 16bit spin This is an 11Khz 16bit sound driver with 9 independent audio channels It s pretty cool However only exposed a portion of its abilities thru the current SPI messages since sound is something that you will probably want either a little or a lot no need to waste messages You can always add more Therefore the abilities you see exposed in the following API are just a taste of what it can do For example to save commands mashed sound commands into a single SPI packet so you only can control 4 channels with limited frequency and control In other words if you need more than simple 4 channel sound then you will have to add messages to the SPI driver and add them yourself 194 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit With that in mind if you want to use the sound driver then you need the following files added to your project CHAM AVR SOUND DRV_V010 c C file source for Sound module CHAM AVR SOUND DRV_V010 h Header file for Sound modul
93. entire screen and moves cursor to upper left on MS DOS ANSI SYS CSI n K EL Erases part of the line If n is zero or missing clear from cursor to the end of the line If n is one clear from cursor to beginning of the line If n is two clear entire line Cursor position does not change CSInS Scroll whole page up by n default 1 lines New lines are added at the bottom not ANSI SYS CSInT Scroll whole page down by n default 1 lines New lines are added at the top not ANSI SYS Moves the cursor to row n column m Both default to 1 if omitted Same as CUP CSI n k m SGR Sets SGR Select Graphic Rendition parameters After CSI can be zero or more parameters separated with With no parameters CSI m is treated as CSI 0 m reset normal which is typical of most of the ANSI codes CSI 6n DSR Reports the cursor position to the application as as though typed at the keyboard ESC n mR where n is the row and m is the column May not work on MS DOS Saves the cursor position Restores the cursor position EM EM Color Table for Select Graphics Rendition SGR Commands Intensity O 1 2 3 4 5 6 7 9 Normal KR ETT OWA White reset Bright Yellow Magenta Cyan Write 266 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit SGR Select Graphic Rendition Parameters Code Effect Note 0 Reset Normal all attributes off 1 Intensity Bold 2 Intensity Faint
94. fairly involved and take a little bit of numerical analysis but once you get it working its not an issue and you can build libraries to create any sound you wish in fact many advanced synthesizers use PWM systems so it s very powerful To start with you might want to Google for PWM techniques and read up a bit Watch out since most PWM references are about using PWM for motor control Here are a few PWM articles to get your started http www freescale com files 32bit doc app note MC68EZ328PWM pdf http www freescale com files 32bit doc app note MC68EZ328DTMF pdf http www intel com design mcs96 technote 3351 htm http ww1 microchip com downloads en AppNotes 00655a pdf http archive chipcenter com knowledge_centers embedded todays_feature showArticle jhtml articlelD 10100668 68 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 14 4 Duty cycle modes Standard PWM 50 Duty Cycle Cycle 0 Cycle 1 O us 2us 5us 1 0us 1 5us 2 045 t Time ys 1 MHz Clock Average 0 2 5V 1V Time Slice 0 1 2 3 4 5 6 7 9 50 Duty Cycle 4 045 i 2 3 4 5 6 7 8 910 Time us 10 Mhz Clock Average 50 0 2 5V 0 5V over 10 clocks 1000ns After reading all these documents you should have a fairly good grasp of PWM techniques More or less PWM is really a method of digital to analog conversion using a single bit output along with a low pass filter that acts as an averagi
95. figure the NTSC signal is on Pin 12 13 14 VGA is on pins 16 23 audio is on pin 10 the PS 2 keyboard mouse is connected to pins 26 27 and finally the serial is on pins 30 31 Basically this is a standard Propeller Board Rev C D pin map 128 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 16 1 shows the pin map in more detail Table 16 1 The I O pin map for the connections to media devices device Propeller Port Pins Used NTSC video 12 13 14 video LSB to MSB VGA video 16 V 17 H 18 B1 19 B0 20 G1 21 G0 22 R1 23 RO PS 2 Keyboard 26 data 27 clock 10 PWM or pure signal 30 TX 31 RX Figure 16 2 The SPI link between the AVR and Propeller chip Client processor anything with a SPI interface AVR PIC Propeller Cog i Processor Virtual SPI Driver wee ee MISO SPI Bus 25MHz 991 Common Ground The MCP cham default2 drv 112 spin is the primary driver that runs on the Propeller chip and listens to SPI traffic over the SPI link from the AVR chip as shown in Figure 16 2 As the virtual SPI interface running on its own core receives packets messages commands from the AVR the messages are parsed and packaged and placed into a global shared memory region The MCP is listening to the global shared region and tracks a flag Once this flag is noted to change the MCP reads the packet in and then
96. from then encodes the tile in 2 bit pixels where each 2 bit pixel value represents one of four colors from the tile palette to use Thus each tile has its own palette of 4 colors Also you may notice the funny 9696 character sequence this is how SPIN indicates binary representation but 969e means to use 2 bit encoding to simplify your typing thus instead of writing 00s 01 5 105 115 we can write 1 2 3 4 which is convenient Summing up each tile is a 8x8 pixels Each pixel is 2 bits therefore each tile bitmap row is a single 16 bit WORD and there are 8 WORDs that make up a tile Each 2 bit pixel represents 1 of 4 colors from the palette that is indexed from the tile entry s high byte So each tile has its own palette The tile engine is very optimized and thus needs the tile bitmaps in a specific format That is reversed So the 2 bit pixels are reversed when output that is the bitmaps you enter must be mirrored so that when displayed they are correct Normally bitmaps in tile engines might be left to right as they are on the screen but in this case the left most pixels will display on the right etc So keep that in mind when making your own tiles The tile bitmaps themselves are defined by the declaration bitmaps in the driver and you can change the pointer to them with the global tile bitmaps base ptr parm in the register interface However this is rare unless you want to point the tile bitmaps base ptr parm to anot
97. int GFX_Set_Tilemap_Width int width Sets the width of the tilemap in encoded format Top and bottom overscan control functions int GFX Get Bottom Overscan Color void Retrieves the bottom overscan color int GFX Get Top Overscan Color void Retrieves the top overscan color 185 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit int GFX_Set_Bottom_Overscan_Color int col Sets the bottom overscan color int GFX Set Top Overscan Color int col Sets the top overscan color The following lists each function a description comments and example usage of the function Function Prototype int GFX GPU Fill Mem16 unsigned int dest ptr unsigned int value unsigned int num bytes Description GFX GPU Fill 6 copies a number of bytes from source to destination in the GPU memory space in WORD side chunks or in other words in the Prop s local memory of 32K you can use this to overwrite SPIN code so watch out The parameters are the destination address of the fill dest ptr the 16 bit data value and finally the number of bytes always a multiple of 2 num bytes Typically you will use this function to clear tile map bitmap memory and other repetitive operations that require the same value to be written Returns 1 Example s Fill 100 WORDS starting at address 3456 with the value AAFF GFX GPU Fill 16 0x3456 OxAAFF 100 2 Function Prototype int GFX GPU Copy Memte6 uns
98. is in terms of an IRE unit IRE is an arbitrary unit where 140 IRE 1Vp p or sometimes 1 4Vp p From the figure you can see that the voltage during the active video portion would yield a bright white picture for this horizontal scan line whereas the horizontal blanking portion would be displayed as black and therefore not seen on the screen Please refer back to Figure 11 3 4 for a pictorial explanation Some video systems NTSC only use something called setup which places reference black a point equal to 7 5 IRE or about 54mV above the blanking level Figure 11 6 b NTSC composite video waveform Timing and Level Standards of NTSC RS170A Waveform Front Porch 1 5 0 1pSec Blanking 10 9 0 2uSec Sync to Blanking End 9 4 1 t Sync to Burst End 7 8 Sec 9 1 100 IRE 1 714mV Breezeway M Burst 2 5 Sync 4 7ySec x 0 1 40 IRE Ref Burst Amplitude Blanking Level Ref Sync Amplitude Figure 11 6 b depicts yet another timing drawing the NTSC video signal this time more formally labeled at the RS 170A color standard created in the early 1950 s as the successor to the B W only RS 170 standard created 1941 48 2009 NURVE NETWORKS LLC Exploring the Chameleon AV
99. is useful for testing the connection between the mouse and its host Wrap mode may be entered by sending the Set Wrap Mode EE command to the mouse To exit Wrap mode the host must issue the Reset FF command or Reset Wrap Mode command If the Reset FF command is received the mouse will enter Reset mode If the Reset Wrap Mode EC command is received the mouse will enter the mode it was in prior to Wrap mode RESET Mode The mouse enters Reset mode at power on or in response to the Reset FF command After entering reset mode the mouse performs a diagnostic self test referred to as BAT Basic Assurance Test and sets the following default values Sample Rate 100 samples sec Resolution 4 counts mm Scaling 1 1 Data Reporting Disabled After Reset the mouse sends a BAT completion code of either AA BAT successful or FC Error The host s response to a completion code other than AA is undefined Following the BAT completion code of AA ok or FC error the mouse sends its device ID of 00 This distinguishes the standard PS 2 mouse from a keyboard or a mouse in an extended mode After the mouse has sent its device ID of 00 to the host it will enter Stream mode Note that one of the default values set by the mouse is Data Reporting Disabled This means the mouse will not issue any movement data packets until it receives the Enable Data Reporting command The various modes of operati
100. la elites edits 52 11 2 7 Generatng Color Video Dope ea de e 52 L12 8 NTSC Signal References 1 LU LL ee d esu or eR Ede estado i Re nada eile 53 12 0 KEYBOARD amp MOUSE HARDWARE nnn nnn nnns nnn nnnntn nnn sanas sss 53 12 1 Keyboard 54 12 1 1 Communication Protocol from Keyboard to 55 12 12 Keyboard Read Algorithm node doh eee oie t tein ac oai d oeste 56 121 3 Keyboard Write meh eee eI UE et n eO eia 56 12 1 4 Keyboard Commands RR Rai pani ete dea 57 12 2 Communication Protocol from Mouse to Host cerei eee e eene eese seen nett netta setas setas etes s seen sesenta ense een sse tns seno 58 12 21 Basic OE EOS EI ILE m 59 122 2 M se Data II X CM HEP 59 12 2 3 Modes of Operation isuse thant tee tides b ieee E Rented os 60 12 24 Sendin amp Mouse Commands s senda ache eee ih emot 61 12 2 5 MOUSE 63 12 2 6 Reading Mouse Movement 63 13 0 THE HEADERBS addas o Did at d 63 14 0 AUDIO HARDWARE inisencintuu cinia ia Ente unu inb rank n
101. many of them are invisible due to overscan and some must be used for the vertical retrace pulse Therefore a first attempt to generate a video signal frame is the following algorithm Step 1 Draw the top over scan For line 1 to 8 Begin the next black scanline En Step 2 Draw the active region of the scan 240 lines For line 1 to 240 Begin Generate the next scanline End Step 3 Draw the bottom over scan For line 1 to 10 Begin generate the next black scanline En Step 4 Generate a vertical sync pulse basically apply Ov to the signal for Time duration of scanlines note no HSYNC pulse is sent no serrations video 0 0v Delay 4 6 Scanlines If you add up the lines you will get a total of 262 lines including active inactive and retrace or vertical sync Now due to overscan you probably won t be able to see more than 200 220 of the active scan video lines they will typically be beyond view Thus most games systems don t waste draw them and simple increase the overscan regions So a good rule of thumb is that active video should be from 192 224 lines with equal amount of top and bottom overscan 50 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Now the above algorithm to draw a frame will work and is very simple but it doesn t comply with the RS 170A spec completely It s missing a very important signal component called the vertical serrations in the
102. means that the input to the TV s luminance has to be 6 0 MHz or greater Sorry to say it s not In most cases you are lucky if you get 4 5 5 0 MHz input bandwidth this 320 is a definitely upper limit on B W luminance transitions per line 11 2 7 Generating Color Video Data Generating color video is much more complicated than B W however if we take a practical approach rather that a mathematical its quite easy Forgoing the complex quadrature encoding of color and luminance and the encoding and decoding of the signals creating a color is very easy For each color clock on the active scan line you must generate a 3 579594 MHz sine wave this must ride on top or be superimposed on the luminance signal the Chameleon AVR hardware does all this The overall amplitude of the signal is the brightness or luminance just as it was with B W but the color signal s saturation is simple the peak peak p p value of the color signal 3 579595 MHz signal as shown in Figure 7 6 The actual color that is displayed has nothing to do with the amplitude of the video signal but only the PHASE difference from the reference burst from the original color burst reference at the beginning of each line To re iterate to generate color we simply produce a 3 579594 MHz signal superimpose or add it to the overall luminance signal and the phase difference between our color signal and the reference is the color on the screen Cool Taking this further let s b
103. not widely supported 3 Italic on not widely supported Sometimes treated as inverse 4 Underline Single not widely supported 5 Blink Slow less than 150 per minute 6 Blink Rapid MS DOS ANSI SYS 150 per minute or more 7 Image Negative inverse or reverse swap foreground and background 8 Conceal not widely supported 21 Underline Double 22 Intensity Normal not bold and not faint 24 Underline None 25 Blink off 27 Image Positive 28 Reveal conceal off 30 39 color nomnal 3x where x is from the color table above 40 49 ene color nomal 4x where x is from the color table above Examples CSI 2 J This clears the screen and sets the cursor to 0 0 or 1 1 upper left corner CSI 32m This makes text green 267 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit NOTES 268
104. note bootloader slightly modified Thus you can make your own bootloader use Atmel s and so forth along with your own copy of the GNU GCC AVR tools and then program on Linux Windows Mac or any other operating system the GNU GCC tools are available on The bottom line is that all the bootloader does for us is allow a serial protocol to communicate to the AVR chip and FLASH its memory with a program This saves you the 29 39 of a AVR ISP programmer that s about it 248 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 33 1 Developing Your Own Propeller Drivers Well the last burning question in your mind should be how do add more functions to the Propeller driver This is a multistep process but very easy As an example we are going to add a couple messages that allow the client master application running on the AVR to control the status LED on the Chameleon next to the Propeller Local 8 bit port Before we begin let s take a quick look at the flow of messages from the AVR to the Propeller once again to review all the components take a look at Figure 33 1 below Figure 33 1 The flow of messages from the AVR or PIC to the Propeller CORE 1 COG 1 AVRIPIC Processor SPI Interface Running main application as master 1 Shared Memory j all cores have access aia _ Virtual SPI Interface CORE 0 COG 0 This process starts first a
105. on the rising edge of the clock Note Most SPI slaves default to mode 0 so typically this mode is what is used to initiate communications with a SPI device Figure 19 2 a SPI timing diagrams for clock phase polarity CPHA 0 SCK CPOL 1 SCK CPOL 0 Present bit Sample bit SPI signals when CPHA 0 154 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 19 2 b SPI timing diagrams for clock phase polarity CPHA 1 SCK CPOL 1 SCK CPOL 0 Present bit Sample bit SPI signals when CPHA 1 19 1 1 Basic SPI Communications Steps Figures 19 2 a and b show the complete timing diagrams for all variants of clock polarity CPOL and clock phase CPHA You must adhere to these timing constraints during communications In most cases you will use mode 0 since its the default that most SPI devices boot with The good news is this is all taken care of by the AVR 328P in fact most AVR microcontrollers have complete SPI and hardware built in that take care of all the details of both transmission and reception The only thing we have to do as programmers is set the hardware up then send and receive bytes and maybe handle an interrupt or two Thus working with SPI in the AVR 328P is very easy Nonetheless the library module we developed wraps the SPI hardware with a thin layer of functions so that you do
106. parity and stop bit but you don t need to unless you want to perform error correction Both the keyboard and mouse use an odd parity scheme for error detection Odd parity is HIGH when the number of 1 s in a string is ODD LOW otherwise Even parity is 2 HIGH when the number of 1 s in a string is EVEN LOW otherwise Note that parity only tells us there is an error but not how to correct it or where it was You simply have to re transmit the data 12 1 3 Keyboard Write Algorithm The process of sending commands to the keyboard or writing to the keyboard is identical to that when reading The protocol is the same except the host initiates the conversation Then the keyboard will actually do the clocking while the host pulls on the data line at the appropriate times The sequence is as follows Step 1 Wait for the keyboard to stop sending data if you want to play nice This means that both the DATA and CLOCK lines will be in a HIGH state 56 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Step 2 Initiate transmission The host drives the CLOCK line LOW for 60us to tell the keyboard to stop all transmissions This is redundant if you waited for Step 1 however the keyboard might not want to shut up therefore this is how you force it to stop and listen Step 3 Data ready for transmission Drive the DATA line LOW then release the CLOCK line by release we mean not to put a H
107. picture is painted on the screen by scanning all of the horizontal lines of the picture in one pass from the top to the bottom This is illustrated in Figure 11 4 Figure 11 4 Progressive non interlaced scanning system Retrace Scan Line NOTE Exaggerated in the vertical dimension for clarity Screen 46 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 11 2 2 Video Formats and Interfaces There are many different kinds of video signals which can be divided into either two classes those for television and those for computer displays The format of television signals varies from country to country In the United States and Japan the NTSC format is used NTSC stands for National Television Systems Committee which is the name of the organization that developed the standard In Europe the PAL format is common PAL phase alternating line developed after NTSC is an improvement over NTSC SECAM is used in France and stands for sequential coleur avec memoire color with memory It should be noted that there is a total of about 15 different sub formats contained within these three general formats Each of the formats is generally not compatible with the others Although they all utilize the same basic scanning system and represent color with a type of phase modulation they differ in specific scanning frequencies number of scan lines and color modulation techniques among others The various computer formats such as
108. port but these generic access commands model how you would access a general register based system remotely so good example these commands are DANGEROUS since you can break the COG with them and require a reset so if you are going to write directly to the registers be careful REG_CMD_WRITE 56 performs a 32 bit write to the addressed register 0 F from the output register buffer REG_CMD_READ 57 performs a 32 bit read from the addressed register 0 F and stores in the input register buffer REG_CMD_WRITE_BYTE 58 write byte 0 3 of output register g_reg_out_buffer byte 0 3 REG_CMD_READ_BYTE 59 read byte 0 3 of input register g_reg_in_buffer byte 0 3 system commands SYS_RESET 64 resets the prop As you can see there is a lot of commands supported This is necessary so the AVR master client can issue commands to the Propeller slave to do what it needs it to do However this is only a template you can re write the default2 driver if you wish modify optimize change the objects it uses etc But you will have to modify all the APIs on the AVR side as well with the new commands and SPI API calls so we suggest you start simply by adding commands and or modifying commands that already exist Once a valid command is detected then its parsed and a case handler in the MCP tries to dispatch it to the proper driver object themselves running on other cores potentially An excerpt from that section of the d
109. primary IDE developed by Atmel for programming the AVR line of processors The tool comes complete with everything you need to program in assembly language use simulators debuggers and various programming tools developed by Atmel as well as 39 party vendors AVR Studio 4 xx does NOT have a built in compiler only assembler For this we will use a free GNU GCC compiler targeted toward AVR processors Normally this would be a very complex task to set up however there is another tool called WinAVR that eases this process for us 76 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit AVRISP This is the actual hardware programmer that is recommended for the Chameleon AVR 8 Bit The programmer only supports programming and not debugging but is low cost and very versatile The programmer must be installed as well and its firmware potentially updated This installation will be done after the other tools are installed so AVR Studio 4 xx specifically can update any drivers needed for the tool since AVR ISP is integrated into the AVR Studio IDE itself WinAVR This is a GNU GCC compiler installation that works on Windows that integrates the GNU GCC compiler and appropriate tools such as the GNU Assembler Linker and Make tools all in a single Windows installation package Thus after we install AVR Studio 4 xx we will install WinAVR to give the IDE C C support In addition to the GCC compiler the 34 party run time C C
110. puu 3 end setup LOOP CALL ARDUINO SPE D MM MM M MILI B M MaUIE I LB B M aal FP M M M P MM O I T T initialize and set SPI rate SPI_Init SPI_DEFAULT_RATE clear screens NTSC Clearscreen VGA_ClearScreen enter infinite loop print on NTSC terminal screen NTSC_Color 0 NTSC Term Print Hello world SNE print on VGA terminal screen VGA Color 0 Term Print Hello world a slow things down a bit so we can read the text _delay_ms 10 end while end main Reviewing both files 90 of porting all programs from AVRStudio to Arduino is simply making sure header files have angle brackets lt gt and that main is replaced with and that a function setup is added to your program The setup function can be empty but will be called before loop is thus it s a nice place to put initialization code Personally just think of loop as main and leave it at that Serial I O Libraries The last little porting tip has to do with serial communications We wrote serial UART libraries for the Chameleon AVR that are stored in CHAM AVR UART DRV 010 You have seen these in the API overview section However Arduino has a built in serial class that you can review here http arduino cc en Reference Serial Thus you can use our library or the Arduino library if you decide to use one or the other then por
111. reference at the beginning of each line and the color burst tone of each pixel In any case 8 10 clocks must be sent usually send 9 10 cycles of color burst Each cycle at 3 579594 MHz takes 279 36 ns therefore if you want 10 cycles of color burst you must turn the color burst hardware on for 279 36 ns 10 2 79 us approximately Back Porch Immediately following the color burst is the final part of the setup for the actual pixel data this is called the back porch and should last 1 6 us 11 2 6 Generating B W Video Data The remainder of the video information is 52 6 us this is where you insert your pixel data Now if you wanted a B W only signal then you would modulate the video signal from BLACK 0 3V to WHITE 1 0V for the remainder of the line and be done with it For example each line could rasterize a line buffer or a sprite and different values would map to different voltages from BLACK to WHITE With this approach most TVs have an input bandwidth wide enough to display about 320 luminance changes per active line that means that no matter how fast you try to change the luminance signal only 320 times a line will you see anything Let s see how we roughly estimate this The line length is 52 6 us we want to make 320 changes in that time that means that we need to send data at a rate of 52 6 us 320 164 375 ns per change Inverting this gives us the frequency which is 1 164 375 ns 6 0 MHz roughly Ouch that
112. run the program you will see a dialog like that shown in Figure 15 50 112 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15500 PuTTY Setup for serial communications with Chameleon AVR 115200 baud N81 i amp PuTTY Configuration Category B Session Logging Terminal BET Serial line Keyboard Bell COM30 Features Connection type Window ORaw OTelnet Rlogn OSSH Serial Appearance Behaviour Translation Saved Sessions Load save or delete a stored session Selection Colours Connection Data Proxy Telnet Rlogin Serial Close window on exit ONever Only on clean exit Default Settings Click on lt Serial gt for the connection type as shown in the top right then click Serial on the bottom of the Category tree panel on the left and make sure the settings listed below and shown in Figure 15 51 Data Format N81 no parity 8 data bits 1 stop bit Baud Rate 115200 Handshaking None Figure 15 51 PuTTY Setup for serial communications with Chameleon AVR 115200 baud N81 continued i amp PuTTY Configuration Category Session Options controlling local serial lines Logging Terminal Keyboard Serial line to connect to Bell Features Window Speed baud Appearance Behaviour Translation Stop bits Selection Colours Connection Flow control Data Proxy Telnet
113. same value to be written Returns 1 Example s Fill 100 BYTEs starting at address 3456 with the value AF 186 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit GFX GPU Fill Mem8 0x3456 OxAF 100 Function Prototype int GFX GPU Copy Meme8 unsigned int dest ptr unsigned int src ptr unsigned int num bytes Description GFX GPU Copy 8 copies a number of bytes from source to destination in the GPU memory space in BYTE side chunks or in other words in the Prop s local memory of 32K you can use this to overwrite SPIN code so watch out The parameters are the destination address to copy to dest ptr the source address to copy from src ptr and finally the number of bytes num bytes to copy Typically you will use this function to copy tile maps scroll page flip perform various animations etc Returns 1 Example s Assuming that the current tile map is 32x24 physically and virtually and there are two tile maps located at 1000 and the other at 2000 copy the later to the former GFX GPU Copy Mem8 0 1000 0x2000 32 24 2 Function Prototype unsigned int GFX Read Palette Ptr void Description GFX Read Palette Ptr reads the 16 bit palette pointer that points to the set of palettes referred to by the palette index in each tile entry This pointer is of course relative to the Propeller s 32K memory space and an absolute address Each p
114. standard default mode as explained in the sections above The only thing we need to do to get the mouse sending packets is to tell the mouse to start reporting movement This is done by sending the command Enable Data Reporting F4 the mouse responds with FA to acknowledge the command worked and then will start streaming out 3 byte movement packets at the default rate of 100 samples sec This step is necessary since on start up if the mouse simply started streaming data packets the host could loose important data thus the mouse waits to be told to start streaming the data and reporting the motion The movement data packets are formatted as shown in Table 12 5 You simply need to read these packets and send them upstream to your application 12 2 6 Reading Mouse Movement Assuming that the mouse has been initialized and is in Streaming mode with Reporting mode enabled then you simply loop and read each 3 byte movement packet As you read the first byte you use it to determine the state of the buttons as well as any overflows with the counters Then the next two bytes the X and Y deltas should be added to running counters 16 bit that track the absolute position of the mouse cursor That s it Of course this is only for your edification the Propeller driver does all this for you so all you have to do is send a simple command from the AVR to the Propeller to read the keyboard or mouse 13 0 The I O Headers The I O headers on th
115. sub section of the design we need to look at and that s the serial port routing switch shown in Figure 5 1 31 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 5 1 Serial port routing selector switch USB serial transmit out switch SW3 lt gt USB RXDavr lt T gt USB RXDprop The USB UART has a standard TX RX serial line pair But there are two targets we need these to go to the Propeller chip and the AVR thus we just can t connect them in parallel since if both the Propeller and AVR try to transmit at the same time then there will obviously be a problem Moreover the impedance reflected by tying the TX RX to both devices is not desired Thus a mechanical switch SW3 is used to switch the RX lines which at very least are needed to allow both devices to share the serial port Therefore when you want to talk to the Propeller chip via the USB serial port you must place the switch into the Propeller mode UP and similarly when you want to talk to the AVR you must put the switch into the AVR mode DOWN 32 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 6 0 USB Serial UART Figure 6 1 The FTDI USB to Serial UART USB_5VOUT USB Interface System lt T gt USB_TXD lt gt Use U6 H1 FTDI FT232R 20 5 ao D Teno USB MINI B FEMALI USB RTSn USB CTSn USB DTRn USB DSRn USB DCDn USB Rin lt T gt USB 0 CL USB GPIO
116. such a short time The Chameleons push 180 200MIPs depending on the version AVR PIC Literally 100 200x more powerful that the 8 bit computers of the 1980 s but yet are the size of credit cards The first official processor was the 4 Bit Intel 4004 shown to the left created in 1971 It contained about 2300 transistors and executed instructions at a rate of 92 000 per second Comparing this to our simple Chameleon AVR that runs about 180 million instructions per second that s about 2000 times more powerful But if we look at cutting edge GPU cores that perform computation in the trillions per second then that s 10 million times more powerful Then go head and parallel up 10 100 1000 of those processing cores and the amount of computation is astonishing Bottom line our little brains are easily going to be matched and surpassed by computers VERY soon So cherish these last days while humans are still the dominant species on the planet Good luck and please help us build the Chameleon community you can visit our forums at http www xgamestation com phpbb index php and http www chameleon dev com Discuss and show off your demos applications drivers and games with other Chameleon programmers Also if you have any questions comments or remarks please email us at support nurve net 256 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Part 1 Appendices Appendix A Schematics This appendix c
117. supports some extra functionality that we haven t exposed yet and wish to The sound driver for example falls under this category barely exposed its true power so you might want to add more messages In this case you have to add the messages to the H file as well as the SPIN file In addition to this you need to add more cases to process and dispatch the messages in the SPIN driver and then on the AVR C C side you might want to add more API functions Class 2 New object new functionality The second case is when you want to add a completely new driver object and run it on another processor on the Propeller In this case you will load the object in at the top of the main driver start it up and then add messages along with message handlers to the main message dispatcher loop This is the most complex case Class 3 Simple messages that can be processed in place Finally the last case is the easiest and the one we will illustrate This is the case where we want to add some functionality to the main Propeller driver but we can run that functionality right on the main processor that is running the message loop Examples of this are the Propeller local port driver Messages run right on the main SPIN interpreter there is no need to add another processor 33 1 1 Adding SPIN Driver Support for the Status LED As we designed the Chameleon we added a status LED to it The idea of this LED was for the Propeller to use it to indicate statu
118. that the Propeller uses SPI SS2n as its chip select respectively The remaining chip selects SPI SSOn SPI SS1n are exported out to the interface header J6 on pins 7 8 respectively So you can hook up 2 more SPI devices easily with the MISO MOSI SCLK lines and then connect on of the aforementioned SPI selects to enable it All the other SPI devices will be disabled and thus no bus contingency issues 10 0 VGA Graphics Hardware In this chapter we are going to take a look at the VGA hardware on the Chameleon AVR The VGA hardware is very simple consisting of little more than 8 I O lines and 3 D A converters based on resistors The Propeller chip does all the work generating the VGA signal but its nice to understand what s going on so we are going to briefly take a look at the VGA specification so you have a conversational understanding of it if you haven t programmed direct VGA before and why VGA is both good and bad from a video generation point of view So here s what s in store Origins of VGA Chameleon AVR VGA hardware design VGA signal primer 36 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Before we start into the design let s get some history and terminology correct First the last time saw a real VGA monitor was about 20 years ago the new 21 century monitors that you are used to are super sets of VGA they are typically multisync variable refresh and can go up to 2400x2400 or more
119. the Chameleon AVR 8 Bit 15 1 Atmel s AVR Studio Toolchain Overview Atmel s AVR Studio is the premier development tool for AVR processors The tool is 100 free support assembly language natively and now with the integration of WinAVR the tool supports C C seamlessly Like all tool chains this can be quite complex and a single incorrect checkbox can wreak havoc on many installation making them useless For this reason we will cover the installation of all main tools in the chain step by step For those of you reading that are already expert in installation of AVR tools then you can skim this section and jump to the Arduino tool installation Figure 15 1 The relationship of the various AVR programming tools in the tool chain WinAVR AVR Studio 4 xx IDE MEAE Es AVR LibC Make lt gt Gas lt gt Stdlib Runtime This component performs all the complex installation of the tools for you All the AVR libraries needed to build applications Sta rtup This is the main application you will develop your code with Chameleon AVR 8 Bit 18 AVR ISP Programmer Referring to Figure 15 1 you can see that there are three main components of the tool chain for the Chameleon AVR and AVR processors in general they are Studio 4 xx AVRISP sold seperately WinAVR AVR Studio 4 xx This is the
120. the chip since we don t want to do that yet but it will program the fuse bits only Go ahead and click Programs to write the fuse bits if everything goes well you should see the text output window at the bottom of the tool scroll some informational strings and you should see a lot of OK s displayed If you don t try it again Normally you do not have to do this when programming the chip The programming process will reset the fuse bits as well but it can t hurt to make sure If your chip ever acts strangely always go and investigate the fuse bit settings and see if they are correct as shown in Figure 15 38 We are almost there the very last tab of interest is the Lockbits tab select this tab as shown in Figure 15 39 Figure 15 39 The AVR ISP MKII control panel s Lockbits tab AVRISP in ISP mode with 328 No memory lock features enabled No lock on SPM and LPM in Application Section No lock on SPM and LPM in Boot Section LOCKBIT Auto read Smart wamings Lockbits not read clear lockbits use Erase Device on Main tab Verify after programming Program _ Setting mode and device parameters OK Entering programming mode OK Reading lockbits OxFF OK Leaving programming mode OK 103 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The Lockbits tab controls memory protection features of the AVR series processors I
121. the flexibility to add stuff if we desire gfx_ntsc Out_Term 00 add other functionality to the clear screen here As you can see the code to extract and rebuild the SPI packets is tricky a lot of bit fiddling and masking to get the data back from the ASM SPI driver that is passing the data into the global shared memory All packets are 3 bytes long and look like this Command Packet Format 8 data low8 data high8 Commands that only require 8 bits of data or operand only use the first data byte commands that require 2 bytes use both the low and high The bottom line is all commands only are 3 bytes so you can t send a string or something large you have to design your commands so they are simple and can be constructed with only 2 bytes of data at most Thus most commands are atomic in nature For example there is no print string command there is only a print character command but by stringing a collection of print chars together at the master client side you can print a string All the commands are designed with this in mind The drivers for each of the media devices were selected based on functionality and popularity There are definitely better drivers for many of the devices For example more robust graphics drivers or more advanced sound drivers etc However this default driver isn t about using the best but more about system integration Thus drivers that are easy to interface to and easy to control
122. the whole other process of creating a sound engine on top of these techniques to play music such as MIDI or MOD 74 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 0 Installing the Tool chains AVRStudio Arduino and Propeller IDE The first step in developing applications for the Chameleon AVR is to install the tool chains and all their components Since the Chameleon is compatible with the Arduino tool chain as well as the standard AVR Studio we are going to cover both methods with the emphasis on the more complex toolchain AVR Studio The Arduino tool is relatively easy to install so we will cover that at the end of this section Also the Chameleon s AVR is pre loaded with the Arduino bootloader in its flash memory So if you don t have a AVR ISP programmer or you simply don t want to deal with AVRStudio you can work with the Arduino toolchain alone However still recommend you skim the discussion of AVRStudio since it s a much more powerful tool than the Arduino tool Additionally the Chameleon has a Parallax Propeller chip on it so we have to install that tool as well so there is a lot to do We are going to show the installations of the tool in the following order AVR Studio IDE Arduino Development System Propeller IDE If you do not own a AVR ISP II or similar in circuit programmer then you can skim the first section 75 2009 NURVE NETWORKS LLC Exploring
123. to generate a line of video with a negative sync polarity you start by turning off all the R G B channels with a 0 0V and simply hold the hsync line LOW for 3 77 us B then you wait 1 89 C and the VGA is ready to take R G data now you clock out 640 pixels at 25 175 MHz for a total time of 25 17 D for the active video portion You then turn the video lines B off and wait 0 94 ps E and then start the process again And that s all there is too it Perform this process 480 times then its time for a vertical sync and retrace let s look at that 10 3 2 VGA Vertical Timing The vertical sync and retrace is much easier than the horizontal timing since there is no video to interleave in the signal Referring to Figure 8 3 c the various named timing regions of the vertical timing are O 16 68 ms Total frame time P 64 us Vsync pulse Q 1 02 ms Back porch R 15 25 ms Active video time S 0 35 ms Front porch The meaning of each is similar to that in the horizontal sync period except the event they are focused around are the 480 lines of active video so the 480 lines are encapsulated in R The most important thing to realize is that these times are in measured in milliseconds for the most part except for the Vsync pulse So once again the timing of an entire frame starts off with the Vsync pulse P for 64 us after which comes the back porch for 1 02 ms followed by the active video R for 15 25 ms
124. to make things easier 16 4 1 Normalization of Drivers for Common RPC Calls in Future The last thing want to discuss about the drivers in the interfaces to all of them Since this is a pieced together system of other people s drivers each driver obviously has its own methodology and API For example the NTSC calls look entirely different from the keyboard calls and so forth Alas if you were to develop a system from the ground up and design drivers for NTSC VGA keyboard etc you would be wise to design all the APIs in a similar fashion with conventions for function calls inputs and outputs so that technologies like RPC calls and others could more easily be implemented and optimized better 17 0 Chameleon AVR API Overview In this section of the manual we are going to discuss the Chameleon AVR API and its related components First and foremost want to make it clear that the API we have developed is by no means complete the best the fastest etc It s just a set of source files and functions that get you started developing applications Moreover since the whole idea of the Chameleon is to leverage the functionality of the drivers running on the Propeller chip The AVR side API is nothing more than wrapper functions that container a number of SPI commands so you don t have to type a lot to get things done In other words you don t have to use these libraries in most cases you can just send command directly if you wish Moreover these
125. tries to parse it to determine if it s a valid command that is supported This is achieved via a large switch statement to see if the command portion of the packet is valid Below is the list of current commands supported by the MCP by the default driver cham default2 drv 112 spin null command does nothing CMD NULL 0 graphics commands GFX_CMD_NULL 0 NTSC commands GFX_CMD_NTSC_PRINTCHAR 1 GFX_CMD_NTSC_GETX 2 GFX_CMD_NTSC_GETY 3 GFX_CMD_NTSC_CLS 4 VGA commands GFX_CMD_VGA_PRINTCHAR 8 GFX_CMD_VGA_GETX 9 GFX_CMD_VGA_GETY 110 GFX_CMD_VGA_CLS 1 mouse and keyboard are loadable devices user must load one or the other on boot before using it keyboard commands KEY_CMD_RESET 16 KEY_CMD_GOTKEY ily KEY_CMD_KEY 18 KEY_CMD_KEYSTATE 19 129 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit KEY_CMD_START 220 KEY CMD STOP 21 KEY CMD PRESENT 22 mouse commands MOUSE_CMD_RESET 24 resets the mouse and initializes it MOUSE CMD ABS X 25 returns the absolute X position of mouse MOUSE CMD ABS Y 26 returns the absolute Y position of mouse MOUSE ABS Z 27 returns the absolute Z position of mouse MOUSE CMD DELTA X 28 returns the delta X since the last mouse call Y Y F x MOUSE_CMD_DELTA_Y 29 returns the delta Y since the last mouse call L MOUSE_CMD_DELTA_Z 30 returns the delta Z since the last mouse call MOUSE_
126. underlying code in printf scanf and so forth but in embedded systems we can t use these calls since they usually have no meaning and we need to write them ourselves Alas in this case we need some kind of simple single line text editor so the user can type on the screen backspace etc and do a few reasonable edit related keystrokes The terminal program has no idea about this and nor does the UART the UART just receives ASCII characters thus we need to write a single line text processor to make this work The function listing of this code is below 236 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Get_String char cmd_buff char tokens A LIUM LU TUUM ggg gu function waits for the user to input a string on from the UART it supports some editing such as backspace when the user hits return the string is tokenized into an array of strings tokens The number of tokens extracted are returned by the function INPUTS 7 buffer pointer to string storage where the raw ASCII string from the UART is placed tokens an array of pointers where the function puts the tokenized strings OUTPUTS 724 urns the number of tokens HT HIE TRI IH M MA int c char token buff 64 int num tokens 0 int next token 0 int cmd buff index 1 char token ptr NULL char result ptr enter infinite while until valid string is entered process next c
127. various files and statistics as builds are performed The IDE supports the built in Atmel assembler directly or GNU GCC When in Atmel ASM mode then all your programs must be ASM files using Atmel ASM directives and syntax they are assembled and linked and a final binary image is generated ready for download to the target Chameleon in this case This is not how we will use the tool in most cases Typically we will use it in GCC mode so we can code in both C and ASM However when you use the GCC mode of operation you are using the entire GCC tool chain including GCC the C compiler GAS GNU assembler make librarian and so forth Luckily all of this is handled for you automatically as are the creation of Make scripts and so forth 22 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit But when you use GCC and the GNU assembler GAS you must use all GNU syntax which is fine for C but a bit tedious for ASM The Atmel assembler is a little cleaner in my opinion but GAS is fine as well In any event when you create a new project for the Chameleon you will select GCC and then you can write C or S asm files and then will be compiled assembled and linked together More of the mechanics of this later but that s the idea Additionally you can use inline assembly with GCC but the syntax is terrible as shown in the code snippet below which simply swaps a pair of integers asm volatile mov tmp reg mov
128. vertical sync pulse If you look at the rough draft algorithm above we have a vertical sync period where we simply generate sync signal for 4 6 scanlines This is fine and will work but you will notice an effect called flagging at the top of the display which is ugly A better approach is to continue to generate hsync pulses during the vsync This keeps the horizontal sync timing hardware tracking To accomplish this the hsync is simply inverted Both the hsync and vsync filters will still detect the edges of the pulses so the inversion doesn t hurt anything so both the hsync and vsync occurs and the horizontal timing circuitry doesn t loose sync Now you might ask why wouldn t you always perform this inversion of the hsync during the vsync Well the answer is that you might want to have once big continuous block of 4 6 lines that you set a single bit sync and then you can do work without interruption but the video looks quite ugly so it s a compromise In any event considering this adjustment to our algorithm all we have to do is generate 6 hsync pulses at the end of the bottom overscan that are inverted thus this new algorithm will suffice Step 1 Draw the top over scan For line 1 to 8 Begin cenonate the next black scanline En Step 2 Draw the active region of the scan 240 lines For line 1 to 240 Begin Generate the next scanline End Step 3 Draw the bottom over scan For line 1 to 10
129. with a specific number of data table elements will make the whole thing work Here s the final math Given 1 A complete sine waveform has 65536 data entries in our virtual table and 256 in the real table 2 The PWM frequency is 256K NUM_INCREMENTS The number of times that the PWM signal increments thru the final signal table in ONE complete wave cycle This is shown in Figure 14 7 In other words NUM_INCREMENTS signal period PWM period PWM frequency signal frequency Now let s compute PHASE_INC PHASE_INC 65536 NUM_INCREMENTS That is the PHASE_INC is the rate at which we need to increment thru the data table to maintain the relationship so that the output is changing at the rate of the signal frequency Now plugging this all in together and moving things around a bit PHASE_INC 65536 signal frequency PWM frequency And of course PHASE_ACC is simply set to 0 to begin with when the algorithm starts As an example let s compute some values and see if it works First let s try a 1KHz signal and see what we get PHASE_INC 65536 1KHz 256 000 256 So this means that we add 256 to the phase accumulator each PWM cycle then use the upper 8 bits of the phase accumulator as the index let s try it a few cycles as see of it works Table 14 2 Test of PWM algorithm at 1KHz with PHASE_INC of 256 Iteration PHASE INC PHASE ACC PHASE ACC upper 8 bits oO 256 0 256 512
130. written by paid professionals so it s a compromise As mentioned before WinAVR integrates into AVR Studio giving AVR Studio C C support along with the GCC assembler named GAS Before WinAVR you could still get AVR processor GCC support but you would have to do a lot of work to accomplish this thus the installer for WinAVR performs all kinds of really complex and tedious setup tasks and hides all the complexity from you With that in mind let s begin the installation The latest WinAVR installer is located on the DVD here DVD ROM CHAM_AVR TOOLS AVR WinAVR 20090313 install exe Of course you can always download the very latest copy to the minute from the Source Forge site but once again let s just use the one on the DVD ROM so we both have the exact same software You can update in the future once you have everything working Once you have located the installation file go ahead and launch it you will see the language splash screen as shown in Figure 15 11 below ignore the version differences from our screen shots to the latest copy on the DVD 82 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 11 WinAVR language selection Installer Language amp Please select a language cnc Select English and click lt gt this will bring you to the main splash screen shown below in Figure 15 12 Figure 15 12 WinAVR main splash screen amp
131. 0 1 Keyboard demo in action Press keys on local keyboard Key Code 115 s Welcome NEO ficcess Granted Compiling and Running the AVRStudio Version Demo Version Description Echoes the local PS 2 Chameleon keyboard to the displays Main Source File CHAM AVR KEYBOARD DEMO 901 C Additional Files Required CHAM AVR SYSTEM V010 c h CHAM AVR TWI SPI VO010 c h CHAM AVR NTSC 010 CHAM AVR VGA V010 c h CHAM AVR KEYBOARD DRV V010 h General Requirements Video ports connected to NTSC or VGA monitors Controls Required PS 2 keyboard plugged into Chameleon simply type into the keyboard and watch the output on the NTSC VGA displays Compiling and Running the Arduino Version Demo Version Description Echoes the local PS 2 Chameleon keyboard to the displays Main Sketch Source File CHAM AVR KEYBOARD DEMO Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR TWI SPI DRV V010 CHAM AVR NTSC V010 CHAM AVR V010 CHAM AVR KEYBOARD DRV V010 General Requirements Video ports connected to NTSC or VGA monitors Controls Required PS 2 keyboard plugged into Chameleon simply type into the keyboard and watch the output on the NTSC VGA displays Technical Overview This demo uses the single keyboard API call Keyboard Key to read the keyboard It then displays the key both integer as well as ASCII format The listing below is an
132. 000 01101001 01101010 01101011 01101100 01101101 01101110 01101111 Bin 10100000 10100001 10100010 10100011 10100100 10100101 10100110 10100111 10101000 10101001 10101010 10101011 10101100 10101101 10101110 10101111 Bin 11100000 11100001 11100010 11100011 11100100 11100101 11100110 11100111 11101000 11101001 11101010 11101011 11101100 11101101 11101110 11101111 Dec 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 Dec 240 Oct 260 261 262 263 264 265 267 270 271 272 273 274 275 276 277 01111000 01111001 01111010 01111011 01111100 01111101 01111110 01111111 Bin 10110000 10110001 10110010 10110011 10110100 10110101 10110110 10110111 10111000 10111001 10111010 10111011 10111100 10111101 10111110 10111111 Bin 11110000 11110001 11110010 11110011 11110100 11110101 11110110 11110111 11111000 11111001 11111010 11111011 11111100 11111101 11111110 11111111 265 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix J ANSI Terminal Codes This appendix lists some of the more popular ANSI X3 64 terminal codes used to control graphically terminals and make really cool graphics on 8 bit computers The majority of ANSI codes start off with the ANSI escape sequence which is the characters ESC ASCII decimal 27 hex 0x1B and left bracket in other words ESC Where ESC is act
133. 000 Hz Step 2 Calculate the Phase Increment PHASE INC to add to the Phase Accumulator PHASE such that the final desired signal frequency is output via the lookup into the sine or waveform table Step 3 Continually add the Phase Increment to the Phase Accumulator and every cycle use the upper 8 bits of the Phase Accumulator as the index into the 256 element sine table Figure 14 7 Our final PWM setup Sine Table 256 0 1 Phase Accumulator constantly changing b7 bO A Bits b15 b8 used Phase Inc is added as 8 bit index to Phase Accumulator into lookup table 255 b15 bO Phase Inc constant value Now to recap we still have a table that has only 256 elements but we are going to pretend it has 65536 elements that is 256 256 to improve our accuracy this is nothing more than using a shift lt lt 8 and create a fixed point value in 8 8 format Next we are going to call out a couple vars to make the algorithm easy one is an accumulator called PHASE_ACC that simply accumulates the current count then we convert it back to an integer by shifting it gt gt 8 times OR just using the upper 8 bits at the index into our 256 element sine table the later is preferred Then we simply need the magic number 72 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit PHASE_INC that for a given PWM frequency 256 000 in this case and a desired output signal frequency along
134. 0000C9465180C940000EF92FF920F931F931D 1000C0008C0188E090E06CE070E040E050E00E943D 1000D0003D1280EA4E82E86E0F82EC7010197F1F783 1000E0000770107088E090E0B80140E050E00E9496 1000F0003D12C7010197F1F781E090E01F910F9148 10010000FF90EF9008958BE090E060E070E040E0B9 92 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 1001100050E00E943D1280EA9FE00197F1F781EOF4 1001200090E00895CF92DF92EF92FF920F931F938A 100130007C01680189E090E060E070E040E050E01D Moving on the next settings we are interested in are the Libraries tab of the settings dialog as shown in Figure 15 25 Figure 15 25 The Libraries tab of the Project Configuration control dialog cham avr work 01 Project Options Library Search Path TA har General _ Include Directories Available Link Objects ibc Add Library libobjc a Libraries libprintf libprintf_min a B libscant_flt a libscant_min a Add Obiect Memory Settings Shown in Figure 15 25 is the library tool There are two main panes one for the library search path and one that allows you to add remove libraries Due to the way we setup AVR Studio all we need to do is add one library which is libm a Math library Later we might add more libraries but for now simply select this library on the left side of the Available Link Objects and then click lt Add Library gt to add it once done you should see it on the r
135. 010 00001000 24 18 030 00011000 40 28 050 00101000 56 38 070 00111000 9 9 011 00001001 25 19 031 00011001 41 29 051 00101001 57 39 071 00111001 10 A 012 00001010 26 1A 032 00011010 42 2A 052 00101010 58 3A 072 00111010 11 B 013 00001011 27 1B 033 00011011 43 2B 053 00101011 59 3B 073 00111011 12 C 014 00001100 28 1C 034 00011100 44 2C 054 00101100 60 3C 074 00111100 13 D 015 00001101 29 1D 035 00011101 45 2D 055 00101101 61 3D 075 00111101 14 E 016 00001110 30 1E 036 00011110 46 2E 056 00101110 62 3E 076 00111110 15 F 017 00001111 31 1F 037 00011111 47 2F 057 00101111 63 3F 077 00111111 Dec Hex Oct Bin Dec Hex Oct Bin Dec Hex Oct Bin Dec Hex Oct Bin 64 40 100 01000000 80 50 120 01010000 96 60 140 01100000 112 70 160 01110000 65 41 101 01000001 81 51 121 01010001 97 61 141 01100001 113 71 161 01110001 66 42 102 01000010 82 52 122 01010010 98 62 142 01100010 114 72 162 01110010 67 43 103 01000011 83 53 123 01010011 99 63 143 01100011 115 73 163 01110011 68 44 104 01000100 84 54 124 01010100 100 64 144 01100100 116 74 164 01110100 69 45 105 01000101 85 55 125 01010101 101 65 145 01100101 117 75 165 01110101 70 46 106 01000110 86 56 126 01010110 102 66 146 01100110 118 76 166 01110110 71 47 107 01000111 87 57 127 01010111 103 67 147 01100111 119 TT 167 01110111 264 Dec 128 129 130 131 132 133 134 135 137 138 139 140 141 142 143 Hex C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF Oct 200 201 202 203 204 205
136. 1 J6 AIN2 25 PC2 ADC2 PCINT10 J6 AINO 23 PCO ADCO PCINT8 J7 RESn 1 PC6 PCINT14 RESETn J7 GND 8 22 GND Note 1 Power pins 5VCC 33VCC GND don t actually connect to the AVR but to the system power lines which in turn are electrically connected to the AVR s AVCC VCC and GND respectively Note 2 VIN is connected to the 5V regulator s input pin This signal reflects the input analog voltage plugged into the 9V DC power jack If only the USB power is plugged in this signal will be floating or near ground 14 0 Audio Hardware There is no dedicated audio hardware inside the AVR chip nor the Propeller chip therefore we have to rely on software techniques to create sound for the system However knowing that software is going to be used to generate sound we can add a little analog circuitry to help the audio software out and allow us to use certain common techniques for generating sounds The Propeller does have counters on board and can generate PWM signals thus the audio drivers typically leverage these hardware elements Thus for most audio applications that connect to a Propeller chip all you need is a typical PWM integrator or low pass filter The Chameleon employs such a hardware design as shown in Figure 14 1 Figure 14 1 The analog audio hardware on the Chameleon AVR Audio PWM Low Pass Filter R44 C14 RCA2 AUDIO MONO 1K 10uF RCAIFEM amp C set 3db point f3db 1 2 PFR C
137. 1 lt T gt USB GPIO 2 CL USB GPIO 3 lt T gt UsB 4 2 3 1 USB_3V30UT USB DTR Reset Signal Conditioning lt I gt RESn C16 o1 USB_DTRn 2N3904 USB_5VOUT USB_RTSn OtuF R11 EEE 330 Referring to Figure 6 1 this is the USB to serial converter designed into the Chameleon AVR Its based on a FTDI FT232R USB to serial UART chip The chip works by converting a USB packet stream into a standard serial port signal set Of course the other end of the USB cable has to be plugged in a PC running the custom FTDI USB drivers that create virtual COM ports from the operating system s perspective but other than that This magical little chip let s us talk serial to the Chameleon with a USB port FTDI has written drivers for Windows Linux and Mac OS X so these chips are quite popular since its very difficult to find a real DB9 RS 232 serial port on a PC anymore You can take a look at the data sheet for the chip here DVD ROM CHAM_AVR DOCS DATASHEETS DS_FT232R pdf Considering all that let s take a quick look at the design The USB cable from the PC plugs into H1 which is a Mini B USB header the USB packets are converted into a serial stream by the chip and the standard RS 232 signals are generated by the chip We are only interested in TX RX and DTR data terminal ready which is used to reset the Propeller and AVR by both the Propeller tool and Arduino tools respectively The TX RX s
138. 10 0 VGA GRAPHICS HARDWARE nna ruina anao an sa os Era E AE Sapa sa Esa UE ESPERA RR 36 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 10 1 M 37 10 2 VGA Hardware HITOUCUE RR 38 10 3 Sisal uultu Tr MO 41 10 371 VGA Horizont l Limlng iter 42 102352 VGA Vertical TEE lee 42 10 3 3 Generating the Active VGA Video iuo uu I naa bh Ma UR Ie OUR HO Pee dE NER Raise De ede cie 43 11 0 NTSC PAL COMPOSITE VIDEO HARDWARE 44 11 1 Video Hardware 44 11 2 Introduction to NTSC Video R 45 11 2 1 Interlaced versus Progressive 45 11 2 2 Video Formats and Interfaces eene nennen seen nre enters entere nnne sienten eene ee nnne nennen eene 47 11 2 3 Composite Color Video Blanking Sync 47 11 2 4 Color Encodine Ue E 49 11 25 P t ng w ATI Reo UL ope 49 11 2 6 Generating B W Video An T Adde Oe
139. 119 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 58 The Hello World program loaded into the Arduino tool ham_avr_hello_world Arduino 0017 DER it Sketch Tools Hel Copyright Nurve Networks LLC 2009 Filename CHAM AVR HELLO WORLD 01 Original Author Andre LaMothe Last Modified 9 NT Description NTS __AVR_ATmega328P___ __AVR_ATmegal68 define _ AVR ATnega328P include everything finclude lt stdint h gt include lt stdio h gt include lt stdlib h gt include lt string h gt finclude lt ctype h gt include lt avr eeprom h gt finclude lt avr io h gt finclude avr sleep h lt Go ahead and scroll thru the program bit its very short Once you are done now its time to finally download it to the this will both compile and tell us if there are any errors as well as Chameleon Simply press the Compile button show the final size The Arduino tool has terrible user diagnostics While compiling or downloading it just WARNING sits there without any updates in the text output area at the bottom of the screen or EE status This is quite disturbing so just hold tight while the program compiles and downloads it could take moments When the compilation is complete there should be no errors you should see the following text appear in the black text output window at the bottom of the tool Binary sketch size 1034 bytes of a 30720
140. 15 5 a is really just a charging circuit and as we send these pulses to it the circuit charges a bit then another pulse comes and it charges a bit more when a pulse doesn t come or the duty cycle is smaller then the RC circuit discharges so the PWM modulated pulse train gets turned into a signal by an averaging process and looks like a stair step where you can see the averaging period superimposed on the signal Figure 14 5 b shows an example of this Here we see a PWM signal running at frequency 10 and a sine wave being synthesized at 1KHz before and after the averaging circuit We will get more into the programming of PWM when we discuss sound generation in the programming section of the manual But for now realize that the low pass filter LPF that the Chameleon AVR uses on the audio circuit acts as a LPF as well as an averaging circuit for PWM so it has two uses pretty cool 14 1 3 1 Selecting the Filtering Frequency Also there are a couple of concerns with the actual values of the LPF so that you don t get too much noise Noise is going to come from the PWM frequency itself For example say you use a PWM frequency of 1MHz then your filter obviously needs to cut this frequency out but it also needs to cut in at the highest frequency you plan to synthesis for example if you plan to have sounds all the way up to CD quality at 44KHz then you might set the 3dB point at 50KHz for example Also we are using an passive or inactive s
141. 15200 slow down to 57600 38400 if you have trouble transmit and receive buffer constants define UART TX BUFF SIZE define UART BUFF SIZE 32 The defines are trivial simply a constant for a convenient baud rate as well as the size of the circular buffers You can make these any size you wish but memory is at a premium so keep it in mind If you are going to be using a lot of serial communications and know you are going to send large strings or receive large strings and not be able to interrogate the buffer functions then you might want to increase the buffers to 64 128 256 etc But for now 32 32 seems to work find in all examples Next are all the global data structures and variables used by the API functions global that holds UART current baud rate extern int g baudrate receiver and transmitter head and tail indices for circular buffers extern int uart rx head extern int g uart rx tail extern int g uart tx head extern int g uart tx tail buffers for uart interrupt driver A extern UCHAR uart buffer rx UART BUFF SIZE receiver buffer for incoming characters extern UCHAR uart buffer tx UART BUFF SIZE transmit buffer for outgoing characters First we have a global baudrate pointers to the circular buffers and finally the buffers themselves These are all declared in the C file of course these are simply the external references The API listing for the
142. 2 DRV 112 spin Propeller local port specific commands these are handled locally in SPIN on the interface driver s C PORT_CMD_SETDIR sets the 8 bit I O pin directions for the port 1 output O input DIRA 7 0 g_data PORT_CMD_READ reads the 8 bit port pins outputs are don t cares g spi result INA 7 0 4 FF data is now in g spi result client must perform a general READ CMD to get it back PORT CMD WRITE writes the 8 bit port pins port pins set to input ignore data OUTA 7 0 g data As you can see there are 3 commands set direction read and write These are directly interfaced to SPIN native functions and port I O control The AVR side API is nothing more than 3 commands to set the direction read and write The name of the API file is CHAM AVR PROP PORT DRV V010 c Contains the API functions for the Propeller local port functionality And once again this functionality is available in all versions of the main Propeller driver Default and 2 The Propeller Local Port module header CHAM AVR PROP PORT DRV VO010 h has nothing in it but the prototypes for the API functions so nothing to show you there The API listing for the Propeller Local Port module CHAM AVR PROP PORT DRV 010 is listed in Table 26 1 categorized by functionality Table 26 1 Propeller Local Port module API functions listing Function Name
143. 39 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 10 3 VGA female header pin out HD15 RED Video BLACK GREEN Video BLACK WHITE 3 BLUE Video BROWN 4 RESERVED BROWN WHITE 5 GROUND RED SHIELD 6 RED Ground ORANGE 7 GREEN Ground YELLOW 8 BLUE Ground MINT GREEN 9 NC NC Pin Function Color Code most manufactures 1 2 GROUND GREEN IDO Ground BLUE 10 11 12 101 NC PURPLE 13 VSYNC GREY 14 HSYNC WHITE 15 NC SHRIMP 40 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The VGA standard is much easier to understand that the NTSC standard is in fact using a visual explanation Figure 10 3 is usually all people need to see but still there are some gotcha s so we are going to discuss them as well in the brief primer To start the actual important signals you need to generate for VGA are referring to Table 10 3 are Red Green and Blue video as well as Hsync and Vsync The R G B signals are analog voltages representing the instantaneous intensity of any particular channel and range from 0 1 0V the Hsync and Vsync are simply TTL signals usually active LOW but these can be inverted on most monitors where a logic LOW is sync and a logic HIGH is no sync Now let s look more closely at the signal itself Figure 10 3 The VGA timing specifications A VGA 640x480 Layout 640 pixels 0 0 480 pixels
144. 6 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit include you need this one always include you need this always include needed for NTSC driver include needed for VGA driver EFINES AND S T T T T T E T T T define CPU frequency in MHz here if not defined in Makefile or other includes compiler will throw a warning ignore ifndef F_CPU define F_CPU 16000000UL 28636360UL 14318180UL 21477270 UL endif LLL UENEN LL B LL LI ULL ML P P P P LL M gl LH gg gL HB initialize and set SPI rate SPI Init SPI DEFAULT RATE clear screens NTSC Clearscreen ClearScreen enter infinite loop while 1 print on NTSC terminal screen NTSC Color 0 NTSC Term Print Hello world ys print on VGA terminal screen Color 0 Term Print Hello world ys slow things down a bit so we can read the text delay 5 10 end while end main Take note of the highlight header files and the main function now take a look at the Arduino version its nearly the same with a slight syntactic change to the header files and main has been replaced with setup and loop Arduino Sketch Version LEE INCLUDES M MEM Mg PC CB M M M LL B B MM LL LL B Bl ll E P P B
145. 7 sharp 622 659 698 sharp 740 784 flat 831 880 0 20mmmocoouu The array scale holds the scale from middle A at 440Hz then from this we can compute any octave or half notes etc which are used to generate chords There are all kinds of chords and all kinds of theory about what sounds good and doesn t One method of computing chords is to play 2 3 notes that are related to each other by adjacent notes from the base note There are formulas you can use to calculate these notes and simply experiment to see what sounds good dissonant resonant or just plain bad The program plays a number of chords in an increasing fashion then in decreasing Below is a copy of the increasing code so you can see the computation of the chord frequencies as well as the sound API calls to play the actual chord NTSC Term Print Going up NTSC Term Char OxOD play the scale up for note 0 note NUM NOTES note compute chord to play play these an octave above sprintf sbuffer Playing Chord d d d Cint chord freq 1 Cint chord freq 2 Cint chord freq 3 play the notes we have a freq limit of 2049 Hz with the current API interface the driver can do whatever you want though so you will have to create new messages and a 16 bit format if you want to play higher frequencies Sound Play 0 Cint chord freq 1 1 Sound Play 1 Cint chord freq 2 1 Sound Play 2 Cint chord freq 3 1
146. 8 Arduino Pro or Pro Mini 3 3V 8 MHz w 168 Arduino NG or older w 168 Arduino NG or older w ATmega8 Next we need to make sure that the Arduino tool is using the proper serial port You should have noted this earlier when you plugged the USB cable into the Chameleon and the PC recognized the FTDI USB to serial chip If you haven t done then plug the USB cable in and go thru the installation of the FTDI drivers Then take not in the Control Panel where the new USB serial port was installed you need that information for this step Setting the COM Port To set the Arduino tool s COM port simply select from the main menu Tools Serial Port as shown in Figure 15 56 and select the proper serial port 117 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 56 Selecting the serial port that the USB serial chip is connected to sketch_sep24a Arduino 0017 File Edit Sketch Help Auto Format Ctrl T Archive Sketch Fix Encoding amp Reload Board Serial Port 7 COM2 Burn Bootloader comes COM26 v COM46 15 2 3 2 Loading the Hello World Sketch A sketch is like a project For each sketch there is a single directory and in that directory there is a main file with the extension PDE This is your working main C C files Additionally there is a directory in each sketch named applet This directory contains all the source file
147. AC with the resistance values chosen and shown above in the figure Table 11 1 shows the signal relationship to the Propeller signals Table 11 1 The Video Hardware Prop Port Bit Chameleon Signal Description ___________ O 12 VIDEO_0 Bit 0 of the overall composite video signal contains both LUMA and CHROMA P13 VIDEO 1 Bit 1 of the overall composite video signal contains both LUMA and CHROMA P14 VIDEO 2 Bit 2 of the overall composite video signal contains both LUMA and CHROMA P15 AURAL 0 Single aural audio bit used when transmitting broadcast video There are 3 bits of D A conversion for the overall composite video signal VIDEO 0 3 thus giving a total of 8 different overall LUMA values however a number of them at the low scale of the range must be used to jump from sync level 0 0V to black level 0 25 0 3V For example if the entire D A range is 1 0V then 0 3 1 0 30 30 of 7 is 2 thus the 3 bit value of 0 is sync while the 4 bit value of 2 is black leaving us with only the values 3 7 or 5 different intensity levels Additionally since the chroma signal rides on top of the luma signal there is yet another constraint since the chroma need to have a peak to peak of at least 2 units this in fact we can only drive the video signal to a value of 6 so the Propeller s chroma hardware can twiddle the luma 1 to obtain the chroma However in fact most drivers simply use 0 as sync 1 as black then values 1 6 a
148. API functions are designed for the specific drivers running on the default Propeller drivers If you change or modify drivers on the Propeller side chances are these new drivers will have different functionality and you will want to re write a new high level wrapper API for the driver in question However hope that you use them as starting points only to develop your own API functions and drivers that are much more optimized and complete On the other hand have spent a good deal of time trying to develop a base set of API libraries to get you started so that you can do everything from graphics and sound to UART communications with the PC Table 17 1 lists all the API library modules we have developed for you to jumpstart your development and exploration of the Chameleon AVR and the AVR processor itself 137 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 17 1 The Chameleon AVR source level library modules at a glance Library Module Name Description a a ee eae System Level Library Module 11 21 ee Oe ee ee CHAM AVR SYSTEM V010 c h System level utility functions and configuration ___ a a A a a _ NN High Level Graphics Module 23 ee et 010 Functions to take advantage of the graphics tile engine that runs under the default2 drivers e se ee NTSC Text and Tile Graphics Module Cn E CHAM A
149. AVR ATMega 168 328 on each Arduino board there is no extra hardware to do anything So looked deeper and found out the Arduino guys came to the same conclusion did about embedded system programming its too hard The tool chains area nightmare installation has too many steps and its just too complicated for newbie s that just want to play with something So what they did was not concentrate on hardware but concentrate on software They took the AVR tool GNU GCC tool chain and covered it up with a Java application Therefore from your perspective as a programmer you don t need to know anything about AVRStudio GNU GCC WinAVR etc All you need to know is how to type in the 11 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Arduino text editor and press a couple buttons Now programming AVRs and PICs is a challenge as well You normally need an ISP in circuit programmer and to use another tool Thus you first write your code with AVRStudio compile it then you have a binary that you download with yet another software tool and a physical ISP programmer This again is a nightmare and a mess for newbies so the Arduino guys also integrated this into the tool and supplied a bootloader on the AVR chips their Arduino s ship with therefore all you need is a serial connection to the AVR chip on the Arduino hardware and the Arduino tool can initiate communications and download to the FLASH memory Therefore with a s
150. All Keys to Make keyboard responds by sending an ACK clearing its output buffer and setting the key type to Make Scanning continues if scanning was enabled This command may be sent while using any Scan Code Set but only has effect when Scan Code Set 3 is in use PS 2 Set All Keys to Typematic Make Break keyboard responds by sending an ACK clearing its output buffer and setting the key type to Typematic Make Break Scanning continues if scanning was enabled This command may be sent while using any Scan Code Set but only has effect when Scan Code Set 3 is in use PS 2 Set Key Type to Typematic keyboard responds by sending an ACK clearing its output buffer and then waiting for the key ID make code from Scan Code Set 3 The specified key type is then set to typematic This command may be sent while using any Scan Code Set but only has effect when Scan Code Set 3 is in use PS 2 Set Key Type to Make Break keyboard responds by sending an ACK clearing its output buffer and then waiting for the key ID make code from Scan Code Set 3 The specified key type is then set to Make Break This command may be sent while using any Scan Code Set but only has effect when Scan Code Set 3 is in use PS 2 Set Key Type to Make keyboard responds by sending an ACK clearing its output buffer and then waiting for the key ID make code from Scan Code Set 3 The specified key type is then set to Make This command may be sent while using any Scan Code Set but only
151. BASE ID writes screen width value 0 16 tiles 1 32 tiles 2 64 tiles etc define GFX SRC ADDR R 22 6 GFX BASE ID Reads 16 bit source address for GPU operations define GFX SRC ADDR 23 GPU GFX BASE ID Writes 16 bit source address for GPU operations define GFX DEST ADDR R 24 GPU GFX BASE ID Reads 16 bit destination address for GPU operations define GPU GFX DEST 25 6 GFX BASE ID Writes 16 bit destination address for GPU operations define GPU GFX NUM BYTES R 26 GPU GFX BASE ID Reads 16 bit number representing the number of bytes for GPU operation Sub Function define GFX NUM BYTES W 27 6 GFX BASE ID writes 16 bit number representing the number of bytes for a GPU operation Sub Function define GFX DATA R 28 6 GFX BASE ID Reads 16 bit data word uses for GPU operations or memory access operations define GPU GFX DATA 29 6 GFX BASE ID writes 16 bit data word uses for GPU operations or memory access operations define GPU GFX RAM PORT8 R 30 GPU GFX BASE ID Reads 8 bit data pointed to by the currently addressed memory location in the GPU pointed to by the src addr low hi After the operation the src addr ptr is incremented as per the GPU configuration define GPU GFX RAM PORT8 W 31 GPU GFX BASE ID Writes 8 bit data pointed to by the currently addressed memory location in the GPU pointed to by the
152. Begin the next black scanline En Step 4 Generate a vertical sync pulse with serrated inverted hsync pulses Video 0 0v for entire video line expect for BLACK during hsync pulse Output 6 blank lines with inverted hsync this will keep horizontal tracking and cause a vsync to occur 11 2 5 2 Line Construction Generating each line is a little more tricky that generating a frame since the real work must be done on each line The basic idea is that you must generate the video signal which controls the luma brightness the chroma color and synchronization all within the same signal This is accomplished by mimicking the signals you see in Figures 11 5 and 11 6 Each line consists of a total of 63 5 us where 52 6 us is actual video data and the other 10 9 us is sync and setup data However you can slightly alter them if you wish For example if you want to make the video portion of a line 50 us rather than 52 6 us then it will work since you can just stuff black into non active region however the more you alter the spec especially in terms of the length of the sync and color burst the higher the chances are that the signal will not work on some older or newer sets such as LCD and plasma with digital filtering To generate the actual video signal the Propeller chip gives you total control over the actual output voltage of the composite video line therefore you program the voltages as a function of time to create each video line u
153. C 60 3C lt 13 D CR 29 1D GS 45 2D 61 3D 14 0 30 1 46 2 62 gt 15 F SI 31 1F US 47 2F 63 3F ASCII Symbol ASCII Symbol ASCII Symbol ASCII Symbol 64 40 80 50 96 60 112 70 65 41 81 51 97 61 113 71 66 42 B 82 52 R 98 62 b 114 72 q 67 43 C 83 53 S 99 63 115 73 68 44 84 54 T 100 64 d 116 74 5 69 45 85 55 U 101 65 e 117 75 t 70 46 F 86 56 V 102 66 f 118 76 u 71 47 G 87 57 103 67 9 119 77 x 72 48 H 88 58 X 104 68 h 120 78 w 73 49 89 59 Y 105 69 i 121 79 X 74 4A J 90 5A Z 106 6A j 122 7A y 75 4B K 91 5B 107 6B k 123 7B 2 76 4C L 92 5C 108 6C 124 7 77 4D M 93 5D 109 6D m 125 7D 78 4 94 5E 4 110 6E n 126 7E 79 4F 95 111 6F 127 7F z Decimal Hex Octal Binary Table Dec Hex Oct Bin Dec Hex Oct Bin Dec Hex Oct Bin Dec Hex Oct Bin 0 0 000 00000000 16 10 020 00010000 32 20 040 00100000 48 30 060 00110000 1 1 001 00000001 17 11 021 00010001 33 21 041 00100001 49 31 061 00110001 2 2 002 00000010 18 12 022 00010010 34 22 042 00100010 50 32 062 00110010 3 3 003 00000011 19 13 023 00010011 35 23 043 00100011 51 33 063 00110011 4 4 004 00000100 20 14 024 00010100 36 24 044 00100100 52 34 064 00110100 5 5 005 00000101 21 15 025 00010101 37 25 045 00100101 53 35 065 00110101 6 6 006 00000110 22 16 026 00010110 38 26 046 00100110 54 36 066 00110110 7 007 00000111 23 17 027 00010111 39 27 047 00100111 55 37 067 00110111 8 8
154. C header file named CHAM AVR GFX DRV VO010 h and see 180 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit what s inside If you look inside the file you will see nothing other than a conditional compilation section and the prototypes for the function API so where are all the register interface defines Well remember we have to keep all the SPI commands in a single place so the register interface are actually message ids for the SPI messaging system Thus if you open up CHAM_AVR_TWI_SPI_DRV_V010 h scroll down then you will get to the section with the register interface messages for the GFX driver itself they are advanced GFX commands for GFX tile engine define GPU GFX BASE 192 starting id for GFX commands to keep them away from normal command set define GFX NUM COMMANDS 37 number of GFX commands define GPU GFX SUBFUNC STATUS 0 GPU GFX BASE ID Reads the status of the GPU Writes the GPU Sub Function register and issues a high level command like copy fill etc define GPU GFX SUBFUNC STATUS W 1 GPU GFX BASE ID Writes status of the GPU writes the GPU Sub Function register and issues a high level command like copy fill etc sub function constants that are executed when the GPU GFX SUBFUNC STATUS W command is issued define GPU GFX SUBFUNC COPYMEM16 0 Copies numbytes from src gt dest in wordsize chunks define GPU GFX SUBF
155. C listening to USB serial port An X Modem protocol file transfer Data is sent a block at a time Each block consists of header information along with the 128 byte data Serial settings for Chameleon FLASH Memory communications N81 2400 baud Missi 1 XModem receive to FLASH 2 Dump FLASH to screen Receiver Chameleon controls the flow of data from the sender PC FLASH demo running on Chameleon Simple X Modem downloader X Modem Protocol If you have never heard about X modem protocol its probably the most widely used modem to modem download protocol on the planet and still widely used There are a number of variants that have been developed over the years such as X modem 1K X Modem CRC Y Modem Z Modem and so forth but fundamentally they all work the same way the uploader sends packets usually 128 256 bytes to the downloader until the entire file has been sent The uploader is typically the PC and the downloader is typically another PC that needs the file or a stand alone device X Modem protocol is rather simple but a bit tricky to implement robustly since there are lots of potential forks in the communications logic that have to do with packets being lost errors resending timeouts etc If you have ever written and communications protocols you really understand how complex getting them to work robustly it You can read about X Modem protocol by Googling for it but h
156. CMD_RESET_DELTA 31 resets the mouse deltas MOUSE_CMD_BUTTONS 32 returns the mouse buttons encoded as a bit vector MOUSE_CMD_START 33 starts the mouse driver loads a COG with it etc MOUSE_CMD_STOP 34 stops the mouse driver unloads the COG its running MOUSE CMD PRESENT 35 determines if mouse is present and returns type of mouse general data readback commands READ 36 sound commands SND CMD PLAYSOUNDFM 40 plays a sound on a channel with the sent frequency at 90 volume SND CMD STOPSOUND 41 stops the sound of the sent channel SND_CMD_STOPALLSOUNDS 42 stops all channels SND SETFREQ 43 sets the frequency of a playing sound channel SND CMD SETVOLUME 44 sets the volume of the playing sound channel SND_CMD_RELEASESOUND 45 for sounds with infinite duration releases the sound and it enters the release portion of ADSR envelope propeller local 8 bit port I O commands PORT CMD SETDIR 48 sets the 8 bit I O pin directions for the port 1 output O input PORT CMD READ 49 reads the 8 bit port pins outputs are don t cares PORT CMD WRITE 50 writes the 8 bit port pins port pins set to input ignore data register access commands Propeller registers for the SPI driver cog can accessed ONLY but the user can leverage the counters and even the video hardware if he wishes most users will only 1 play with the counters and route outputs inputs to from the Propeller local
157. D APPS 0 2F E0 F0 2F 71 71 B a ate Z lt n us u s iB ENTER sa ro KPO 70 70 ee 1 69 69 U FO 05 KP 2 72 72 x 1 T x KP 3 7A F0 7A ip roirl 04 roo 6B 6B x 22 Fo 22 r oc roo ws 73 73 35 Fo 35 rs roo 6 74 74 7 6C 6C 0 45 FO 83 KP 8 75 0 75 54 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 1 16 F0 16 F8 FO 0A KP 9 7 F0 7D 2 1E FO 1E F9 01 F0 01 5B FO 5B 3 26 20 26 F10 09 09 ac FO 4C 4 25 20 25 F11 78 F0 78 52 52 5 2E FO 2E F12 07 FO 07 41 FO 41 EO FO 6 36 F0 36 7C EO 49 F0 49 i F0 12 7 3D 3D SCROLL 7E 7 4A FO 4A E1 14 77 8 3E F0 3E PAUSE E1 F0 14 F0 77 The keyboard hardware interface is either an old style male 5 pin DIN or a new PS 2 male 6 pin mini DIN connector The 6 pin mini DIN s pin out is shown in Figure 12 2 referenced looking at the computer s female side where you plug the keyboard into notice the staggering of the pin numbering Figure 12 2 Female PS 2 6 Pin Mini Din Connector at
158. DRV_V010 c Main C file source for VGA module CHAM_AVR_VGA_DRV_V010 h Header file for VGA module ARDUINO TIP As you will see the VGA terminal mode functionality is nearly identical to the NTSC This is by design so when you are developing terminal applications that print out to the NTSC VGA screens basic information you don t have to worry about details each system is like a mini VT100 terminal with limited abilities but at least easy to work with 21 1 Header File Contents Overview The VGA API module header CHAM_VGA_DRV_V010 h has no globals or defines as of yet nothing more than the function prototypes 21 2 API Listing Reference The API listing for the VGA module CHAM_VGA_DRV_V010 c is listed in Table 21 1 categorized by functionality Table 21 1 VGA module API functions listing Function Name Description Initialization int VGA_ClearScreen void Clears the VGA screen E int _GetXY int x int Gets the current cursor position on the terminal int VGA SetXY int x int y Sets the current position on the terminal pee _ int VGA_Term_Char char ch Prints a single character to the terminal at the current cursor position int VGA Term Print char string Prints a NULL terminated string to the terminal int VGA Color int col Sets the color of the text 172 2009 NURVE NETWORKS LLC Exploring the Chameleon A
159. Delay_Clocks long count Delays for the requesting number of processor clocks use _delay_us and delay ms for time based delays these are out of AVRLibc void delay s int sec Delays for the requested number of seconds E 1 long atoi2 char string Converts binary decimal and hex formatted strings to integer 143 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit System Reset int Reset_Master void Resets the AVR chip int Reset_Prop void Resets the Propeller chip remotely Note The time functions are currently approximations and need updating to be more accurate Please use AVRLibc functions instead 17 1 3 API Functional Declarations The following lists each function a description comments and example usage of the function Function Prototype void Delay_Clocks long count Description Delay_Clocks waits the specificied number of processor clocks then returns The AVR library has similar timing functions as well Note it is recommend AVR Libc functions are used instead Example s Wait for 1000 clocks Delay ClocksC 1000 Function Prototype void delay s int sec Description X delay s waits the specificied number of processor clocks then returns The AVR Libc library has similar timing functions as well Note it is recommend Libc functions are used instead Example s Wait 60 seconds _delay_s 60
160. Description int PropPort_SetDir int dirbits Sets the port bit direction bits individually int PropPort Read void Read the port input buffer int PropPort Write int data8 Writes to the port output buffer Note When reading or writing I O pins that aren t set the proper direction will have invalid data on them thus if you have set the lower 4 bits as inputs and read the port only count on the lower 4 bits having valid data Similarly when writing data only pins that are outputs will drive current The only will sink it as inputs Thus any data written to them is ignored as is should be 203 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The following lists each function a description comments and example usage of the function Function Prototype int PropPort_SetDir int dirbits Description sets the direction of the 8 I O bits on the Propeller local port 1 output O input eg 11110000 out out out out in in in in Physically on the port header bit 0 is on the right bit 7 on the left so its LSB to MSB right to left Returns 1 Example s Set the lower 4 bits to outputs upper 4 bits to inputs PropPort SetDir OxOF Function Prototype int PropPort Read void Description Read reads the pins of the input port that are set as inputs pins set as outputs are invalid Returns the pin data Example s Set the port to
161. Development Kit This is a light hearted non censored no holds barred manual If you find technical errors or have comments simply write them down in a and please send them to us at support nurve net or post on our forums and we will continue to merge them into this working document The document contains two main sections The Hardware Manual This is a fast and furious circuit description of the Chameleon AVR 8 Bit Board s dual processor implementation around the Atmel AVR 328P and Parallax Propeller processors The Atmel 328P chip is 8 bit single cycle instruction in most cases supporting 16 bit math and multiplication It has 32K of FLASH and 2K of SRAM We are running it at 16 MHz on the Chameleon but its capable of running 20 MHz nominally and beyond when over clocked The Parallax Propeller chip is used for media processing and runs at 80Mhz per core with 8 cores Each instruction takes 4 clocks thus the Propeller runs at 20 MIPS per core nominally It has 32K of SRAM and 32K ROM Programming Manual This is the nitty gritty of the manual and has examples of programming graphics sound keyboard mice I O etc and explains how the processors work together along with their various tool chains The Chameleon PIC 16 Bit is very similar to the Chameleon AVR 8 Bit In fact the Ney pay Processor was removed from my originally design and replaced by the PIC 16 and the interfaced re connected so if you learn o
162. E 35 The Propeller Tool v1 05 5 Installer 3 Welcome to the Propeller Tool v1 05 5 installer This program will allow you to modify repair or remove the Propeller Tool 1 05 5 To continue click Next PROPELLER by Parallax Inc m FES Step 2 The installation type should be displayed next as shown below in Figure 15 60 select Complete install click lt gt Figure 15 60 Selection of Complete install y The Propeller Tool v1 05 5 Installer Please select a setup type OR 18 All program features will be installed Requires the most disk space O Custom Choose which program features you want installed and where they will be installed Recommended for advanced users Setup Type Choose the setup type that best suits your needs Step 3 VERY IMPORTANT The Propeller tool IDE communicates to the Chameleon AVR using a USB cable and driver this USB driver must be installed The next dialog shown below in Figure 15 61 shoul d have the Automatically Install Update driver selected so the driver is installed Check this box and click lt NEXT gt 122 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 61 Automatic USB driver installation dialog y The Propeller Tool v1 05 5 Installer x Install Optional Driver L Choose optional driver installation This program ca
163. ED 0 91 this data is then placed into spi buffer for transport back to client byte address to read 0 3 is in g_data g_spi_result g_reg_in_buffer byte g_data SYS_RESET resets the prop reboot end case commands set result and set dispatcher to idle spi finishcmd g_spi_result end main lo That s it Save the file as cham_default2_drv_112_modified spin and we are done with this portion In fact you can flash it down to the Propeller and every single program will still work the same We have added messages and features but we have NOT made anything incompatible or re used message ids for something else This is very important to keep in mind so you do not damage a driver and make it incompatible with other software 31 1 2 Adding AVR Support at the Client Master Side At this point we have new messages added to the Propeller driver along with the message handler code If you haven t done so compile and download the new driver to the Propeller chip on the Chameleon whatever application you have running on the Chameleon should work exactly the same Now what we need is to add support on the client master side or write a program that sends the messages to the Propeller Rather than go into the SPI driver code header decided to just write a stand alone program that blinks the LED started with the port b
164. ED BY NURVE NETWORKS LLC INC TO ITS CUSTOMERS FOR THEIR USE ONLY AS SET FORTH BELOW IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT DO NOT USE THE SOFTWARE OR HARDWARE USING ANY PART OF THE SOFTWARE OR HARDWARE INDICATES THAT YOU ACCEPT THESE TERMS GRANT OF LICENSE NURVE NETWORKS LLC the Licensor grants to you this personal limited non exclusive non transferable non assignable license solely to use in a single copy of the Licensed Works on a single computer for use by a single concurrent user only and solely provided that you adhere to all of the terms and conditions of this Agreement The foregoing is an express limited use license and not an assignment sale or other transfer of the Licensed Works or any Intellectual Property Rights of Licensor ASSENT By opening the files and or packaging containing this software and or hardware you agree that this Agreement is a legally binding and valid contract agree to abide by the intellectual property laws and all of the terms and conditions of this Agreement and further agree to take all necessary steps to ensure that the terms and conditions of this Agreement are not violated by any person or entity under your control or in your service OWNERSHIP OF SOFTWARE AND HARDWARE The Licensor and or its affiliates or subsidiaries own certain rights that may exist from time to time in this or any other jurisdiction whether foreign or domestic under patent law copyright law publici
165. ETWORKS LLC Exploring the Chameleon AVR 8 Bit begin x mode state machine switch xstate case XSTATE_INIT initialize all the variables and data structures for the xmodem transmission if DEBUG_XMODEM gt 2 NTSC_Term_Print XSTATE_INIT NTSC Term Char OxOD endif reset bytes read counter etc xbytes_read 0 transition to NAK state to initiate xmode transfer xstate XSTATE_SEND_NAK break case XSTATE_SEND_NAK start the transmission or resend current packet if DEBUG_XMODEM gt 2 NTSC Term Print XSTATE SEND NTSC Term Char OxOD NTSC Term Print S NAK NTSC Term Char OxOD endif send NAK and wait UART putc CHR_NAK wait for packet xstate XSTATE_RECEIVE_PACKET break case XSTATE_RECEIVE_PACKET receives the packet if DEBUG_XMODEM gt 2 NTSC_Term_Print XSTATE_RECEIVE_PACKET NTSC Term Char OxOD endif wait for result while 1 ch UART_getcQ if ch CHR_SOH ch CHR_EOT break end while if DEBUG_XMODEM gt 2 sprintf sbuffer Looking for SOT EOT d c ch OxOD NTSC_Term_Print sbuffer endif we have the first byte test for SOH or EOT if ch CHR_SOH if DEBUG_XMODEM gt 2 NTSC Term Print R SOH NTSC Term Char OxOD end if SOH else if ch CHR EOT endif if DEBUG_XMODEM gt 2 NTSC Term Print R EOT NTSC Term Char OxOD endif x
166. I library module CHAM AVR SYSTEM VO010 c h The main SPI API library module CHAM AVR TWI SPI V010 c h The keyboard API library module CHAM AVR KEYBOARD V010 c h The mouse API library module CHAM AVR MOUSE DRV 010 The NTSC VGA GFX driver or all of them And any other ancillary drivers keyboard mouse etc All the required files can of course be found in the Source directory on the DVD which you should have already copied onto your hard drive located here DVD ROM CHAM AVR SOURCE AVRStudio TIP The Arduino version will be in Sketch form already so all you need to do is load the Sketch in and upload and you re in business 30 1 1 Keyboard Demo This demo uses the keyboard API to communicate with a local PS 2 keyboard plugged into the PS 2 port via the Propeller s keyboard driver Make sure to plug your keyboard into the Chameleon and get a good connection and make sure the lt 1 etc keys are released and not in the down position The demo prints keys on the screen as you hit them along with their codes Also the demo has a little bit of fun code it has a little password finder The program has a state machine that is hunting for the token morpheous from the movie The Matrix if you type this in lower case the program will print something out Figure 30 1 shows the demo in action 225 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 3
167. IGH or a LOW but to set the CLOCK into a tristate or input mode so the keyboard can control it This puts the keyboard into the receiver state Step 4 Write data Now the keyboard will generate a clock signal on the CLOCK line you sample the DATA line when the CLOCK line is HIGH and send it The host program should serialize the command data explained momentarily made up of 8 bits a parity bit and a stop bit for a total of 11 bits Step 5 End transmission Once the last data bit is sent then the parity odd parity and stop bit is sent then the host drives the DATA line Stop bit and releases the DATA line 12 1 4 Keyboard Commands Table 10 4 illustrates some of the commands one can send to a generic keyboard based on the 8042 keyboard controller originally in the IBM PC spec This table is not exhaustive and only a reference many keyboards don t follow the commands 100 and or have other commands so be weary of the commands Table 12 4 Keyboard Commands Code Description ED Set Reset Mode Indicators keyboard responds with ACK then waits for a following option byte When the option byte is received the keyboard again ACK s and then sets the LED s accordingly Scanning is resumed if scanning was enabled If another command is received instead of the option byte high bit set on this command is terminated Hardware defaults to these indicators turned off 17 3121110 Keyboard Status Indicator Option Byte
168. IP package in the Chameleon Figure 1 4 shows the packaging and pin out of the chip The AVR 328P was designed as a general purpose high performance microcontroller with an 8 bit data path single clock execution on many instructions as well as support for 16 bit operations and built in multiply instructions The chip has a large FLASH memory of 32K Bytes but a smaller 2K Byte SRAM which makes a lot of RAM intensive applications challenging however the Chameleon is designed for control applications and 2K of RAM should be more than enough for anything you need Moreover the 328P has 2x the amount of FLASH as the 168 which successfully was used in thousands if not tens of thousands of Ardunios and everyone did just fine For complete details on the processor please review the datasheet located on the DVD ROM here DVD ROM cham_avr docs datasheets ATMega48 88 168 328 doc8161 pdf Table 1 2 below shows the various differences between the 48 88 168 and 328 variants for reference Additionally there is a useful EEPROM memory as well that can be used as a little disk drive or memory storage for whatever purposes Of 19 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit course the AVR 328P allows re writing to the FLASH as well so unused portions of FLASH can be used for storage however it s not ideal to constantly re write FLASH since there is a limit to the number of times it can be re written 100 000 give or take A
169. ISING OUT OF OR IN CONNECTION WITH THE USE OF THE LICENSED WORKS SOME JURISDICTIONS PROHIBIT THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE ABOVE LIMITATIONS MAY NOT APPLY TO YOU THESE LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY SEVERABILITY In the event any provision of this License Agreement is found to be invalid illegal or unenforceable the validity legality and enforceability of any of the remaining provisions shall not in any way be affected or impaired and a valid legal and enforceable provision of similar intent and economic impact shall be substituted therefore ENTIRE AGREEMENT This License Agreement sets forth the entire understanding and agreement between you and NURVE NETWORKS LLC supersedes all prior agreements whether written or oral with respect to the Software and may be amended only in a writing signed by both parties NURVE NETWORKS LLC 12724 Rush Creek Lane Austin TX 78732 support nurve net www xgamestation com 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit This document is valid with the following hardware software and firmware versions e CHAMELEON AVR 8 Bit Board Revision or greater Atmel AVR Studio 4 14 or greater Arduino Toolchain 0017 or greater for Windows Linux Mac OS X e Propeller IDE 1 26 or greater The information herein will usually apply to newer versions but may not apply
170. L P gg HL P P P Pg PP PP LT LUULLA Maus AVR Soft Reset N o 15 5 forG EU t QI un 3 while 0 These macros are primarily used to manipulate port bit set bits reset bits and write to the ports in a clean way Finally there is a convenient conversion from hex to decimal used by some of the conversion functions in the API Next are the defines and one very important definition is the processor speed 142 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit define CPU frequency in MHz here if not defined in Makefile define F_CPU 16000000UL This constant is special to many of the C libraries and it used as a compile time constant You might recall us setting this constant in the compiler build configuration setup However we are going to override that constant here making it the same as extra insurance to make sure that manually set this constant and then use it throughout the code base to set up timing calculations Although the Libc libraries have many standard types prefer to always create a few of my own that are compiler independent so know they work if port the code with this in mind the System module has a few types it declares basic unsigned types typedef unsigned short USHORT typedef unsigned short WORD typedef unsigned char BYTE typedef unsigned char UCHAR typedef unsigned long QUAD typedef unsigne
171. LC Exploring the Chameleon AVR 8 Bit Figure 15 53 the Arduino application at last sketch_sep24a Arduino 0017 it Sketch Tools Help Please read the Arduino documentation to learn all the features of the tool but its fairly straightforward It has a simple menu and a set of icons buttons Simply hover over each button see what they do From left to right they are Verify Compiles only to show errors Stop Stops the serial monitor New Sketch Creates a new sketch Open Sketch Opens a sketch Save Sketch Saves the current sketch Upload Sketch Compiles and uploads the sketch to the Chameleon Arduino Serial Monitor Launches a serial monitor terminal program Tab Controls Standard tab controls to add more views Ok so the first thing we need to do is make sure that the Arduino tool can find our sketchbook since it likes to place sketches in a different place If you recall we copied our sketchbook from the DVD ROM to the installation directory of the Arduino files refer to Figure 15 43 So first we need to tell the Arduino tool where to look To do this from the main menu select File Preferences which should bring up the dialog shown in Figure 15 54 below 115 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 54 The Arduino tool preferences dialog P Preferences etchbook location D development chameleon cham_avr source arduino Ed
172. NETWORKS LLC Exploring the Chameleon AVR 8 Bit The SPI and I2C module header CHAM_TWI_SPI_V010 h is very important since it houses the constants for the SPI communications interface to the Propeller so we are going to cover it in detail Let s begin with the defines that declare some of the hardware signals and constants used to represent and SPI interfaces TWI I2C defines 12 clock in Hz define TWI CLOCK 100000L initially set to 100Khz this is the default when you call TWI Init define SCL CLOCK TWI CLOCK define TWI PORT PORTC define TWI DDR PORTC define TWI SCLK PORTCO define TWI SDA PORTC1 SPI defines define SPI DDR DDRB define SPI PORT PORTB Zdefine SPI CS PORTB2 not used for spi addressing define SPI MOSI PORTB3 define SPI MISO PORTB4 define SPI SCLK PORTB5 define SPI CS DDR define SPI CS PORT PORTC define SPI CSO PORTC2 Zdefine SPI CS1 PORTC3 SPI rate bit settings define SPI FOSC 2 0b100 define SPI_FOSC_4 0b000 define SPI_FOSC_8 0b101 define SPI_FOSC_16 06001 define SPI_FOSC_32 0b110 define SPI_FOSC_64 0b010 define SPI_FOSC_128 0b011 The defines simply declare the I O ports signal bits and some timing constants For example CLOCK is a convenient constant to pass the initialization function covered later and the last set of constants are paraphrased from the hardware control register settings for the SPI speed settin
173. NTSC only text tile engine with support for terminal mode graphics with a tile resolution of 32x24 However the tile engine has extra features for more graphically oriented tile graphics and gaming applications Now keep in mind the GFX library functions are only supported with the Default2 driver s and only work on the NTSC screen wrote this driver myself to fit into a single Propeller core but give you some decent control of the tile maps bitmaps palettes scrolling and colors The tile engine has two layers of functionality The topmost layer is the console or terminal layer which acts like a simple VT100 terminal you print to it it scrolls you can clear the screen etc This functionality give you the base abilities to write applications that only need basic text output Moreover we selected the NTSC and VGA drivers in both the Default1 and Default2 example drivers to support exactly the same commands So applications written to drive the VGA terminal work exactly the same on Default Default2 or with a simple change of function calls from VGA to NTSC they will work on the NTSC screen That said if you want to do gaming tile based graphics right now as is you have to use the Default2 driver CHAM DEFAULT2 DRV 112 SPIN and only the NTSC screen output is supported But again the point is you can change the Propeller driver and re write it as you wish we simply give you a starting point to get going with So if you want to k
174. Number of Samples per Cycle Which in this example is 256 000 256 1000 Hz So you have two options either increase the PWM frequency or index into your sample table at larger intervals This problem along with the lack of precision can be handled by use of fixed point arithmetic and a little numerical trick We are going to scale all the math by 8 bits or in essence multiply by 256 then we are going to create two variables one called a phase accumulator PHASE and one called a phase increment PHASE INC Then instead of using count down algorithms we are going to simply add the phase increment to the phase accumulator and use the phase accumulator as an index into the sine table Therefore what we have done is turned out 256 element sine table into a virtual 256 256 65536 element sine table for math purposes to give us more accuracy for slower non integral waveforms as well as allow fast waveforms to index and skip elements in the look up table so a possible setup is something like this The Phase Accumulator 16 bit M MM E EAM b15 b8 used as index value Now we have two interesting properties first no matter what the index in the upper 8 bits can never exceed 255 so we can never go out of bounds of our table secondly we can put very small numbers into the phase accumulator via that phase increment variable So now the algorithm for PWM sound is simple Step 1 Run the PWM at the output frequency 256
175. Nurve Networks LLC Version 1 0 EXPLORING THE CHAMELEON AVR amp BiT USER MANUAL AND PROGRAMMING GUIDE Andre LaMothe www xgamestation com CHAMELEON AVR 8 Bit User Manual v1 0 Exploring the CHAMELEON AVR 8 Bit A Guide to Programming the CHAMELEON AVR 8 System Copyright 2009 Nurve Networks LLC Author Andre LaMothe Editor Technical Reviewer The Collective Printing 0001 ISBN Pending All rights reserved No part of this user manual shall be reproduced stored in a retrieval system or transmitted by any means electronic mechanical photocopying recording or otherwise without written permission from the publisher No patent liability is assumed with respect to the user of the information contained herein Although every precaution has been taken in the preparation of this user manual the publisher and authors assume no responsibility for errors or omissions Neither is any liability assumed for damages resulting from the use of the information contained herein Trademarks All terms mentioned in this user manual that are known to be trademarks or service marks have been appropriately capitalized Nurve Networks LLC cannot attest to the accuracy of this information Use of a term in this user manual should not be regarded as affecting the validity of any trademark or service mark Warning and Disclaimer Every effort has been made to make this user manual as complete and as ac
176. OFF position this is to the RIGHT Step 3 Plug your 9V DC wall adapter in and plug the 2 1mm connector into the bottom right power port on the Chameleon AVR If you do not have a power adapter then you can power the Chameleon AVR with the USB port Plug a USB mini B cable from you PC to your Chameleon AVR We suggest using a powered USB hub since the Chameleon will draw a lot of power Step 4 Insert the A V cable into the ORANGE video and WHITE audio port of the Chameleon AVR located top right of the board and then insert them into your NTSC Multi System TV s A V port Step 5 Plug a PS 2 compatible keyboard into the PS 2 port on the Chameleon top right Step 6 Turn the power ON by sliding the ON OFF switch to the LEFT then hit the Reset button as well next to the AVR chip 16 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Step 7 The demo will start immediately it s a little block pushing game called Crate it Use the keyboard arrow keys to move your character and push blocks around and move them to their resting positions usually on the opposite side of the screen You should see something like that shown in Figure 1 3 The actual program that is loaded into the AVR is located on your DVD here DVD ROM CHAM_AVR SOURCE CRATE_IT_V010 C The Arduino version is located in the Sketches directory on the DVD here DVD ROM CHAM_AVR TOOLS ARDUINO SKETCHES CHAM AVR CRATE IT Both versions
177. OURCE In the section below we will briefly cover each one of these libraries and the functions within them Before we get started let s take a look at the big picture illustrating all the components of the Chameleon AVR development suite of software and tools Figure 17 1 shows a system level architecture diagram of all the pieces involved 138 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 17 1 System level architecture of the Chameleon API and other library modules User Applications API Layer us APIs Running on Client Master AVR PIC Graphics API Input Device API Audio API FLASH Storage Application Layer SPI COMMs Driver Layer Mouse Keyboard NTSC Drivers VGA Drivers Driver Driver Audio Driver Drivers AVR PIC has direct connection to FLASH memory and does not need to go thru SPI driver on Propeller and message dispatcher Physical Hardware Layer Referring to the figure there are a lot of components to discuss First off the primary library that all C C programs use is the open source AVR Libc library that is part of the WinAVR install and is what the GNU GCC compiler uses as the base for all of the standard C library functions you are used to Therefore when you create a C C program for the Chameleon AVR and include say lt stdio h gt you are including functions from the AVR Libc installation Let s talk about this for a moment First embed
178. R which stood for War Operations Planned Response which was a computer running the entire USA missile system The computer wants to play a game and the story begins from there The whole point of this stroll down memory lane is that computers used to be magical devices that opened up whole worlds to people in a much more personal way than they do today And text based games used to be the conduit of much of this interaction with computers So even with a simple terminal program you can create something with the serial port that s kinda cool If you re interested in the computer used in the movie its too is very famous the IMSAI only a few left in operation Here s a link to more information CECLI http www imsai net movies wargames htm Ait fa EIL m 234 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Compiling and Running the Demo s There are two demos in this group the AVRStudio version and the Arduino version They are nearly identical except that for the AVRStudio version serial communications uses the CHAM AVR UART VO010 c h driver that we created but the Arduino version uses the Arduino serial class Nearly the same and could have used the Chameleon serial driver in the Arduino version but wanted to show you two fairly complex programs that use serial communications using each driver respectively Compiling and Running the AVRStudio Version Demo Version Description Serial UART demo illustr
179. R 8 Bit 11 2 4 Color Encoding Color information is superimposed on top of the luma brightness signal and is a sine wave with the colors identified by a specific phase difference between it and the color burst reference phase at the beginning of each scanline This can be seen in Figure 11 6 c which shows a horizontal scan line of color bars Figure 11 6 c Composite Video Waveform of the Color Bars Amplitude gt Saturation amount of color Phase Difference gt Hue color The amplitude of the modulation is proportional to the amount of color or saturation and the phase information denotes the tint or hue of the color The horizontal blanking portion contains the horizontal synchronizing pulse sync pulse as well as the color reference color burst located just after the rising edge of the sync pulse called the back porch It is important to note here that the horizontal blanking portion of the signal is positioned in time such that it is not visible on the display screen 11 2 5 Putting it All Together Generating a NTSC or PAL signal means controlling the signal into the TV such that all the timing specifications are met There are a number of aspects that must be taken into consideration to achieve this successfully However one important detail is that the video signal does not have to be perfect that is the timings can be slightly off per line per frame per color burst etc nevertheless the amount of s
180. R TWI SPI V010 h Header file for SPI and module ARDUINO TIP Before we discuss the module and functionality let s briefly review both SPI and protocols and their features For more detailed descriptions and tutorials on both protocols suggest reading the SPI and material in the AVR 328 data sheet located here DVD ROM CHAM AVR DOCS DATASHEETS ATMega48 88 168 328 doc8161 pdf Also there are numerous SPI and documents located on the DVD here DVD ROM CHAM AVR DOCS I2C DVD ROM CHAM_AVR DOCS SPI A few of which highly recommend you read specifically are DVD ROM CHAM_AVR DOCS SPI avr_spi_doc2585 pdf DVD ROM CHAM_AVR DOCS SPI avr_spi_master_doc1108 pdf DVD ROM CHAM AVR DOCS SPI SPI pdf DVD ROM CHAM_AVR DOCS I2C avr315 TWI I2C pdf DVD ROM CHAM_AVR DOCS 12 twi programming htm DVD ROM CHAM_AVR DOCS I2C I2C bus pdf These cover AVR specific SPI controls as well as general software implementations and some interesting examples of SPI controls But if you just want a quick overview read on The Atmel processors have mult functional 2 wire hardware devices inside them These devices can support as well as other protocols under programmability Thus instead of calling the interfaces Atmel calls them TWI for Two Wire Interfaces suspect it has something to do with licensing as well And to avoid licensing the
181. RV 010 CHAM AVR PROP PORT DRV 010 General Requirements Video port connected to NTSC TV monitors LED plugged into the Propeller Port leftmost 2 pins orientation doesn t matter Controls Required None Technical Overview This demo uses the Propeller Port API library to control the pins of the 8 bit local Propeller Port and blink an LED A couple cool things about the demo is that it toggles the pins on the I O header in pairs then thus no matter which way you have the LED nor what pins you have it plugged into it will actually blink or go bi color if you were lucky and got a bi color LED in your kit Below is the entire main loop of the program void main run over and over again initialize and set SPI rate SPI Init SPI DEFAULT RATE give Prop a moment before sending it commands the boot process is about a second if you like you can speed it up by removing the Prop driver s LED blink sequence in the driver or speed it up but commands that are sent before the Prop driver is done booting will be ignored therefore if you have a lot of set up work to do then you don t require a delay but if you jump right into commands then you need a good 1 5 2 second delay delay ms 2500 clear screens NTSC Clearscreen NTSC Color 0 set direction of prop port so we have all bits output Prop enter infinite loop Mu print on NTSC terminal screen NTSC
182. RVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Mouse Reading Ea cP int Mouse_Read gid_event_ptr mouse Reads the mouse message The following lists each function a description comments and example usage of the function Function Prototype int Mouse Load void Description Mouse Load loads the mouse driver up on a free Propeller core If the driver is already loaded this function has no effect Returns 1 Example s Load the mouse driver Mouse Load Function Prototype int Mouse Unload void Description Mouse Unload unloads the mouse driver freeing core on the Propeller Typically you will do this when you want to load the keyboard driver Returns 1 Example s Load the mouse driver Mouse Load Function Prototype int Mouse Read gid event ptr mouse Description Mouse Read reads the current mouse event from the driver In this case it only reads relative events and thus the data is in delta format You send a pointer to a gid event structure and the function will write the latest mouse deltas and button states into the structure Returns 1 Example s Read the mouse position and test if left button is down gid event mouse Mouse Read amp mouse test bit 3 left button if mouse buttons amp 0b01000 do stuff end if 202 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 26 0 P
183. SB cable plugged into the Chameleon AVR The FTDI chip device makes it easy to use serial communications from the PC Note that the Chameleons can be powered from the USB cable or an external 9V power supply OR both but USB cable is needed for serial communications always Figure 15 48 The Mini USB port on the Chameleon connects to the FTDI USB to Serial converter chip gt Serial Communications as well as Propeller Chip Programming 110 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Now if you computer recognizes the FTDI chip and has drivers it will load them automatically and install a virtual COMxx port into your system However if it doesn t you will need to install the FTDI drivers This is needed for all serial communications with the Chameleon so a necessary step You can manually install the FTDI driver from the DVD ROM ZIP file here DVD ROM CHAM_AVR TOOLS DRIVERS USBDriverInstallerV2 04 16 exe After you have installed the driver then each time you plug a Chameleon AVR into the PC via the USB port the FTDI chip will assign a NEW COM port you need to determine what COM port it attached itself to Goto Windows Start menu on and select Control Panel System Properties gt select Hardware Device gt and select Ports you should see something like that shown in Figure 15 49 Figure 15 49 Determining the COM port that the FTDI chip on the Chameleon AVR u
184. SSH Serial Select a serial line Configure the serial line Data bits Parity 113 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit To launch the terminal program you would press lt Open gt which opens a new terminal window This is where you would type on the PC keyboard to communicate with the Chameleon AVR and run the demos or do serial terminal experiments 15 2 3 1 Running the Arduino Tool We are all ready to go let s do a final checklist before we launch the tool 1 You have the USB cable plugged into the PC and you have installed the FTDI serial drivers if needed 2 You have a 9V DC power supply plugged into the Chameleon optional 3 You have moved the serial select switch into the DOWN position so the USB serial port is connected to the AVR chip not the Propeller 4 You have the VGA and NTSC cables connected to the Chameleon as well as a mouse optional Finally we are ready to launch the Arduino tool itself If you take a look back in the installation directory where you decompressed the Arduino ZIP file Figure 15 44 you will see an icon ARDUINO EXE go ahead and double click it You should see the splash screen load shown in Figure 15 52 Figure 15 52 Arduino splash screen Arduino Based on processing by y as and Ben Fry Then finally the application will load and will look something like that shown in Figure 15 53 114 2009 NURVE NETWORKS L
185. Scroll Lock indicator O off 1 Num Lock indicator O off 1 6 5 Caps Lock indicator O off 1 reserved must be zero EE Diagnostic Echo keyboard echoes the EE byte back to the system without an acknowledgement FO PS 2 Select Read Alternate Scan Code Sets instructs keyboard to use one of the three make break scan code sets Keyboard responds by clearing the output buffer typematic key and then transmits an ACK The system must follow up by sending an option byte which will again be ACK ed by the keyboard 00 return byte indicating scan code set in use 01 select scan code set 1 used on PC amp XT 02 select scan code set 2 03 select scan code set 3 F2 PS 2 Read Keyboard ID keyboard responds with an ACK and a two byte keyboard ID of 83AB F3 Set Typematic Rate Delay keyboard responds with ACK and waits for rate delay byte Upon receipt of the rate delay byte the keyboard responds with an ACK then sets the new typematic values and scanning continues if scanning was enabled Typematic Rate Delay Option Byte 17161514131211101 typematic rate indicator see INT 16 3 A in period formula see below iil B is period formula see below nS typematic delay always zero 57 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8
186. TEST PGM VER c CHANLANR TWI SPL VOLOC let prop finish transaction CHAM_AVR_UART_DRY_VO10 c delay_us SPI_PROP_DELAY_LONG_US CHAM AVR VGA DRV VO10 c sader Files CHAM AVR FLASH VOLO h CHAM AVR GFX DRV VO10 h CHAM AVR header template h end CHAM_AVR_KEYBOARD_DRV_VO10 h CHAM_AVR_MOUSE_DRV_VO10 h CHAM AVR NTSC DRY vO10 h x CHAM AVR PROP PORT DRY VO10 h AVRISP mkll in ISP mode with ATmega328P CHAM AVR SOUND VO10 h CHAM AVR SYSTEM V010 h CHAM AVR TWI SPI DRV VO10 h HAPLAR DART DRY VOITO R send read command 6 6 CHAM AVR GA DRV VO10 h SPI Prop Send Cmd GPU GFX OUERSCAN COL 0x00 0x80 io h GFX Set Tilemap Width int width sets the width of the tile 32 64 128 256 are available and encoded as 9 1 2 3 SPI_Prop_Send_Cmd GPU GFX SCREEN WIDTH W width 8x00 bl Lj Main Program Fuses LockBits Advanced Hw Settings HW Info Device Erase device before flash programming Verify device after programming iom168 h let prop get data ready iom328p h delay_us SPI_PROP_DELAY_LONG_US Flash 2 iomx8 h or FLASH Men REM AVR NTSC 128 96 ULTRA VO10 h eve results note if we read the results back too soon the drivi REM AVR NTSC 128 96 ULTRA VO10 h se keep that in
187. THE LICENSED WORKS WILL MEET YOUR EXPECTATIONS v ANY ERRORS IN THE LICENSED WORKS WILL BE CORRECTED AND OR vi YOU MAY USE PRACTICE EXECUTE OR ACCESS THE LICENSED WORKS WITHOUT VIOLATING THE INTELLECTUAL PROPERTY RIGHTS OF OTHERS SOME STATES OR JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES OR LIMITATIONS ON HOW LONG AN IMPLIED WARRANTY MAY LAST SO THE ABOVE LIMITATIONS MAY NOT APPLY TO YOU IF CALIFORNIA LAW IS NOT HELD TO APPLY TO THIS AGREEMENT FOR ANY REASON THEN IN JURISDICTIONS WHERE WARRANTIES GUARANTEES REPRESENTATIONS AND OR CONDITIONS OF ANY TYPE MAY NOT BE DISCLAIMED ANY SUCH WARRANTY GUARANTEE REPRESENATION AND OR WARRANTY IS 1 HEREBY LIMITED TO THE PERIOD OF EITHER A Five 5 DAYS FROM THE DATE OF OPENING THE PACKAGE CONTAINING THB LICENSED WORKS OR B THE SHORTEST PERIOD ALLOWED BY LAW IN THE APPLICABLE JURISDICTION IF A FIVE 5 DAY LIMITATION WOULD BE UNENFORCEABLE AND 2 LICENSOR S SOLE LIABILITY FOR ANY BREACH OF ANY SUCH WARRANTY GUARANTEE REPRESENTATION AND OR CONDITION SHALL BE TO PROVIDE YOU WITH A NEW COPY OF THE LICENSED WORKS IN NO EVENT SHALL LICENSOR OR ITS SUPPLIERS BE LIABLE TO YOU OR ANY THIRD PARTY FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND OR ANY DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITATION THOSE RESULTING FROM LOSS OF USE DATA OR PROFITS WHETHER OR NOT LICENSOR HAD BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND ON ANY THEORY OF LIABILITY AR
188. U GFX BASE ID Reads 16 bit tile bitmaps ptr which points to the bitmaps indexed by the tilemap define GPU GFX PALETTE R 10 GPU GFX BASE ID Reads 16 bit palette array ptr which points to the palettes in use for the tilemap define GPU GFX PALETTE W CL1 GPU GFX BASE ID Writes 16 bit palette array ptr which points to the palettes in use for the tilemap define GPU GFX OVERSCAN COL 124GPU GFX BASE ID Reads top overscan color drawn on the screen define GPU GFX TOP OVERSCAN COL W 13 GPU GFX BASE ID writes top overscan color drawn the screen define GPU GFX BOT OVERSCAN COL R 14 6 GFX BASE ID Reads top overscan color drawn on the screen define GPU GFX BOT OVERSCAN COL W 15 GPU GFX BASE ID Writes top overscan color drawn on the screen define GPU GFX HSCROLL FINE R 16 GPU GFX BASE ID Reads current fine horizontal scroll register 0 7 NOTE NOT implemented yet fdefine GPU GFX HSCROLL FINE W 174GPU GEX BASE ID writes current fine horizontal scroll register 0 7 NOTE NOT implemented yet define GPU GFX VSCROLL FINE 184GPU GFX BASE ID Reads current fine vertical scroll register 0 7 define GFX VSCROLL FINE 19 GPU GFX BASE ID writes current fine vertical scroll register 0 7 define GPU GFX SCREEN WIDTH R 20 GPU GFX BASE ID Reads screen width value 0 16 tiles 1 32 tiles 2 64 tiles etc define GPU GFX SCREEN WIDTH W 21 GPU GFX
189. UNC FILLMEM16 1 Fills memory with datal6 2 bytes at a time define GPU GFX SUBFUNC COPYMEM8 2 Copies numbytes from src gt dest in byte size chunks define GFX SUBFUNC 3 Fills memory with low byte of 16 1 bytes at a time normal commands define GFX TILE MAP R 24GPU GFX BASE ID Reads 16 bit tile map ptr which points to the current tile map displayed define GFX TILE MAP W 34GPU GFX BASE ID Writes 16 bit tile map ptr which points to the current tile map displayed define GPU GFX DISPLAY PTR R 44GPU GFX BASE ID Reads 16 bit tile map ptr which points to the current display ptr into the tile low level print functions use this pointer define GPU GFX DISPLAY PTR W 5 6 GFX BASE ID Writes 16 bit tile map ptr which points to the current display ptr into the tile map low level print functions use this pointer define GFX TERM 6 GPU GFX BASE ID Reads 16 bit tile map ptr which points to the current terminal ptr into the tile map terminal level print functions use this pointer define GFX TERM PTR W 7 GPU GFX BASE ID Writes 16 bit tile map ptr which points to the current terminal ptr into the tile map terminal level print functions use this pointer define GPU GFX BITMAP R 8 GFX BASE ID Reads 16 bit tile bitmaps ptr which points to the bitmaps indexed by the tilemap define GFX BITMAP W 9 GP
190. V VO010 c h CHAM AVR NTSC DRV VO010 c h CHAM AVR DRV VO010 c h CHAM AVR SOUND VO010 c h General Requirements Video port connected to NTSC or VGA monitors RCA audio connected to an amplifier or the TV s audio input Controls Required None Compiling and Running the Arduino Version Demo Version Description Plays sounds on the speaker Main Sketch Source File CHAM AVR SOUND DEMO 01 Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR TWI SPI DRV 010 CHAM AVR NTSC DRV 010 CHAM AVR DRV 010 CHAM AVR SOUND DRV 010 General Requirements Video port connected to NTSC TV monitor Controls Required None 223 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Technical Overview This demos uses the Sound API to plays tones on the speaker You need to hook up the Chameleon s audio out port to the an amplifier or the TV s audio in However the program outputs to both the NTSC and VGA display for its text output This program is the most complex yet since it deals with sound First off we need a scale of frequencies which is at the top of the program and shown below float adjacent_note 1 059463094 2A 1 12 ratio between adjacent keys scale from middle A to one octave above A int scale 440 466 494 523 554 587 622 659 698 740 784 831 880 A 440 flat 466 494 523 sharp 554 58
191. VR 8 Bit The following lists each function a description comments and example usage of the function Function Prototype int VGA_ClearScreen void Description _VGA_ClearScreen simply clears the VGA terminal screen and fills the screen with spaces Returns 1 Example s Clear the screen VGA_ClearScreen Function Prototype int GetXY int x int y Description VGA GetXY returns the position column row of the virtual cursor Depending on the driver you are using the x y values have different possible ranges For the Default2 driver they are 0 31 0 23 The function takes two pointers to the integer variables you want to receive the values Returns 1 Example s Retrieve the current cursor position int X y amp x Function Prototype int VGA_SetXyY int x int y Description VGA SetXY sets the current cursor position on the VGA terminal screen The position ranges depend on the driver but for Default2 they are 0 31 0 23 Returns 1 Example s Read the current cursor position and then move the cursor one position to the right int x y VGA GetXY amp x VGA_SetxY 1 Function Prototype int VGA_Term_Char char ch Description _VGA_Term_Char prints an ASCII character to the VGA terminal at the current cursor position updates the current cursor position and potential
192. VR NTSC DRV V010 c h Tile engine and text console terminal functions VGA Text and Tile Graphics Module a ar CHAM AVR VGA V010 c h Tile engine and text console terminal functions Audio Driver Module CHAM AVR SOUND DRV VO10 c h Sound driver functions Communications Modules aa 2 CHAM_AVR_UART_DRV_V010 c h Low level Serial RS 232 communications driver CHAM AVR TWI SPI VO010 c h Low level I2C and SPI peripheral driver 2 ee Input Output Devices Modules a i CHAM AVR GAMEPAD 010 Gamepad driver CHAM AVR KEYBOARD DRV VO010 c h PS 2 keyboard driver CHAM PROP PORT 010 Propeller local 8 bit driver Am Storage Device Modules a a ee CC CHAM AVR FLASH VO010 c h 1MB SPI FLASH memory chip driver ee ee ee MM MC LC EN NN NN Mechatronics Actuator and Sensor Modules 7 a a ee ne es eee Note 1 This mode uses 6 8 tiles to squeeze more characters per line for text modes When building application using the Chameleon AVR library you will typically include the System module always and then include various modules such as video keyboard UART etc as needed by your application All the C and Header files are located on the DVD here for reference DVD ROM CHAM AVR S
193. VRStudio IDE and you have purchases the AVR ISPMKII programmer or similar then you can compile and program the Chameleon AVR via the 6 pin ISP port Both methods and setups were covered earlier in the manual But let s briefly review a couple details about the differences between the AVRStudio and Arduino version of each demo 27 1 1 Differences Between the AVRStudio and Arduino Demos and General Porting Strategies Before we get into the pre setup of AVRStudio and the Arduino tool let s take a step back and discuss the differences between the two tools and software as you write it First off with AVRStudio and the Arduino tool you program in C C Technically AVRStudio you can program in straight C while the Arduino tool you can use C C That said we made all programs C so they work on both tool chains So assuming we start with a simple C program on AVRStudio then porting it to Arduino requires only a few changes relating a number of topic areas that we will cover below Include Files The Arduino tool isn t as flexible as AVRStudio The whole point of the Arduino tool is to insulate the user from the complexities of compilers linkers make files etc Thus you have to code in the template that Arduino provides to this end the search paths are a little different When programming in AVRStudio your header files will typically be included like this 205 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit AVRStud
194. X Write Mem Portl16 0x1234 Function Prototype unsigned int GFX Get Src Ptr void Description GEX Get Src Pir retrieves the 16 bit source pointer in the GPU for memory transfer and fill operations This address is absolute in the Propeller s main RAM memory Returns the pointer Example s Retrieve the source pointer unsigned int src ptr src ptr GFX Get Src Ptr 191 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Function Prototype unsigned int GFX Get Dest Ptr void Description GFX Get Dest Ptr retrieves the 16 bit destination pointer in the tile GPU for memory transfer and fill operations This address is absolute in the Propeller s main RAM memory Returns the pointer Example s Retrieve the destination pointer unsigned int dest ptr dest ptr GFX Get Dest Ptr Function Prototype unsigned int GFX Set Src Ptr unsigned int src ptr Description GEX Set sets the 16 bit source pointer for tile GPU fill and memory operations This is an absolute address in Propeller RAM memory Returns 1 Example s Read the source pointer and add 4 to it and write it back GFX Set Src Ptr GFX Get Src Ptr 4 Function Prototype unsigned int GFX Set Dest Ptr unsigned int dest ptr Description Set Dest sets the 16 bit destination pointer for GPU fill and memory operations This is
195. _GFX_subfunc GPU_GFX_SUBFUNC_COPYMEM16 0 Copies numbytes from src gt dest in wordsize chunks wordmove tile_dest_addr_parm tile_src_addr_parm tile_numbytes_parm GPU_GFX_SUBFUNC_FILLMEM16 1 Fills memory with 16 2 bytes at a time wordfill tile_dest_addr_parm tile_datal6_parm tile numbytes parm gt gt 1 182 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit GPU_GFX_SUBFUNC_COPYMEM8 2 Copies numbytes from src gt dest in byte size chunks bytemove tile_dest_addr_parm tile_src_addr_parm tile_numbytes_parm gt gt 1 GPU_GFX_SUBFUNC_FILLMEM8 3 Fills memory with low byte of data16 1 bytes at a time bytefill tile_dest_addr_parm tile datal6 parm amp FF tile numbytes parm END CASE GFX subfunc GPU_GFX_TILE_MAP_R Reads or Writes the 16 bit tile map ptr which points to the current tile map displayed g_spi_result tile_map_base_ptr_parm GPU GFX TILE MAP W tile map base ptr parm g datal6 GPU_GFX_DISPLAY_PTR_R Reads or writes the 16 bit tile display ptr which points to the location where low level printing is displayed g_spi_result tile_display_ptr GPU_GFX_DISPLAY_PTR_W tile display ptr datal6 EEE GPU_GFX_TERM_PTR_R Reads or writes the 16 bit tile terminal ptr which points to the location where high level terminal mode printing is displayed g_spi_result tile_term_ptr GPU_GFX
196. _TERM_PTR_W tile term ptr datal6 GPU_GFX_BITMAP_R Reads or writes the low byte of the 16 bit tile bitmaps ptr which points to the bitmaps indexed by the tilemap g_spi_result tile_bitmaps_base_ptr_parm GPU_GFX_BITMAP_W tile bitmaps base ptr parm g datal6 have highlighted the register access code fragments at the top of each section So the idea is the AVR PIC sends the GFX command message via SPI the SPI message dispatcher catches these messages and passes all of them to the function then this function cases on each possible register access message and processes it viola Of course the above code is a partial listing the complete function is really long and you can look it yourself in the Propeller source file GPU Functions Overview These functions deserve a bit of explanation am using the word GPU pretty freely here and its not meant to infer there is a hidden GPU somewhere but rather than indicate that the hardware or driver is capable of doing large operations via a single command Two things that we do a lot of in computer graphics is copying data and moving data Copy move copy move copy move 9096 of operations are copy move So one thing you want you GPU graphics engine software whatever to do is copy and move fast Thus one of the simple additions to the tile driver is the ability to copy and fill memory So added some sub functions that call GPU functi
197. a menu on both the NTSC and VGA displays this is shown in Figure 31 6 below Chameleon FLASH Memory Demo Main Menu 1 XModem receive to FLASH 2 Dump FLASH to screen Selection 1 2 Referring to Figure 31 6 there are two menu options 1 Xmodem receive to FLASH 2 Dump FLASH to screen You control the menu with the local keyboard plugged into the Chameleon s PS 2 port 245 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Option 1 starts a 3 second countdown and then starts the X Modem download Thus the PC side better already have the XModem file transfer program ready and waiting Moreover the programs dumps the data to the screen in ASCII format so suggest that what your transfer its human readable Also make it short maybe a few hundred bytes to a couple K The AVR only has enough room for a 1K receive buffer in the X Modem function thus it only buffer 1K of the data and writes it to the FLASH memory everything else is shown on the screen as its received but lost Option 1 is shown in Figure 31 7 below Figure 31 7 The FLASH demo receiving a file Download Complete 11 Blocks File Size 1408 Opening FLASH memory Erasing first 4K of FLASH Writing 1408 bytes to FLASH Closing FLASH memory Main Menu 1 XModem receive to FLASH Dump FLASH to screen Of course you can alter the XModem receive function to write files directly to the FLASH as they are received bl
198. ably should work in the more robust AVRStudio since it allows ASM language simulation etc But its up to you just have fun 15 3 Installing the Parallax Propeller IDE Since each Chameleon AVR and PIC has dual processors consisting of an AVR and Parallax Propeller chip both chips need to be loaded with firmware and accessed to program To program the Parallax Propeller chip you need to install the Parallax IDE tool This tool is a very simply IDE that allows you edit programs for the Propeller chip and download them to the target The editor has no built in debugging which is really a result of the Propeller chip s lack of debugging internally in hardware However this isn t as bad as it seems You can use printf techniques as well as run debug like processes on other cores and have them interrogate memory locations in real time Finally its pretty easy to test code change something recompile and download to the target since programs can only be up to 32K bytes in size The Propeller Chip IDE was developed by Parallax Inc to program their new multi core Propeller chip The Chameleon AVR and PIC uses a Propeller chip as the media processor thus to program the Propeller chips EEPROM on the Chameleon with code we need to use this tool The Propeller is a 32 bit processor and you program it in a BASIC like language called SPIN or you can program in Assembly language The Propeller IDE supports both seamlessly The assembly languag
199. ain by Walt Whitman xmodem test file o captain txt All the World s a Stage by William Shakespeare xmodem test file all the worlds stage txt 246 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit They are better than using random TXT files or data files and if you are over 21 years old and haven t read these at least once in your life its worth doing so they are very powerful and very true Compiling and Running the AVRStudio Version Demo Version Description FLASH memory demo that receives files X Modem protocol Main Source File CHAM AVR FLASH DEMO 01 Additional Files Required CHAM AVR SYSTEM V010 c h CHAM AVR TWI SPI DRV VO010 c h CHAM AVR UART DRV VO010 c h CHAM AVR NTSC DRV VO010 c h CHAM AVR DRV V010 c h CHAM AVR KEYBOARD V010 c h CHAM AVR FLASH V010 c h General Requirements NTSC or VGA display connected local PS 2 keyboard connected X Modem download program running on PC N81 2400 baud Controls Required Local PS 2 keyboard simply use menu also PC running X Modem uploader Compiling and Running the Arduino Version Demo Version Description FLASH memory demo that receives files X Modem protocol Main Sketch Source File CHAM AVR FLASH DEMO Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR TWI SPI DRV 010 CHAM AVR UART DRV 010 CHAM AVR NTSC DRV 010 CHAM AVR DRV 010
200. airly easy and lots of schematics and designs are on internet that need only a RS 232 or parallel port However the Atmel product is USB based for speed Figure 4 3 The Chameleon ISP programming interface schematics 5VCC 6 pin ISP Programming Interface C22 Note ISP draws power from target with mandatory 50mA avg I 0 4uF SVCC SPI_MISO SPI SCK RESn Figure 4 3 shows the actual circuitry for the ISP interface As you can see its fairly straightforward Nothing more than the port header routed to the proper pins and a bypass cap on the power signals Also the ISP programmer pulls its power from the Chameleon which is on the order of 50mA 5 0 Serial USB UART Programming Port The Propeller chip as well as the AVR can also be programmed via the serial USB UART The Propeller uses serial to communicate as default however the AVR uses serial only when there is a bootloader programmed into the AVR that listens to the serial port and there is a protocol in place as well as tool on the other end that follow the protocol agreement to re program the FLASH Therefore the native method to re program the Propeller is via the serial connection but the AVR is typically re programmed via the USP port thus the serial re programming is a trick hack that is simply supported by a bootloader that supports it With that in mind the next section cover the USB UART design but before we take a look at that there is one
201. ak strings apart that come in via the UART The bottom line is text parsing isn t as easy as you would think and when you have to write editors that run over terminal programs there are a lot of issues you need to resolve Summary Hopefully you have a good command of the serial driver now and you can use it to communicate with the PC or any other serial based device There are all kinds of interesting things you can do with a serial port and the Chameleon AVR for example you could get an external serial modem and write a simple BBS bulletin board system on the Chameleon AVR How cool would that be For example the TRENDnet 56k V 92 High Speed Voice Fax Modem has a standard RS 232 DB9 connector on it so you can connect quite easily to the Chameleon AVR and send standard HAYES AT commands at it Can you imagine running a BBS on your little Chameleon and then dialing in from a friends house Here s a link to the product http www tigerdirect com applications SearchTools item details asp EdpNo 671884 amp CatlId 564 31 1 3 FLASH Memory Demo with X Modem Protocol Bonus Example This demo illustrates how to use the onboard 1MB SPI FLASH memory Atmel part T26DF081A This is not to be confused with the Propeller chip s 64K EEPROM The EEPROM is for the Propeller s boot image and only directly accessible by the Propeller chip The 1 MB FLASH is accessible by the AVR chip via the SPI mux interface With that in mind you might want review
202. alea et ee a tke ttum fm et 211 28 1 2 NTSC Glowing Top Bottom Overscan DEMO 213 28 1 3 NESC Smooth Scrolling Tilemap Demo 2 3 ea eaa a bead io e Hbi He EHE 215 28 TL AVGA Printing inaudito oe oH pe t Hb ee HM a ice a Ie LEE 217 28 15 Dual NTSC7 Demo 4 oi uel adm 219 28 6 Star Field Demo deed te dedidit pipe iota mp dust dit 220 29 1 Demos M 222 29 11 Sound DEMO 223 30 1 Input SIS 225 30 1 T Keyboard Deos oic ntt at du tet dits 225 30 1 2 Mouse ASGIL ia neas etit tute i te t CO n e e ET E DRE ERI 228 31 1 Serial FLASH and Port I O Device Demos ecce eene eene e eere eerte etes sess esee as Po 230 31 1 1 Propeller Local Port LED Blinker Demo 231 31 12 Serial RS 232 Communications 2 tte setts e eet ett ne ee E Ft eoe en T AXE Ee Fe EUR EE Fe E e EV ee egeo 233 31 1 3 FLASH Memory Demo with XModem Protocol Bonus
203. alette entry is a single 32 bit long that represents 4 colors in the format color 3 color 2 color 1 color 0 that are represented by the bitmaps as each 2 bit pair indexing as color 0 1 2 3 Returns the 16 bit pointer value address Example s Read the palette pointer unsigned int palette ptr prop palette ptr prop GFX Read Palette Ptr Function Prototype unsigned int GFX Write Palette Ptr unsigned int palette ptr Description GEX Write Palette Pir writes the 16 bit palette pointer palette ptr that points to the set of palettes referred to by the palette index in each tile entry each palette entry is a single 32 bit long that represents 4 colors color 3 color 2 color 1 color 0 that are represented by the bitmaps as each 2 bit pair indexing as color 0 1 2 3 When this operation is performed the palettes pointed to must be valid colors otherwise sync issues could occur since the color words can represent both color and sync So make sure that when you do alter the palette pointer you have built up value palette entries and that all potential palette indices in your tile map are represented by a palette Returns 1 Example s X Read the palette pointer and then shift it by 4 bytes in essence by a single palette of 4 colors down the list 187 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit GFX Write Paltte Ptr GFX Read Palette Ptr 4 Function Prot
204. all can sustain this speed The timings on some of the peripherals become tight for example the serial and SPI might error more often and the rate of bit errors with the FLASH memory increases but 28 636 MHz is a solid overclocking rate The chip will get a little hotter but not much the interesting thing though is the chip doesn t stop malfunctioning due to overheating but simply that certain parts of the chip can t go any faster For example the internal SRAM FLASH has more limits than say the glue logic inside So even though most of the chip might run at 40 MHz it doesn t matter since the SRAM and FLASH won t read correctly In conclusion the AVR will go 28 636 MHz no problem without any changes to the Vcc voltage or heatsinking needed 263 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix ASCII Binary Octal Universal Lookup Tables ASCII Hex Table ASCII Symbol ASCII Symbol ASCII Symbol ASCII Symbol 0 0 NUL 16 10 DLE 32 20 space 48 30 0 1 1 SOH 17 11 DC1 33 21 49 31 1 2 2 STX 18 12 DC2 34 22 50 32 2 3 3 ETX 19 13 DC3 35 23 51 33 3 4 4 EOT 20 14 DC4 36 24 52 34 4 5 5 ENQ 21 15 NAK 37 25 53 35 5 6 6 22 16 SYN 38 26 amp 54 36 6 7 7 BEL 23 17 ETB 39 27 f 55 37 7 8 8 BS 24 18 CAN 40 28 56 38 8 9 9 TAB 25 19 EM 41 29 57 39 9 10 A LF 26 1A SUB 42 2A 58 11 VT 27 1B ESC 43 2B 59 3B 12 28 1C FS 44 2
205. all the Arduino tool make sure you have the bootloader on the AVR chip and then use the tool from your perspective the experience on Windows Linux and Mac should be identical 262 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix H Overclocking the AVR and Propeller As with any TTL or CMOS device you can always overclock them Typically 10 overclocking will work 99 of the time anything higher than 10 you have to take a few things into consideration such as power dissipation memory response times and overall timing of the chips However both the AVR and Propeller can be over clocked if you want to get more performance and are willing to potentially damage the chips H 1 Overclocking the Propeller Microcontroller The Propeller uses an external clock or xtal that is then spun up by an internall PLL The PLL has a number of power of 2 clock multiplier rates but typically a 5 10MHZ clock xtal is used and then the clock multiplier is set at 8x or 16 For example the Default2 driver clock directives look like this CON These settings are E 5 MHZ XTALS _clkmode 11 111 enable external clock and pll times 16 _xinfreq 5 000 000 set frequency to 5 MHZ This instructs the compiler to generate an object with settings that assume a 5MHz input clock and then the processor scales this by 16X resulting in the nominal 80MHZ that the Propeller chip needs to operate The 80 MHz cloc
206. all we need to do is add the two messages that set the port bit LOW and HIGH Reviewing the main message dispatcher loop we simple find the last message processed and add a couple more messages Here s that section before and after again Before REG CMD WRITE BYTE write byte 0 3 of output register g reg out buffer byte 0 3 byte address to write 0 3 is in g data while data to write is in g data2 g reg out buffer byte data g data2 read command from byte registers of 32 bit buffer register REG CMD READ BYTE read byte 0 3 of input register g reg in buffer byte 0 3 this data is then placed into spi buffer for transport back to client byte address to read 0 3 is in g data 251 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit g_spi_result g_reg_in_buffer byte g_data SYS_RESET resets the prop reboot end case commands set result and set dispatcher to idle spi finishcmd g_spi_result end main loop After Adding New Message Handlers REG CMD WRITE BYTE write byte 0 3 of output register g reg out buffer byte 0 3 byte address to write 0 3 is in g data while data to write is in g data2 g reg out buffer byte g data data2 read command from byte registers of 32 bit buffer register REG CMD READ BYTE read byte 0 3 of input register ger uo
207. ally anticipating another read or write The actual code looks like update src pointer based on auto increment value tile src addr parm tile mem autoinc parm Thus the variable mem parm is used as the memory increment stride each read write operation This comes in handy and reduces address updates when you access continuous memory There is of course a function to change mem autoinc parm Finally the function always returns 1 Example s Write FF to the byte of memory currently pointed to by the source memory pointer GFX Write Mem Port8 OxFF Function Prototype unsigned int GFX Read Mem Port16 void Description GFX Read Mem Port16 reads a 16 bit value from prop memory source ptr note source pointer is always used for memory port operations In the Propeller driver source ptr is the variable tile src addr parm and is set using GFX Set Src Ptr unsigned int src defined below The idea of this function is that it provides a simple mechanism to access the Propeller s RAM Returns the 16 bit 190 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit value read directly from the Propeller s 32K RAM This function also updates the source pointer automatically anticipating another read or write The actual code looks like update src pointer based on auto increment value tile_src_addr_parm tile_mem_autoinc_parm Thus the variable tile_mem_autoinc_parm
208. amming model C C support huge library of software and customer base along with the multicore support of the Propeller and its ability to run multiple tasks at once as well as its special ability to generate video With that in mind now let s discuss every one of the hardware modules in the design Part Hardware Design Primer In this section we are going to cover every one of the Chameleon AVR s hardware sub sections so you can get an idea of what s going on and how the systems and signals are routed Taken as a whole the Chameleon is rather complex but as you will see each individual sub system is rather straightforward Let s begin with a birds eye view of the entire system schematic on the next page in landscape mode Figure 2 1a Please take a good look at it and see if you can locate the AVR Propeller FLASH memory EEPROM and power supplies to help with our discussions Then right under it in Figure 2 1 b is a PCB view so you can see where everything is as well as a clear view of the I O headers in black and white with high contrast The board is so small its a bit hard to see things Figure 2 1 a The complete Chameleon AVR 8 bit schematic 26 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit ET orama von lt gt Js mk hee sos ks lt gt pe D CENE 2 won os D ve sae HSV14 IdS ANS
209. amp 1 TWSTO END TWI WRITE end POT Set As you can see using the TWI Action function must be interleaved with the protocol of the target device The low level protocol is handled by each call to TWI Action via the hardware but the actual communication bytes setup and control of the target device a digital pot in this case is a completely other issue Reviewing the code you can see that the first step is to send the START and address to the device then start writing data to control the pot Also notice the testing of the return value from each call to TWI Action Depending on the results you can take what action you must In this case the empty function TWI Error are called which you can insert any code you wish Function Prototype s void TWI Error void TWI Status void TWI_Success int code Description s These functions are not implemented and are simply place holders or wrappers for future expansion As noted in the primer on I2C the protocol has a lot of state and you might want to add these functions to the API and fill them out Currently a much simpler approach is taken where the single action function listed above performs both any action as well as returns status and errors Example s None Function Prototype int SPI Init unsigned char spi rate 162 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Description SPI Init
210. an absolute address in Propeller RAM memory Returns 1 Example s Read the destination pointer and add 4 to it and write it back GFX Set Dest Ptr GFX Get Dest Ptr 4 Function Prototype int GFX Get Tilemap Width void Description GFX Get Tilemap Width retrieves the 8 bit the tile map width encoded as 0 1 2 3 which means 32 64 128 256 tiles Example s Read the tilemap width and store it int tilemap width GFX Get Tilemap width 192 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Function Prototype int GFX_Set_Tilemap_Width int width Description GFX Set Tilemap Width sets the width of the tile map to 32 64 128 or 256 which are encoded as 0 1 2 3 with the parameter width The idea of this function call is to set the virtual playfield of the tilemap to large than its physical size which is always 32 tiles Doing so allows for horizontal scrolling course Returns 1 Example s Set the width to 128 tiles which is 4 complete screenfull s of tiles for horizontal scrolling GFX Set Tilemap width 2 Function Prototype int GFX Get Bottom Overscan Color void Description GFX Get Bottom Overscan Color retrieves the bottom overscan color of the NTSC driver The bottom overscan is a few lines at the bottom of the screen that no tiles are drawn into Usually this area is black on normal broadcasts of TV programs but
211. and Target Settings Depending on what programmer you have plugged in it will have a number of communication modes ISP mode JTAG mode etc In our case simply select ISP mode since the AVR ISP programmer uses the ISP interface on the AVR chip Additionally there is a speed setting that controls the download baud rate to the programmer Set it for 125 KHz as a nominal value you can get away with higher speeds but then risk some bit errors which can lead to locked up chips Thus 125 KHz should be fast enough and the default setting Simply press the lt Settings gt buttons to adjust the programmer baud rate When you have completed setting the Main tab up properly select the Program tab next You should see the controls shown in Figure 15 37 below Figure 15 37 The AVR ISP control panel s Program tab AVRISP mkll in ISP mode with ATmega328P ses LockBits Advanced Hw Settings Hw Info Auto Erase Device Erase device before flash programming Verify device after programming Flash Input HEX File rce cham_avr_work_O1 default cham_avr_work_Ol hex Program Verify Read EEPROM Input HEX File Program Verify ELF Production File Format Input ELF File Fuses and lockbits settings Program Save must be specified before saving to ELF Setting mode and device parameters OK Entering programming mode OK Reading fuses address 0 to 2 OxDF
212. and it might as well be predictable 153 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Sending bytes with SPI is similar to the serial RS 232 protocol you place a bit of information on the transmit line then strobe the clock line of course RS 232 has no clock As you do this you also need to read the receive line since data is being transmitted in both directions This is simple enough but SPI protocol has some very specific details attached to it about when signals should be read and written that is on the rising or falling edge of the clock as well as the polarity of the clock signal This way there is no confusion about edge level or phase of the signals These various modes of operation are logical called the SPI mode and are listed in Table 19 1 below Table 19 2 SPI clocking modes Mode CPOL Clock Polarity CPHA Clock Phase Mode Descriptions Mode 0 The clock is active when HIGH Data is read on the rising edge of the clock Data is written on the falling edge of the clock default mode for most SPI applications Mode 1 The clock is active when HIGH Data is read on the falling edge of the clock Data is written on the rising edge of the clock Mode 2 The clock is active when LOW Data is read on the rising edge of the clock Data is written on the falling edge of the clock Mode 3 The clock is active when LOW Data is read on the falling edge of the clock Data is written
213. any channels as we wish since at the end of the day we need only a single bit as the output Figure 14 4 b shows another PWM like technique where instead of modulating the duty cycle instead complete 50 duty cycle pulses are sent but they are interspersed with 0 duty cycles as a function of time If the rate of these pulses is high enough they too create an average voltage over time In Figure 14 4 b there are 10 total cycles and in 2 of them we have 50 duty cycles for a total analog voltage per 10 clocks of Average Signal 20 duty cycle 5V 50 100 ns 1000 ns 0 5 69 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Notice we are dealing in nanoseconds in the second example this technique needs to run at a higher frequency to give the average enough time to change at the highest frequency rate you want to synthesize in this method of D A Figure 14 5 A low pass averaging filter and the stair step results a b Low Pass Filter gem inal Output to Filter Now the only mystery component to the D A PWM converter is averaging of the signal Well fortunately for us a low pass filter as shown in Figure 14 5 acts as an averaging circuit in fact those of you with an EE background know that 1 S is integral in the S Domain and a low pass filter has a 1 S term it in Intuitively it makes sense as well since a low pass filter as shown in Figure
214. arations R 202 26 0 PROPELLER LOCAL PORT MODULE nnmnnn 203 26 1 Header File Contents Overview cssscsssccssscsssecsssecsssscssssessssecsssecssssesssssssssssssscsssscssssenssssssssscnssecsssssossssscssscossonessoes 203 26 2 API Listing Reference 203 26 3 API Functional Declarations R H 204 27 0 CHAMELEON HANDS ON PROGRAMMING TUTORIALS AND DEMOS 205 27 1 Setup to Compile the Demos and Tutorialls scsssccssscsssscssssessssecsssecsssscsseesssessssscsssecsssssesssessssscssscsssssssssescssssseseoes 205 27 1 1 Differences Between the AVRStudio and Arduino Demos and General Porting Strategies eese 205 Include Files PPP PPP 205 Renaming the main Function and 4 206 Serial Libraries 208 27 1 2 Setup for AVRStudio Version of Demos 209 27 1 3 Setup for Arduino Version of 209 Copying the Sketches D VD saos i n Ru td tos te Ed dacs 210 27 1 3 Setting the Chameleon Hardware 210 28 1 Graphics T 211 28 I T NTTSC Demo onte ie m
215. are typically interlaced and computer signals and compatible displays are typically progressive scan non interlaced These two formats are incompatible with each other one would need to be converted to the other before any common processing could be done Interlaced scanning is where each picture referred to as a frame is divided into two separate sub pictures referred to as fields 45 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Two fields make up a single frame An interlaced picture is painted on the screen in two passes by first scanning the horizontal lines of the first field and then retracing to the top of the screen and then scanning the horizontal lines for the second field in between the first set Field 1 consists of lines 1 through 262 1 2 and field 2 consists of lines 262 1 2 through 525 The interlaced principle is illustrated in Figure 11 3 Only a few lines at the top and the bottom of each field are shown Most computer displays that output to TVs are progressive scans that is they draw a single frame 60 times a second without interlacing However some computers and game systems do put out interlaced video The old Amiga computer was one such example that had an interlaced video mode option to double the number of scanlines Figure 11 3 Interlaced scanning system les Retrace FIELD 2 NOTE Exaggerated in the vertical dimension for clarity A progressive or non interlaced
216. at the current cursor position updates the current cursor position and potentially scroll the text screen up if printing on last line of display Additionally this function is a sub command conduit to the terminal manager This functionality should be maintained for any drivers that you develop so users can have a standard set of base terminal functionality You can send the following ASCII codes some functions are redundant 00 clear the screen 01 home the cursor to top left 08 backspace 09 tab 8 spaces per 0A set X position X follows 0B set Y position Y follows 0C set color color follows 0D return carriage return and linefeed Example s Clear the screen then print Chameleon NTSC Term Char 0 NTSC Term Char NTSC Term Char NTSC Term Char NTSC Term Char NTSC Term Char NTSC Term Char NTSC Term Char NTSC Term Char NTSC Term Char YY HY YY 170 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Function Prototype int NTSC_Term_Print char string Description NTSC_Term_Print prints a NULL terminated string to the screen with automatic scrolling etc if the string prints off the right of the screen or bottom of terminal Returns 1 Example s Print the string Hello World to screen NTSC Term Print Hello world Fu
217. ates text output and input using a game as the platform Main Source File CHAM AVR GUESS NUMBER 01 Additional Files Required CHAM AVR SYSTEM V010 c h CHAM AVR UART DRV VO010 c h CHAM AVR TWI SPI DRV 010 CHAM AVR SOUND V010 c h General Requirements Serial port connection from Chameleon AVR to PC over the USB cable terminal programming running RCA sound output connected to speaker or TV audio Controls Required None uses PC keyboard via terminal program Compiling and Running the Arduino Version Demo Version Description Serial UART demo illustrates text output and input using a game as the platform Main Sketch Source File CHAM AVR GUESS NUMBER Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM V010 c h CHAM AVR UART DRV VO010 c h CHAM AVR TWI SPI DRV 010 CHAM AVR SOUND V010 c h General Requirements Serial port connection from Chameleon AVR to PC over the USB cable terminal programming running RCA sound output connected to speaker or TV audio Controls Required None uses PC keyboard via terminal program The game starts by asking you if you wish to play you can answer yes or no each has its consequences If you do decide to play then the computer selects a random number from 1 to 100 and asks you to guess it Just play along and see if you can guess Each guess you type in and hit lt RETURN gt 235 2009 NURVE NETWORKS LLC
218. ations even video and audio Figure 19 4 shows an architectural diagram of how the bus is laid out in relation to the master device and the slaves on the line Figure 19 3 2C bus layout Device 1 Device 2 Device3 Device n SDA SCL Electrically the bus consists of any number of masters and slaves on the bus Masters initiate communication while slaves listen and respond Masters can transmit and receive from a slave but a slave can not initiate communications Additionally to enforce that masters are in charge the clock line SCL can only be controlled by a master furthermore placing the slave s into a passive role Moreover so that multiple devices can be connected to the same 2 signal bus from an electrical point of view both SDA and SCL are open drain thus pull up resistors must be connected from SDA and SCL to Vcc via a 5 10K resistor on both lines Note that with the SPI bus all SPI devices share the MISO master input MOSI master output and SCLK serial clock lines however the CS or chip select lines for each device controls the selection of the target device not an address and when a device is selected its bus is active while any other de selected devices go tristate Thus the 12 bus is always active and arbitration is achieved thru an open drain design where SDA and SCL can only be pulled down by the master and SDA alone by the slave Then addre
219. atus_low end SPI_Prop_Send_cmd2 Even though you don t directly call this function its where all the action happens Let s go thru it line by line I have added manual line numbers in the listing to help The function uses the built in SPI hardware and makes calls to the SPI functions we already developed so that makes things a lot easier Here s how it works Propeller Chip Selection Step 1 Line 1 here we select channel 2 with the SPI mux this chip selects the Propeller chip as the target for SPI traffic Data Transmission Step 2 Lines 2 3 here we simply send the 1st byte of the command packet and retrieve the 1st byte back in a buffer Step 3 Lines 4 5 here we simply send the 2nd byte of the command packet and retrieve the 2nd byte back in a buffer Step 4 Lines 6 7 here we simply send the 3 byte of the command packet and retrieve the 3rd byte back in a buffer Propeller Chip De Selection Step 5 Lines 8 9 here we de select channel 2 with the SPI mux and select channel 0 the NULL channel Results Step 6 Line 10 We return the 8 16 bit result to caller This is how all commands are sent to the Propeller chip Example s Send command to NTSC driver to clear the screen So first thing we do is look in the header file at the command list in CHAM_AVR_TWI_SPI_DRV_V010 h also the Propeller driver CHAM_DEFAULT2_DRV_112 SPIN has the same list and look up the command we want GFX_CMD_NTSC_CLS and
220. avr source arduino arduino 0017 h Y Go msn T l A EEPROM 9 CHAM_AVR_NTSC_DRV_VO10 File and Folder Tasks Ethernet cHAM_AVR_PROP_PORT_DRY_VO10 Firmata CHAM_AVR_SOUND_DRY V010 Liquidcrystal CHAM AVR SYSTEM V010 matrix cHaM_AVR_TWI_SPI_DRY _VO10 O hardware servo cHaM_AVR_UART_DRV_ O10 My Documents _ 2 SoftwareSerial C CHAM AVR 0010 Shared Documents Sprite My Computer stepper f wire My Network Places _ C CHAM AVR FLASH DRV V010 Cj CHAM AVR GFX V010 Cj CHAM AVR KEYBOARD V010 C CHAM AVR MOUSE DRV V010 Other Places Details libraries bytes 3 Computer As you can see there are about a dozen new libraries that we have developed for the Chameleon to run in the Arduino environment They are all uppercase to help you differentiate them Ok that s it the entire Arduino installation is complete Now let s fire up the tool and set the environment up a little and try re building the Hello World program 15 2 3 Preparation to Launch the Arduino Tool for the First Time Before you launch the Arduino tool make sure you have the USB cable plugged into the Chameleon you can also have the 9V DC power adapter plugged in if you have one The USB is needed no matter what since that s what the Arduino tool will use to send serial data to the Chameleon s bootloader with Figure 15 48 below shows the U
221. ber for a human Now the next step up would be to still use ASCII formatted data that is human readable but to make it more abstract For example instead of having a command like this NTSC Print Hello We might encode NTSC as a single number and the command Print as another number and then the Hello would stay as is 25 0 Hello As you can see this version of the ASCII protocol is much smaller we have saved bytes already It s still human readable but not as warm and fuzzy The entire RPC string is 11 bytes including NULL terminator But can we do better Sure if we encode in binary then we don t send the longer ASCII text we send the actual byte data Therefore the binary encoding would look like 134 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Byte 0 Byte 1 T To Where byte 0 and 1 would represent the NTSC and Print sub functions In this case the entire RPC call costs 7 bytes but isn t human readable anymore since byte 0 1 are in binary and could be anything depending on what we picked them to be The point is that if you were using another processor or process to make the RPC calls and not a human at a serial terminal then there is no reason to use ASCII coding However that said still prefer ASCII formats when they are feasible since they are much easier to read and debug At least sending things in ASCII format during the de bugging phase so you can at least look at you
222. block diagram form and Table 1 3 lists the pins and their function for the AVR 328P Since the AVR 328P has so many internal peripherals and only a finite number of pins many functions are multiplexed on the I O pins such as SPI I2C UARTs A D D A etc Thus when you enable one of the peripherals they will typically override the I O functionality and take on the special functions requested However when you don t enable any peripherals each pin is a simple I O pin as listed in Table 1 3 Table 1 3 The AVR 328P general pin descriptions Pin Group Description Port 7 Port is 8 bit bi directional I O port with internal pull up resistors selected for each bit The Port B output buffers have symmetrical drive characteristics with both high sink and source capability As inputs Port B pins that are externally pulled low will source current if the pull up resistors are activated The Port B pins are tri stated when a reset condition becomes active even if the clock is not running Port B also contains the SPI interface signals as well as the clocking input pins Port C PC6 PCO Port C serves as analog inputs to the Analog to digital Converter C is an 7 bit bi directional I O port with internal pull up resistors selected for each bit The Port C output buffers have symmetrical drive characteristics with both high sink and source capability As inputs Port C pins that are externally pulled lo
223. byte maximum Now that we know the program is correct lets upload it to the chameleon with the 48 button Go ahead press the button this will take some time When the program is done uploading the Chameleon will immediately reboot and you should see the Hello World text scrolling on both the NTSC and VGA monitors Also in the black text output area of the Arduino tool you should see the message Binary sketch size 1034 bytes of a 30720 byte maximum That s it you have compiled your very first Chameleon program using the Arduino tool Hopefully you can see the incredible power of the Chameleon It leverages the toolchain and main processor of the Arduino but adds a very powerful multicore processor the Propeller to do the heavy lifting And with literally 10 lines of code you are displaying text on BOTH an NTSC and VGA screen Imagine the possibilities 120 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 2 3 3 A Couple Notes About the Arduino Version of Hello World When we get to the Programming API we will discuss this a little more But you might be wondering what are the differences between the pure C C versions of our programs that compile on AVRStudio and the Arduino versions Well there aren t many We wrote all the libraries to be 100 compatible In fact the differences can be listed in a few sentences they are 1 The Arduino run time library has its own main thus in all
224. cales the delays so if you turn on heavy optimization then make this number larger to offset the code speed the optimizer seems to cause issues with the final code interrupts etc if you do try turning on the optimizer you will have to play with delays and get things to work properly Optimizer settings 00 use slow factor of 1 or 2 01 02 03 05 use slow factor of 4 5 define SPI PROP STRING DELAY US 50 SPI PROP SLOW FACTOR the prop needs time to react to each spi terminal print command define SPI PROP CMD DELAY US CC2 SPI PROP SLOW FACTOR 2 the prop needs time to react to each spi transition this delay insures it can keep up if you optimize the Prop driver or convert to ASM then you can reduce this of course define SPI PROP DELAY SHORT US 100 SPI PROP SLOW FACTOR this delay is used where the critical path thru the SPI Prop is relatively short define SPI PROP DELAY LONG US 250 SPI PROP SLOW FACTOR this delay is used where the critical path thru the SPI Prop is relatively long 158 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The next set of defines are rather long they represent all the current commands that the Propeller driver understands These commands each have a specific set of parameters and functionality that will be clarified when we review the individual APIs for each class of messages graphics sound keyboard etc
225. cation set the USART hardware up speed bits per character parity etc and then you communicate via a collection of functions Now although we can use the put and get class functions we have developed a number of other functions that help print strings numbers as well as directly access the USART transmit buffer so you can mix and match you serial library use as you wish or write you own The UART and RS 232 module header CHAM UART DRV VO010 h has a few globals as well as the defines so at least there is something interesting to talk about Let s begin with the defines default baud rate define UART DEFAULT BAUDRATE 115200 slow down to 57600 38400 if you have trouble transmit and receive buffer constants define UART TX BUFF SIZE 32 define UART BUFF SIZE 32 The defines are trivial simply a constant for a convenient baud rate as well as the size of the circular buffers You can make these any size you wish but memory is at a premium so keep it in mind If you are going to be using a lot of serial communications and know you are going to send large strings or receive large strings and not be able to interrogate the 147 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit buffer functions then you might want to increase the buffers to 64 128 256 etc But for now 32 32 seems to work find in all examples Next are all the global data structures and variables used by the API
226. ce Disabled Welcome to AVR Studio 4 r Create new project Project type Project name Atmel AVR Assembler Create initial file Create folder Initial file Location D development chameleon cham_avr source sm Address Value Bits lt lt Back Finish Cancel Help Message Loaded plugin 5 500 a Message Find in Files Breakpoints and Tracepoints CAP NUM OVR Hopefully you see something similar to this However it s possible that some of the tools in different locations or not at all eg the I O view and Processor state Any of these differences can be remedied at a later time from the Main Menu under View Toolbars Now let s get to work The first step to setting up the tool is to create an initial project The New Project dialog is shown in Figure 15 19 below 86 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 19 Setting up the New Project dialog correctly Welcome to AVR Studio 4 Create new project Project type Project name Atmel AVR Assembler cham avc work 01 AVR GCC le Create folder Location D Adevelopment chameleon cham_avr source Ver 4 16 638 lt lt Back Finish Cancel Make the following changes to the default dialog so we have the same project Select AVR GCC This tells the tool that we want to us
227. course the Propeller will do this for us via the VSU and a driver but there is no reason you can t drive the I O pins manually with pure software as well Either way let s take a look at the mechanics of the signal On the Chameleon AVR for example there are 2 bits per channel so the encoding of the VGA data byte is as simple as generating bytes in the format shown in Figure 10 4 Figure 10 4 VGA data byte encoding I O P23 P22 P21 P20 P19 P18 P17 P16 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit O RL RO Gl GO Bl BO VSYNC HSYNC Red Signal Green Signal Blue Signal Sync Signals Let s say that we have a BYTE buffer called vga byte and a function Write VGA value time us that we use to send data to the VGA port given that we can write all kinds of functions that send out different signals as long as we stream the bytes to the port at the 25 175MHz rate everything will work out fine For example say that we are working with a positive sync system that is a VGA monitor that wants a TTL HIGH for sync then to generate a Hsync pulse we could use some pseudo code like this vga byte 0b00000010 Write VGA vga byte 3 77 Ok now consider we want to draw 640 pixels from an array video that is storing the pixel data in byte format already in the proper format for our hardware then all we would do is this UCHAR video buffer 640 pre initialized video bu
228. curate as possible but no warranty or fitness is implied The information provided is on an as is basis The authors and the publisher shall have neither liability nor any responsibility to any person or entity with respect to any loss or damages arising from the information contained in this user manual The example companies organizations products domain names e mail addresses logos people places and events depicted herein are fictitious No association with any real company organization product domain name e mail address logo person place or event is intended or should be inferred eBook License This electronic user manual may be printed for personal use and 1 copy may be made for archival purposes but may not be distributed by any means whatsoever sold resold in any form in whole or in parts Additionally the contents of the DVD this electronic user manual came on relating to the design development imagery or any and all related subject matter pertaining to the CHAMELEON systems are copyrighted as well and may not be distributed in any way whatsoever in whole or in part Individual programs are copyrighted by their respective owners and may require separate licensing NURVE NETWORKS LLC END USER LICENSE AGREEMENT FOR CHAMELEON AVR HARDWARE SOFTWARE EBOOKS AND USER MANUALS YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS BEFORE USING THIS PRODUCT IT CONTAINS SOFTWARE THE USE OF WHICH IS LICENS
229. d be amazing to you that in a few lines of code you are generating a NTSC color text display Reviewing the code the program starts waits for the Propeller to boot don t forget to do this then the call to clear the screen and we enter the main while loop Here a redundant call to set the color is made and the text is printed to the NTSC terminal with NTSC Term Print that s it 212 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Summary This demo shows how easy it is to get NTSC terminal like text output going on the Chameleon 28 1 2 NTSC Glowing Top Bottom Overscan Demo This demo simply uses the NTSC tile graphics engine extensions to glow the top and bottom overscan colors on the display The default2 driver uses a high performance tile engine that we developed that supports scrolling 4 colors per tile large playfields and a lot of more One of its simple features is the ability to control the top and bottom over scan colors on the screen This demo simply cycles thru those colors and shows you how to make calls to update the overscan color registers in the tile engine running on the Propeller chip Figure 28 2 shows the demo in action Figure 28 2 NTSC overscan color animation program demo Cylone Base Star to Gutpost Message Destroy Destroy Destroy BY YOUR COMMAND Compiling and Running the AVRStudio Version Demo Version Description NTSC version prints animates overscan col
230. d int UINT generic input device data record type helps get back data from various multidata calls struct gid_event_type int 2 position data int buttons buttons bit encoded bit4 right side button bit3 left side button bit2 center scrollwheel button bitl right button bitO left button gid_event gid_event_ptr Lastly so that the user can change the system frequency if he wishes during run time there is a variable shadow of the F_CPU constant that is loaded with said constant during startup Thus the variable is used in the Chameleon API library for calculations This gives it typing information and as noted the ability to be changed during run time here s the declaration extern unsigned long f_cpu That wraps it up for the header file declarations The remainder of the header file is simply the prototype listing for the functions themselves which we will see in the next section 17 1 2 API Listing Reference The API listing for the System module CHAM_AVR_SYSTEM_V010 c is quite short As said this C file is a placeholder for future functionality that relates to system level housekeeping and utility functions so at this early stage there isn t much here Considering that Table 15 3 below lists the System API functions categorized by functionality Table 15 3 System module API functions listing Function Name Description Time and Counting void
231. d peripherals as software Figure 1 9 The Propeller pinouts Ga 1 P31 2 CP30_ Ga 3 P29 4 P28 Cpa 5 Gap 6 CP26_ Gap 7 P25 2 8 P24 4 VSS VDD 5 BOEn 6 7 RESn 8 VDD VSS 9 0 AYWWXZZ PB P23 P9 P22 P21 P20 LQFP and QFN Packages DIP Package P15 P16 As you can see the Propeller chips have nothing more than power reset clock and 32 I O pins There are no dedicated peripherals whatsoever actually that s not completely true each core has video hardware Table 1 4 Propeller pin and signal descriptions Eon Description PO P31 General purpose I O Port A Can source sink 40 mA each at 3 3 VDC CMOS level logic with threshold of 1 2 VDD or 1 6 VDC 3 3 VDC The pins shown below have a special purpose upon power up reset but are general purpose afterwards P28 126 SCL connection to optional external EEPROM P29 12C SDA connection to optional external EEPROM P30 Serial Tx to host P31 Serial Rx from host VDD 3 3 power 2 7 3 6 VDC md 24 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Brown Out Enable active low Must be connected to either VDD or VSS If low RESn becomes a weak output delivering VDD through 5 kQ for monitoring purposes but can still be driven low to cause reset If high RESn is CMOS input with Schmitt Trigger Reset active low When low reset
232. d rather than 3 thus even more steps have to be performed for larger more complex operations 135 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 16 5 The virtual drivers used for the project Main SPI Command Dispatcher Drivers cham default2 drv 111 spin gt CHAM GFX 001 TB 001 cjl _ top level object Half Height 011 spin UID essa gt VGA Tex 010 Opny gt NS sound_drv_052_11khz_16bit spin keyboard_010 spin mouse_010 spin Y pueoghey leues gt FullDuplexserial_drv_012 spin Optional 16 4 Virtual Peripheral Driver Overview There isn t much to say about the drivers used on the project other than went to the Parallax Object Exchange located here http obex parallax com objects and hunted around for appropriate objects to use for this project based on my experience with developing objects and using them The objects aren t the fastest the coolest or the best necessarily they just work and get the job done and in most cases are the reference objects developed by Parallax initially with small changes by myself and other authors The idea was to have the NTSC VGA audio and keyboard mouse all running at the same time and be able to access these devices In the future you might want to use other objects or improve these for more specific needs I
233. d the tool will have the proper source data Realize that every time you re compile and build the project the HEX file for the project is also updated thus the programming tool always points to the latest and most updated HEX file At this point we still are not ready to program the unit we need to set the Fuses and Lockbits tabs properly So make sure your Program tab looks like the image shown in Figure 15 37 and then select the Fuses tab You should see something like that shown in Figure 15 38 Figure 15 38 The AVR ISP MKII control panel s Fuses tab AVRISP in ISP mode with ATmega328P Main Program Fuses LockBits Advanced Hw Settings Hw Info Auto Fuse i Value BODLEVEL Brown out detection disabled RSTDISBL DWEN SPIEN WDTON EESAVE BOOTSZ Boot Flash size 1024 words start address 3C00 BOOTRST CKOUT SUT_CKSEL Ext Crystal Osc 8 0 MHz Start up time PWRDWN RESET 16K CK 14w EXTENDED OxFF HIGH OxDA LOW OxDF Auto read Smart warnings Verify after programming Program Verify Setting mode and device parameters OK Entering programming mode OK Reading fuses address 0 to 2 OxDF OxFF Leaving programming mode OK The Fuses tab controls a set of internal processor fuses that are no part of the FLASH or EEPROM memories Rather the fuses control the personality of t
234. d them on DVD located here DVD ROM CHAM_AVR TOOLS VT100 terminal running the Chameleon s serial port connected to the PC with the following settings on your terminal Data Format N81 no parity 8 data bits 1 stop bit Baud Rate 115 200 Handshaking None Terminal Mode VT100 Screen Size 80x24 or larger 120x50 is a good choice Local Echo Off Make sure that you have the serial selection switch in the DOWN position on the Chameleon AVR mode What we are going to focus on here is taking full advantage of the serial UART code and making alittle Guess My Number game that runs on the Chameleon AVR but communicates via serial to a VT100 terminal running on the PC Figure 31 2 shows the demo program running Figure 31 2 Guess My Number running on the PC terminal need new image 58 COM31 PuTTY XGS WarGames 2019 Would you like to play a game yes or no y The screen shot doesn t do the demo justice since there are sound effects and ASCII animation that occur When you run the demo you might have to hit RESET on the Chameleon a couple times to really appreciate the retro feel of the demo What did was play a bit on the 1980 s classic WarGames starring Mathew Broderick It s one of my favorite movies and if you haven t seen it definitely fun to watch The movie s plot was a teenage kid tried to hack into some Silicon Valley computer game company but instead modem ed into the WOP
235. d to represent everything you do with Propeller video for example syne black color burst and active video By setting different bits you can create colors that represent these signals For example Table 22 1 below shows how to create black sync color burst shades of gray and colors with any intensity Table 22 1 Color encoding for various color values Desired Signal Bit encoding Sync 0 0 0 0 0 0 0 0 Control Values Group Black 0 0 0 0 0 0 10 Dark Grey 0 0 0 0 0 0 1 1 Grey 0000 0 1 0 0 Grayscale Values Group Light Grey 0 0 0 0 179 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Bright Grey 0 0 0 0 0 110 white 0 0 0 0 Blue 0 0 0 0 0 0 ES EX EX where 011 lt lt 110 22 5 C STE 1 X XX i e 3 lt xxx lt 6 Purple 45 0 00 1 0 il eC Magenta 67 5 0 0 1 1 TU SE 90 0 0 1 0 0 1 eyes us Red 112 5 at 1 X Orange 1535 9 ia 3 T EX Brown SS Color Values Group Yellow 180 0 1 0 0 0 1 XXE Yell Grn 202 5 1 00 1 XX Green 225901 TX al ak at db X 24 at XC cyan 262 5 dt 3 1 1 XXE X 3 15 50 ily 0 1 5 3 37 5 0 STIS NOTE 1 Colors without_names linear mixes of the colors before and after NOTE 2 when chroma color is enabled the signal is modulated 1 Ref
236. da se eni rni Uns Eia duum lE Ke an oS 65 14 1 A Little Background on Low Pass Filters EE stuff 1 eee eee esee eese eene eene ee etn esee tn tense 66 14 1 1 Pulse Code Modulation rien nass 67 14 1 2 Fregu ncy Modulation oet de diete Hb e Here 68 14 1 3 Pulse Width Modulation nsns esee eniin assess esee nnns seen nnn 68 15 0 INSTALLING THE TOOL CHAINS AVRSTUDIO ARDUINO AND PROPELLER IDE 75 15 1 ATMEL S AVR STUDIO TOOLCHAIN nnmnnn 76 15 1 1 Installing AVR Studio 4 xx Optional ssccssscssssccssecsssscssssessssessssscsssecsssscssseessssesssscsssscsssscssssessssssosscossscosssoocssooees 77 15 1 2 Installing the AVR ISP Hardware Optional sccssscsssssssssecsssecsssecsssssssssessssecsssssssssesssssssssscsssesssssessesesseseoes 81 15 53 dnistalling WinA V RU iiu 82 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 1 4 Building a Project and Testing the Tool Chain ssccsssssssscssscssssessssecsssscssssesssssscssscsssssssssessssesssscsssscosssescsssssess
237. data bootloader Reading FLASH input file OK Setting mode and device parameters OK Entering programming mode OK Erasing device OK Programming FLASH Data 26 bytes 1 3 Full data bss noinit E Build Message Find in Files feakpoints and Tracepoints ATmega328P AVRSimulator2 Auto If all works out immediately after the download the AVR ISP will reboot the Chameleon AVR and you should see on your NTSC VGA displays the Hello World demo running as shown in Figure 15 30 Go ahead and press the RESET button on the Chameleon to restart the hardware At this point you can edit the hello world program and make changes to it If you do suggest you save as another name then remove the original from the source tree and add your modified version This way you will always have the original on your hard drive Of course the original sources can always be re copied from the DVD ROM but that s inconvenient 104 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 1 7 Final Words on AVR Studio Tool Chain Installation This completes our installation of the toolchain all its components and a complete example of building and downloading an application As we develop applications load demos and experiment you will only have to modify the source files in the project pane to the left adding and subtracting source files The programming tool
238. dditionally you can use the 1MByte SPI FLASH on the Chameleon as well for storage FLASH memories typically have a maximum number of times they can be written something in the range of 10 000 to 100 000 This doesn t mean that at 10 001 or 100 001 the memory won t work it just means the erase cycles and write cycles may take longer to get the memory to clear or write And this then degrades further as the write erase cycles persist Thus if you were to code all day and re write your FLASH 100x times a day then at 100 000 re write cycles you would have 3 4 years before you ever saw any problems On the other hand if you write code to use the FLASH as a solid state disk and constantly re write the memory 10 000x a run you can see how quickly you might degrade the memory Thus use the EEPROM for memory you need to update and still be non volatile and save the life of the FLASH Table 1 2 Differences between ATmega 48P 88P 168PP and 328P Device Flash EEPROM RAM gt ey 48 4K Byte 256 Bytes 512 Bytes 88 8 K Byte 512 Bytes 1 K Byte 168 16K Byte 512 Bytes 1 K Byte ATmega328P 32K Byte 1 K Byte 2 K Byte Note The P suffix simply means Pico Power and has nothing to do with the chip operation or functionality The Pico power version is identical to the non pico power for our purposes and will use them interchangeably Figure 1 5 shows the AVR 328P architecture in
239. ded avr avrlib http ccrma stanford edu courses 250a docs avrlib html index html http ccrma stanford edu courses 250a docs avrlib html install html The bus is a little more complex that the SPI bus interface and protocol The reason is that the bus uses only 2 signal lines SDA data SCL clock thus more protocol and conventions must be adhered to to deal with bus contention etc secondly supports up to 128 devices simultaneously connected to the bus This feature makes superior for daisy chaining devices together with as well as cheaper Of course you never get something for nothing 155 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit and the bus is not without its shortcomings First it is nowhere near as fast as SPI SPI can operate at 25 MHz and even up to 50 MHz on the other hand averages around 100 2 with 400 KHz being fast with many new devices supporting 1Mhz Thus SPI is at least 25 times faster But that s not the whole story The added overhead that protocol attaches to communication addressing commands etc slow the protocol even more Thus devices tend to find there way into slow peripherals where speed isn t and or issue but addressing many of them For example serial memories sensors etc where the device itself is slow the 100 400 KHz average speed of is more than enough However SPI devices you will see in very high speed applic
240. ded systems are very unique in that they are very constrained have little memory and resources So any function that you use from the standard C library Libc emulates what you might expect on a PC platform but in many cases the behavior might not be as expected Thus you need to take care when using standard library functions and realize that they may have side effects or limitations that VC or GNU C on your PC do not Please refer to the AVR Libc manual located here on the DVD ROM for a complete overview of the library DVD ROM CHAM_AVR DOCS avr libc user manual 1 4 6 pdf Additionally a great resource for the library is the developer s website itself http www nongnu org avr libc There are lots of tricks and tips to using the AVR Libc functionality on there However for the most part as long as you don t push it you can use standard C functions and everything will work out Of course you have to have common sense when using functions For example on a PC the function printf makes sense since there is some kind of terminal 139 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit device On the Chameleon AVR this won t work since the developer of AVR Libc has no idea about the Chameleon AVR thus anything that is hardware specific won t work since Libc has no idea about the hardware On the other hand you might ask is it possible to get printf to work The answer is yes However you would have t
241. determine if the transmitter is complete and or receiver has shifted in results before writing more data The AVR SPI hardware supports this kind of system as well as full interrupt based systems Finally the function returns the 8 bit data shifted back to the Master from the Slave Example s Example 1 Write a value to the SPI interface channel 1 assumes its been initialized set CS to SPI select select device channel 1 SPI CS PORT 0 lt lt SPI CS1 1 lt lt SPI CSO now write the data dummy SPI WriteRead power and disable the chip select lines set to NULL device 0 SPI CS PORT 0 lt lt SPI CS1 0 lt lt SPI CSO Notice that we always assert then de assert the chip select line so that the SPI device comes online In some case you might want to keep the SPI device selected enabled at all times as long as you don t have other SPI devices on the bus that can contend with the SD SPI interface Example 2 Read 512 bytes from the SPI interface device 1 assumes its been initialized somehow and store in an array set CS to SPI select select device channel 1 SPI CS PORT 0 lt lt SPI CS1 1 lt lt SPI CSO read data note that a dummy value of OxFF is sent each time for Cindex 0 index 512 index data index SPI writeRead OxFF 164 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit and disable the chip select l
242. ds with acknowledge FA then sends a movement data packet This is the only way to read data in Remote Mode After the data packet has been successfully sent the mouse resets its movement counters Set Stream Mode The mouse responds with acknowledge then resets its movement counters and enters Stream mode Status Request The mouse responds with acknowledge then sends the following 3 byte status packet then resets its movement counters as shown below Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Byte 1 Always 0 Mode Enable Scaling Always 0 Left Button Middle Button Right Button Byte 2 Resolution Byte 3 Sample Rate Right Middle Left button 1 if button pressed 0 if button is not pressed Scaling 1 if scaling is 2 1 0 if scaling is 1 1 Refer to commands E7 and E6 Enable 1 if data reporting is enabled 0 if data reporting is disabled Refer to commands F5 and F4 Mode 1 if Remote Mode is enabled 0 if Stream mode is enabled Refer to commands F0 and EA Set Resolution The mouse responds with acknowledge FA then reads the next byte from the host and again responds with acknowledge FA then resets its movement counters The byte read from the host determines the resolution as follows Byte Read from Host Resolution 00 1 count mm 01 2 count mm 02 4 count mm 03 8 count mm Set Scaling 2 1 The mouse responds with acknowledge FA then enables 2 1 scaling mode Set Scaling 1 1 The m
243. e these commands are DANGEROUS since you can break the COG with them and require a reset so if you are going to write directly to the registers be careful define REG CMD WRITE 56 performs 32 bit write to the addressed register 0 F from the output register buffer define REG CMD READ 57 performs a 32 bit read from the addressed register 0 F and stores in the input register buffer define REG CMD WRITE BYTE 58 write byte 0 3 of output register g reg out buffer byte 0 3 define REG CMD READ BYTE 59 read byte 0 3 of input register g reg in buffer byte 0 3 system commands define SYS RESET 64 resets the prop M E EE LL ALLE ommands in th is range for future expansion The commands are fairly straightforward and if there is anything that you want more detail on you can always open up the Propeller driver file s spin code and see exactly how the command is processed Remember all of these commands work in the same way they are sent over the SPI interface to a command dispatching loop on the Propeller a large case statement catches the commands and then sends it to the appropriate driver graphics sound keyboard etc So there are a lot of commands but each one is rather simple when you follo
244. e Technical Overview The demo simply uses the NTSC API to print Hello World on the screen When the printing reaches the bottom of the screen the terminal scrolls the screen image up one line The program is so short let s take a quick peek at only the contents of the main or loop in the Arduino version MAIN int main void initialize and set SPI rate SPI_Init SPI_DEFAULT_RATE give Prop a moment before sending it commands the boot process is about a second if you like you can speed it up by removing the Prop driver s LED blink sequence in the driver or speed it up but commands that are sent before the Prop driver is done booting will be ignored therefore if you have a lot of set up work to do then you don t require a delay but if you jump right into commands then you need a good 1 5 2 second delay _delay_ms 2500 clear screens NTSC Clearscreen enter infinite loop SE print on NTSC terminal screen NTSC 1 0 NTSC Term Print Hello world i slow things down a bit so we can read the text _delay_ms 10 end while end main First it shoul
245. e The Sound module header CHAM AVR SOUND DRV V010 h has nothing in it except the prototypes for the handful of functions Rather it makes more sense to show you the SPI header messages relating to the sound driver sound commands define SND CMD PLAYSOUNDFM 40 plays a sound on a channel with the sent frequency at 90 volume define SND CMD STOPSOUND 41 stops the sound of the sent channel define SND_CMD_STOPALLSOUNDS 42 stops all channels define SND_CMD_SETFREQ 43 sets the frequency of a playing sound channel define SND_CMD_SETVOLUME 44 sets the volume of the playing sound channel define SND_CMD_RELEASESOUND 45 for sounds with infinite duration releases the sound and it enters the release portion of ADSR envelope The above messages are located in CHAM_AVR_TWI_SPI_DRV_V010 H as well as in the main SPI driver running on the Propeller CHAM DEFAULT2 DRV V112 spin or CHAM DEFAULT1 DRV V112 spin The above messages only expose rudimentary abilities of the sound driver but they are enough to start and stop sounds play music sound fx etc The API listing for the Sound module CHAM SOUND V010 c is listed in Table 23 1 categorized by functionality Table 23 1 Sound module API functions listing Function Name Description Playing a Sound int Sound_Play int channel int frequency int duration Plays a sound on one of the 4 channels Stopping Sounds int Sound_Stop int channel Stop
246. e C C and GCC ASM Check Create Folder and uncheck Create Initial File Type in cham avr work 01 under Project Name Under Location browse to your install directory s source sub directory or wherever you want to put projects we will put all projects in there After you make these changes you should have something that looks like Figure 15 19 Also it s important you use the project name cham avr work 01 since will refer to that from time to time and this will be the directory we will copy data to However in the future you can create as many projects as you wish with whatever names you wish Just make sure to place them all in their own directories so you don t have file collisions Once complete go ahead and click Next to move onto the section of the Debug Platform as shown in Figure 15 20 Figure 15 20 AVR Studio selection of the Debug Platform Welcome to AVR Studio 4 Select debug platform and device Debug platform Device AVR Dragon AVR ONE AVR Simulator AVR Simulator 2 ICE200 ICE40 ICE50 JTAG ICE JTAGICE mkll Ver 4 16 638 lt lt Back Finish AVR Studio supports all kinds of programmers debuggers hardware and software tools This dialog helps you select the programming device along with the target device you will be working with In our case under Debug Platform select AVR Simulator 2 along with ATmega328P under Device The software sim
247. e Chameleon AVR consist of a number signals that interface to both the AVR and Propeller chip The Propeller chip has its own 8 bit local I O port located right under the composite video and PS 2 ports The other headers surrounding the Chameleon PCB interface mostly to the AVR chip Let s take a look at the PCB for a moment for reference as shown in Figure 13 1 Figure 13 1 The Chameleon s annotated I O headers 415VCC 1 GNDZ 1521 551 229 Ej1 SPI 550 41 AIN5 4 AIN4 ENTIER AIN1 1 63 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Referring to the figure there are two 8 pin I O headers on the bottom of the board A single 16 pin header on the right and finally the 8 bit Propeller local port The Propeller local port is discussed elsewhere so let s concentrate on the other 3 headers First off on the Chameleon AVR version specifically we tried to map the Arduino compatible signal names to the same pins on the 328P chip so programs written for Arduinos mmm that use digital would work with little modification Similarly we used the name naming conventions for the signals such as Dn for digital l Os and AINn for analog inputs However the Chameleon has a few extra signals mostly on the larger 16 pin header on the right Signals such as the multiple power sources as well as the SPI multiplexer chip selects SPI SS1n and SPI SSOn resp
248. e a couple lines at the top advanced GFX commands for GFX tile engine define GPU GFX BASE ID 192 starting id for GFX commands to keep them away from normal command set define GFX NUM COMMANDS 37 number of GFX commands 181 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit These are important since they give the base offset for these commands 192 and there are 37 So from 192 to 192 37 1 we know are graphics commands Thus in the graphics driver it will get these messages since the SPI message dispatcher is looking for this range If we open up the Default2 driver we can see this as shown below now process command to determine what user is client is requested via spi link case g cmd GFX NULL GFX GPU TILE ENGINE COMMANDS P MM PPP P P gg PPP PP Pg PPP PP P P P P gg M MP P Pg TTT TTT NTSC GFX TILE SPECIFIC COMMANDS PH M HIE EH LEE E EE TLL we only expose a subset of the commands driver supports you can add subtract more commands as desired some commands like PRINTCHAR for Bape support number of sub commands that don t need to expose at this level unless we want to add funcitonality GFX_CMD_NTSC_PRINTCHAR this command pipes right to the out function of the driver which supports the fol lowing sub commands already 00 clear screen 1 01 home 08 backspace 09 tab 8 spaces per 0A set X
249. e allows you to more or less run anything you would run on a HYDRA or Propeller Development kit still You have the VGA connector PS 2 A V connectors as well as an 8 bit port for expansion You might have to do some porting of apps since the HYDRA and Propeller development kits use slightly different pin connections for various devices but those are literally 1 2 line changes in your code The only thing you loose in Propeller stand alone mode is the use of the onboard FLASH since the Propeller can t get to it but the EEPROM for the Propeller is 64K 2x the amount needed for the boot image so that s a conciliation prize in the design if you need more assets Just make sure to keep the serial select switch in the UP position so the Propeller has access to the USB serial port 261 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Appendix Porting HYDRA and Parallax Development Board Applications to the Chameleon There really isn t much to say here other that porting from the HYDRA or Propeller Development board is usually a few lines of code that needs to be changed The things to watch out for are Make sure that you are using the same clocking and XTAL the HYDRA Dev Board application you are trying to port uses a 10MHz XTAL and the 8x mode then make sure you change it to 5MHz and 16X mode in the Source code port assignments The Chameleon s Propeller interfaces are almost the sa
250. e better be on the MISO MOSI SCLK lines at any time Considering this when you write code to control the SPI interface for example before you make calls to SPI write and read functions you will need to asserts the proper SPI CS or appropriate SPI mux chip selects SPI 0 SPI CS1 to your SPI device while making sure all others are de asserted Returns 1 always Example s Example 1 Initialize the SPI hardware and set speed to main clock divided by 128 the slowest rate SPI Init SPI FOSC 128 It is important to remember that the SPI s built in CS line is not used to select anything Instead a pair of digital I O lines are used as SPI select selection bits and are multiplexed to select 1 of 4 devices named 0 3 The signals in the Chameleon design are on Port C define SPI 50 PC2 define SPI C81 To select device 0 3 you simply place 00 015 105 11 on these pins 11 3 selects the FLASH 10 2 selects the Propeller as destination The other two unused selectors are exported off the I O headers to support other SPI devices you might connect For example to select the Propeller chip you would use the following code Programming Sidebar set CS to SPI select select Prop SPI channel 2 SPI CS PORT 1 lt lt SPI CS1 0 lt lt SPI CS0 And to de select the Propeller and select device 0 null device you would use set CS to SPI select channel 0 null SPI CS PORT 0 lt
251. e is very nice but SPIN takes a bit to get used as does the editor which uses indentation like Python for block level This can be frustrating for C C programmer initially You can read about programming the Propeller chip here DVD ROM CHAM AVR TOOLS PROPELLER Propeller Manual WebPM v1 1 pdf DVD ROM CHAM AVR TOOLS PROPELLER PropellerDatasheet v1 2 pdf Also there is a single book about developing games and media applications for the Propeller chip Game Programming the Propeller Powered HYDRA by Andre LaMothe The installation procedure for the Propeller IDE is very simple and consists of the Propeller tool itself along with some Virtual COM port drivers developed by FTDI inc that are needed to communicate with the Propeller Chip itself These drivers are installed as part of the installer program if everything goes smoothly However you might recall we have already installed the FTDI drivers while setting up the Arduino tool As you can see everyone seems to use FTDI chips Step 1 Locate the Propeller IDE installation program Setup Propeller Tool v1 2 6 exe on the DVD here 121 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit DVD ROM CHAM_AVR TOOLS PROPELLER Setup Propeller Tool v1 2 6 exe and launch it you will see the installer splash screen as shown in Figure 15 59 below Click lt NEXT gt Figure 15 59 The Propeller IDE installation splash screen your version might vary
252. e pin for the Analog to digital Converter The AVR 328P is a 8 bit RISC like architecture chip with instructions being either 16 or 32 bits in size mostly 16 bit The memory model is a Hardware Architecture meaning that the data and memory are located in separate memories that are not addressed as a contiguous space but rather as separate memories with different instructions to read write to them This allows faster execution since the same buses aren t used to access data and program space Therefore you will typically access SRAM as a continuous 2K of memory and program FLASH memory is in a completely different address space as is EEPROM memory Thus there are 3 different memories that the AVR 328P supports Additionally the AVR 328P maps registers as well as all it s I O ports in the SRAM memory space for ease of access Figure 1 6 show these memories Harvard as opposed to Von Neumann architecture are the two primary computer memory organizations used in modern processors Harvard was created at Harvard University thus the moniker and likewise Von Neumann was designed by mathematician John Von Neumann Von Neumann differs from Harvard in that Von Neumann uses a single memory for both data and program storage Figure 1 6 FLASH and SRAM memory layouts Program Memory Data Memory 0x0000 0x0000 0x001F 64 I O Registers 0 0020 0x005F 160 Ext I O Reg 0 0060 OxOOFF 0x0100 Internal SRAM 512 1024 1024 2048 x 8
253. e pole RC filter Frequency f Hz Comments a eee 0 1 1 DC gain is 1 0 or no attenuation 1 1 2 PI RC 1 1000 1 1 2 PI 1000 RC 1 000 000 1 1 2 P1 1 000 000 RC This is very interesting ignoring for a moment the actually values of RC we see that very quickly larger values of f frequency very quickly dominate the denominator and the quotient goes to 0 This is why this filter is called a single pole as the term in the denominator goes to infinity the quotient goes to zero Ok so how does this help us Well if we select values of RC we can tune the frequency that this attenuation gets really strong This is typically called the 3dB point that is the point where the signal is attenuated by 3dB decibels not really important to know what a decibels is it s a measure of power or ratio of signals more or less but what is important is that is about 70 of the signal so if you want to filter out everything above 10KHz you would set the 3dB point for about 10KHz maybe a bit more and you 66 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit would see the signal get filtered Also note that at DC frequency f 0 the right hand term in the denominator sum 1 2 0 1 thus the gain is 1 1 or 1 0 which is exactly what it should be Cool huh Filters can be a lot of fun since you can chain them together low pass high pass to make a band pass or multiple low and high pass to make th
254. e the USB cable plugged into the Chameleon power is ON and the serial selection switch is in the UP position When you are ready then you can press lt F11 gt on the Propeller Tool or from the main menu you can select lt RUN gt Compile Current gt Load EEPROM the results will be the same the Propeller tool will scan all COM ports for a connection to a Propeller chip and then compile and download the firmware to the Chameleon This is shown in Figure 15 67 125 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 67 Downloading the firmware into the Propeller Chip Propeller Tool cham default2 drv 111 File Edit EN Help View Info F8 defaul2 drv 111 Q vc cone T Top gt Update Status F9 P mouse_010 3 in_default2_drv_111 spin NS_sound_dry_052_11khz_16bit 4 WU NR Andre LaMothe CHAM GFX DRV 001 TB 001 5 LRST TED 8 19 09 6 VERSION 1 11 8 COMMENTS This is the Chameleon generic driver Default 2 It s 9 good example of interfacing to multiple drivers on the Propeller ch my HEL tile engine to augment the graphics on the NTSC screen and 1 this driver is the same as the Defaultl driver This driver simpl 12 commands that work on the NTSC Default driver work here Thus as 13 you should use the higher performance Default version But botton tl ZI 14 these are just examples 3 Floppy 15 x
255. eceive doesn t use the interrupt system The function interrogates the UART hardware directly and checks if the receive buffer has a character in it if so the function returns it However the function can work in two different modes blocking and non blocking That is you can call the function with a wait 1 and the function will wait for a character or wait 0 and the function will not wait for a character and return immediately if a character isn t ready In either case the function returns the character in the receiver buffer or 1 if a character isn t ready Note that if you set wait 1 the function could theoretically wait forever Example s Wait for the character X when received blow up the world amp wait for the x while UART Receive 1 x 151 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit call the mainframe computer in Zion and execute its last command Blow Up The worldO 19 0 SPI Library Module Primer The SPI and module consist of a single C source file and a number of functions for initialization transmission and reception The SPI module is one of the most important in the system since all communications with the Propeller chip are performed via the SPI hardware The API consists of the following files listed below CHAM AVR TWI SPI 010 file source for SPI and module CHAM AV
256. ectively Figure 13 2 below illustrates the electrical design of the headers themselves laid out as they are on the PCB Figure 13 2 headers electrical design J7 GND GND RESn 33VCC 5VCC GND GND VIN Arduino Compatible I O mS J6 SPI SS1n SPI SSOn AINS AIN3 AIN2 AINO CONN SIL8 J5 J4 AREF DPINT GND DPING DPIN13 DPIN5 DPIN12 DPIN4 DPIN11 DPIN3 DPIN10 DPIN2 DPINS DPINS 1 DPINO CONN SIL8 CONN SIL8 Also the pins on the headers obviously connect to multifunction pins such as the serial UARTS SPI and so forth Table 13 1 below maps the header pin names to the physical pin names and numbers for your convenience Table 13 1 I O header pinout map 1 0 Header Header Pin Name AVR Pin AVR Pin Name Extra Function AREF 21 AREF GND 8 22 GND DPIN13 19 PB5 SCK PCINT5 DPIN12 18 PB4 MISO PCINT4 DPIN11 17 PB3 MOSI OC2A PCINT3 DPIN10 16 PB2 5 PCINT2 DPIN9 15 PB1 OCA1 PCINT1 DPIN8 14 PBO PCINTO CLKO ICP1 JA DPIN7 13 PD7 PCINT23 AINT DPIN5 PCINT21 T1 J4 DPIN4 6 PD4 PCINT20 XCK TO 64 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit J4 DPIN3 5 PCINT19 OC2B INT1 J4 DPIN2 4 PCINT18 INTO ee T a J6 SPI_SSin NA NA J5 AIN4 27 ADC4 SDA PCIN12 J6 AIN3 26 PC3 ADC3 PCINT1
257. ed NTSC driver CHAM DEFAULT2 112 SPIN we are using the following Propeller Object for the VGA tile engine and text display Text 010 spin VGA tile engine with support for terminal mode graphics with a tile resolution of 32x15 Very stable but limited Unlike the NTSC driver we are using the same VGA terminal driver for both Default1 and Default2 Propeller drivers so it doesn t matter which you are using the same rules apply The VGA standard is much higher resolution thus this driver is much less capable than the NTSC driver However you can always use a more advanced VGA driver and modify the Propeller message dispatcher but we choose this one to get you started since it requires only a single processing core and many of the more advanced VGA drivers require 2 or more cores to generate higher resolutions and capabilities But again the point is you can change the Propeller driver and re write it as you wish we simply give you a starting point to get going with So if you want to know what the driver supports you can always peek into the driver itself 171 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit VGA_Text_010 spin which calls sub objects and to see the messages that are getting passed to it you always look into the CHAM_DEFAULT2_DRV_112 SPIN driver itself With that in mind if you want to use the NTSC driver then you need the following files added to your project CHAM_AVR_VGA_
258. ed or exported into any other country or used in any manner prohibited by any government agency or any export laws restrictions or regulations f You may not publish or distribute in any form of electronic or printed communication the materials within or otherwise related to Licensed Works including but not limited to the object code documentation help files examples and benchmarks TERM This Agreement is effective until terminated You may terminate this Agreement at any time by uninstalling the Licensed Works and destroying all copies of the Licensed Works both HARDWARE and SOFTWARE Upon any termination you agree to uninstall the Licensed Works and return or destroy all copies of the Licensed Works any accompanying documentation and all other associated materials WARRANTIES AND DISCLAIMER EXCEPT AS EXPRESSLY PROVIDED OTHERWISE IN A WRITTEN AGREEMENT BETWEEN LICENSOR AND YOU THE LICENSED WORKS ARE NOW PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND EITHER EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR THE WARRANTY OF NON INFRINGEMENT WITHOUT LIMITING THE FOREGOING LICENSOR MAKES NO WARRANTY THAT i THE LICENSED WORKS WILL MEET YOUR REQUIREMENTS ii THE USE OF THE LICENSED WORKS WILL BE UNINTERRUPTED TIMELY SECURE OR ERROR FREE iii THE RESULTS THAT MAY BE OBTAINED FROM THE USE OF THE LICENSED WORKS WILL BE ACCURATE OR RELIABLE iv THE QUALITY OF
259. eeded for UGA driver 7 DEFINES AND MACROS Us Save Gcc DAdevelopmentichameleonYcham avrsourcevcham avr work 01XCHAM AVR HELLO WORLD 01 1 Build x Device 328 Program 2016 bytes 6 2 Full text data bootloader Data 26 bytes 1 3 Full data bss noinit Build succeeded with 3 Warnings lt t AYR Studio Go ahead and scroll thru the output window so you can see all the compiler and linker output You will notice quite a few warnings these are fine and normal unless you want to program like a monk At this point we are still not ready to program the Chameleon with AVR Studio There is one more step we have to setup yet another tool the AVR ISP that is if you re not using the Arduino tool chain Although we installed the driver and hardware for the AVR ISP programmer we didn t configure the tool chain inside of AVR Studio yet to use it This is what we need to do next Of course if you don t have the AVR ISPMK II programmer then you can skip this sect
260. eliver the unit with In this case make sure you 210 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit have the serial select switch on the Chameleon in the down position so the PC can get to the serial port of the AVR since this is how the bootloader works via serial 28 1 Graphics Demos The following graphics demos illustrate examples in both NTSC and VGA modes as well as use of the advanced tile modes of the NTSC driver Each example will typically consist of the primary source file for the demo as well as System API library module CHAM AVR SYSTEM V010 c h main SPI API library module CHAM AVR TWI SPI V010 c h The NTSC VGA GFX driver or all of them And any other ancillary drivers for sound keyboard etc All the required files can of course be found in the Source directory on the DVD which you should have already copied onto your hard drive located here DVD ROM CHAM AVR SOURCE AVRStudio TIP The Arduino version will be in Sketch form already so all you need to do is load the Sketch in and upload and you re in business 28 1 1 NTSC Printing Demo This demo simply uses the NTSC terminal API to print Hello World to the NTSC screen Figure 28 1 shows the demo in action Figure 28 1 NTSC terminal printing demo mf 6579 0 7 L d 43 Ld 6 43 0 C a9 0 55 amp 7z0 I
261. em fall off faster and so forth Here s a cool tool on the web to get a feel for filters Low Pass http www st andrews ac uk www_pa Scots_Guide experiment lowpass Ipf html High Pass http www st andrews ac uk www_pa Scots_Guide experiment highpass hpf html In any event playing with the math the 3dB point for our circuit is 1 2 PI RC Notice f is not there since we solved for it Therefore we have everything we need to use the circuit and the equation Let R and C in our circuit be 1K Ohm and 0 1uF respectively plugging them in we get 1 2 PI 1K 0 1uF 1 59 KHz Which might be a little low to loosen this up let s make the resistor smaller 200 Ohm 1 2 PI 200 0 1uF 7 95 KHz Which is a rather high frequency about 50 the max range of most human ears which top out at 15 20KHz Figure 14 2 Sine wave riding on a constant DC offset as its passed thru a coupling capacitor 6 Audio signal before coupling capacitor 2 0V offset Audio signal after no offset Why is this important Well first off if you send a signal thru our little low pass filter to the output connected to the audio port on the TV then the signal is going to attenuate at high frequencies We will get back to this momentarily let s move on to the second stage in the audio circuit which is based on C15 This stage of the circuit is a AC pass filter that means that it will only pass AC and the
262. emote mode F4 Enable Data Reporting The mouse responds with acknowledge FA then enables Data Reporting mode and resets its movement counters This command may be issued while the mouse is in Remote mode or Stream mode but it will only effect data reporting in Stream mode F3 Set Sample Rate The mouse responds with acknowledge FA then reads one more byte from the host which represents the sample rate in unsigned 8 bit magnitude format The mouse saves this byte as the new sample rate After receiving the sample rate the mouse again responds with acknowledge FA and resets its movement counters Most mice accept sample rates of 10 20 40 60 80 100 and 200 samples sec 61 F2 FO EE EC EB EA E9 E8 E7 E6 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Get Device ID The mouse responds with acknowledge FA followed by its device ID 00 for the standard PS 2 mouse The mouse also resets its movement counters in most cases Set Remote Mode The mouse responds with acknowledge FA then resets its movement counters and enters Remote mode Set Wrap Mode The mouse responds with acknowledge FA then resets its movement counters and enters Wrap mode Reset Wrap Mode The mouse responds with acknowledge FA then resets its movement counters and enters the mode it was in prior to Wrap mode Stream Mode or Remote Mode Read Data The mouse respon
263. er tool so all we have to do now is run the tool which is very simple The first step is to make sure that the PC recognizes the Chameleon and installs a virtual USB COM port When you connected your test Chameleon AVR to the PC via the USB cable and powered the Chameleon up the FTDI drivers on the PC should have detected a NEW USB port and assigned a COM port to it you can find the COM port in the system devices menu You will need this later for the serial communications test however the Propeller took will autoscan all COM ports until it finds the Propeller chip connected to one With that in mind here are the steps to load the firmware into the Propeller chip you will do this for every Chameleon AVR and PIC in the final testing process Step 1 Launch the Propeller IDE tool by clicking the shortcut on the desktop Step 2 Navigate to where you copied the source directory files on your PC and open the master file cham_default2_drv_112 spin latest copy It is located on the DVD ROM here DVD ROM CHAM_AVR SOURCE PROPELLER_DRIVER This is shown in Figure 15 66 ignore my slightly different hard drive paths Figure 15 66 Loading the Propeller firmware into the tool Propeller Tool cham default2 111 cham default2 drv 111 Text 010 VGA 010 keyboard 010 cham defaul2 drv 111 Full Source Condensed Documentation AU 4 7
264. ere are a couple good references online http en wikipedia org wiki XMODEM http www techheap com communication modems xmodem html So what we did was take the protocol and make a simple downloader receive function that initiates an X Modem transfer download over the serial port The function assumes that the uploader is already running and waiting for the downloader the Chameleon to initiate the transfer This is a very important part of X Modem transfer protocol the uploader is started and it simply waits for the downloader to start requesting packets There is actually a timeout that it will give up in the minutes but usually the idea is you start the uploader and leave it THEN go run the downloader and it controls the flow of information or the rate of data reception Additionally the downloader checks each block of information against a sent checksum all of these is covered in the links above But briefly here s the packet format or block as they like to call it 239 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit ASCII Control Codes lt soh gt 01H lt eot gt 04H lt ack gt 06H lt nak gt 15H lt can gt 18H Each block of the transfer looks like lt SOH gt lt blk gt lt 255 blk gt lt 128 data bytes gt lt cksum gt in which lt SOH gt 01 hex blk gt binary number starts at 01 increments by 1 and wraps OFFH to OOH not to 01 255 blk gt blk after goi
265. erring to the table the highest safe value to use for brightness luma is 6 and the lowest safe value is 3 so keep your luma in the range of 3 6 when using chroma otherwise the system won t have enough freedom to encode the color signal modulation since a 1 modulates your luma signal and you don t want it going out of range The color format is not something made up but a direct result of the underlying Propeller video hardware s color format that it needs to process pixels so we are stuck with it However other than the out of range luma values and the color modulation bit its a fairly common way to encode color on 8 16 bit graphics hardware They rarely use RGB Tile Map Review That about sums up the tile engine design The physical tile map on the screen always displays 32x24 characters You can define larger virtual tile maps for scrolling that are 32 64 128 256 wide any height Each tile is 2 bytes representing the tile index character and the palette to use for the tile 4 colors Each tile bitmap is 8x8 pixels each pixel 2 bits Each 2 bit code refers to 1 of 4 colors in the palette for that tile The tile engine supports course scrolling by changing the pointer to the start of the current tile map or page flipping by moving the pointer an entire tile map length The engine also supports smooth scrolling in the vertical direction with the vertical scroll register 0 7 The tile maps tile bitmaps and palettes are all
266. es lt stdlib h gt General utilities lt string h gt Strings pte ome e e a AVR Specific Library Functions UE ei ey lt avr boot h gt Boot loader Support Utilities lt avr eeprom h gt EEPROM handling lt avr interrupt h gt Interrupts lt avr io h gt AVR device specific IO definitions lt avr sfr_defs h gt Special function registers lt avr sleep h gt Power Management and Sleep Modes avr wdt h Watchdog timer handling AVR Specific Utility Functions Ss d e we AN JJ f lt util atomic h gt Atomically and Non Atomically Executed Code Blocks lt util crc16 h gt CRC Computations lt util delay h gt Convenience functions for busy wait delay loops lt util delay_basic h gt Basic busy wait delay loops lt util parity h gt Parity bit generation lt util setoaud h gt Helper macros for baud rate calculations lt util twi h gt TWI bit mask definitions lt compat deprecated h gt Deprecated items lt compat ina90 h gt Compatibility with IAR EWB 3 x 140 lt avr lock h gt Lockbit Support lt avr pgmspace h gt Program Space Utilities lt avr power h gt Power Reduction Management lt avr fuse h gt Fuse Support lt avr version h gt avr libc version macros 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit As you can see the first set of headers looks pretty familiar but the second and third set are totally AVR specific but not hardware speci
267. escription VGA Color sets the color of the text and background depending on driver The col parameter should be from 0 7 and selects one of a number of different foreground background color schemes for the characters printed Returns 1 Example s Print the character X in all colors int for index 0 index lt 8 index VGA_Color index Term Char X end for index 174 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 22 0 GFX Library Module Primer The basic premise of the Chameleon design is that it leverages drivers running on the Propeller chip to do all the media and graphics Thus whatever features the particular driver running on the Propeller side is the only features we can access via the AVR side That doesn t mean we can t abstract functionality and add higher level functions that build on the sub functions however this probably isn t productive since you will want to change drivers re write the Propeller driver and so forth Thus for the majority of the media drivers all the API functions do including the GFX is expose some of the base functionality in nice function calls so you don t have to send SPI messages yourself In the case of the NTSC driver CHAM DEFAULT2 DRV 112 SPIN we are using the following Propeller Object for the NTSC tile engine and text display CHAM GFX DRV 001 TB O01 spin This is the enhanced
268. eset the Propeller Reset PropO wait a moment _delay_ms 1000 now reset the AVR Reset Master 18 0 UART and RS 232 Library Module Primer The UART and RS 232 communications module supports basic transmission and reception of bytes to and from the Chameleon AVR serial port The AVR 328P P Pico power version that we are using has a single very advanced USART Universal Synchronous and Asynchronous Serial Receiver and Transmitters It is connected directly to the TX RX pins of the USB FTDI chip which allows serial communication via the USB port Additionally the TX RX lines are exported on the I O headers Before discuss the overall architecture of the UART library module here are the main features of the AVR 328P USART Full Duplex Operation Independent Serial Receive and Transmit Registers Asynchronous or Synchronous Operation Master or Slave Clocked Synchronous Operation High Resolution Baud Rate Generator Supports Serial Frames with 5 6 7 8 or 9 Data Bits and 1 or 2 Stop Bits Odd or Even Parity Generation and Parity Check Supported by Hardware Data Overrun Detection Framing Error Detection Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter Three Separate Interrupts on TX Complete TX Data Register Empty and RX Complete Multi processor Communication Mode Double Speed Asynchronous Communication Mode As you can see they are pretty powerful and the librar
269. etch form already so all you need to do is load the Sketch in and upload and you re in business 230 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 31 1 1 Propeller Local Port LED Blinker Demo The Propeller chip on the Chameleon had 8 free I O pins so we decided to add an 8 bit port to it With this you can interface SD cards SPI memory control servos whatever Of course the AVR itself has all its headers But give the Propeller a direct port itself allows drivers running on the Propeller to do more stuff Anyway that s what the Propeller 8 bit port is all about And this simple demo shows how to set the I O pin directions and blink and LED All we need is the Propeller Port API library and an LED to plug into the Propeller port which we happen to supply with your Chameleon Now you might have a red green blue or bi color LED Doesn t matter which just plug it into the 2 left most pin headers of the Propeller Port as shown in Figure 31 1 below If you are into electronics you might be concerned that we are plugging the LED directly into two I O ports and it might burn the LED out This is a valid concern but luckily the forward voltage of the LED is about 2 2 2 5V so the 3 3V outputs of the Propeller are just enough to turn it on and the LED will draw a limited amount of current Moreover the Propeller I O ports can actually source or sink 40ma so you can even drive little light bulbs Your
270. ets the prop i HUP TT PM HL EDEL ERE this range of commands for future expansion HT TETTE TH TEL TTE TM M M M BG GL DTT advanced GFX commands for GFX tile engine GPU_GFX_BASE_ID 192 starting id for GFX commands to keep them away from normal command set GPU GFX NUM COMMANDS 97 number of GFX commands Reads the status of the GPU Writes the GPU Sub Function register and issues a high level command like copy fill etc Writes status of the GPU Writes the GPU Sub Function register and issues a high level command like copy fill etc GPU_GFX_SUBFUNC_STATUS_R 0 GPU_GFX_BASE_ID GPU_GFX_SUBFUNC_STATUS_W 1 GPU_GFX_BASE_ID have highlighted the two new message id s That s all there is to it The selection of 100 101 are a bit random could have used 65 66 or could have used a single id and then used one of the data bytes to control on off But thought this would be a little more illustrative Now that we have the message ids we need to process the messages and do something A bit of investigation of the schematic and the boot code shows that I O P25 is connected to the status LED In fact the boot code that blinks the LED 3 times during boot looks like this blink the status LED 3 times to show board is alive DIRA 25 1 set to output OUTA 25 0 repeat 6 OUTA 25 OUTA 25 repeat 25000 Therefore this code already sets up the I O direction of the port bit
271. evelopment is still on Windows machines and will likely stay there for a time to come However that said there are 3 party tools that run on Mac and Linux for the AVR processor Companies such as IAR Green Hills and others have complete tool chains that run on Mac and Linux That said the funny thing is that the AVR compiler used by AVRStudio is a Linux based GNU GCC compiler But Atmel hasn t had a reason to port it to Mac and Linux However you can develop 100 on a Mac or Linux machine and then use programs like AVRDude to download to the AVR using ISP But the Arduino tool does all this for you thus for Mac and Linux enthusiasts suggest simply using the Chameleon in Arduino mode installing the Mac Linux version of the tool on your PC and then copying the Chameleon Libraries and Sketches just as you did would have for the Windows version On the DVD in this location DVD ROM CHAM AVR TOOLS ARDUINO Are all the files you need to get started there is a directory for the Library files that you need to add to the Mac Linux installation of the Arduino tool as well as the Sketches for all the demos Additionally have downloaded the Linux and Mac versions of the Arduino tool and put them in the respective directories Mac and Linux to save you downloading time The cool thing about using the Arduino tool is that the exact same Chameleon software for Arduino mode works on all three operating systems without change You simple inst
272. excerpt of the program 226 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit int main run over and over again int Key key that keyboard returns char sbuffer 64 printing buffer initialize and set SPI rate SPI Init SPI DEFAULT RATE give Propeller driver time to boot delay ms 2500 clear screens NTSC Clearscreen VGA_ClearScreen set NTSC color NTSC Color 0 NTSC Term Print PS 2 Keyboard Demo NTSC Term Char OxOD NTSC Term Print Press keys on local keyboard NTSC Term Char OxOD set VGA color VGA Term Print Press keys on local keyboard Term Char OxOD load keyboard driver this driver is already loaded by default but this call can t hurt Keyboard Load O enter infinite loop 1 1 1 read next key return 0 null if key wait for key press while key _ 0 build display string if key gt 32 sprintf sbuffer Key Code Xd c Cint key Cchar key else sprintf sbuffer Key Code d non printable Cint key position cursor NTSC SetxY 1 4 print on NTSC terminal screen NTSC Term Print sbuffer NTSC Term Char OxOD position cursor VGA SetXY 1 4 print on VGA terminal screen Term Print sbuffer Term Char OxOD slow things down a bit so we can read the text delay ms
273. extensions we just need to read the X Y position along with the state of the buttons The standard PS 2 mouse has two internal 9 bit 2 s complement counters with an overflow bit each that keep track of movement in the X and Y axis The X and Y counters along with the state of the three mouse buttons are sent to the host in the form of a 3 byte data packet The movement counters represent the amount of movement that has occurred since the last movement data packet was sent to the host therefore they are relative positions not absolute Each time the mouse reads its inputs controlled internally by the microcontroller in the mouse it updates the state of the buttons and the delta s in the X Y counters If there is an overflow that is if the motion from the last update is so large it cant fit in the 9 bits of either counter then the overflow flag for that axis is set to let the host know there is a problem The parameter that determines the amount by which the movement counters are incremented decremented is the resolution The default resolution is 4 counts mm and the host may change that value using the Set Resolution E8 command Additionally the mouse hardware can do a scaling operation to the sent data itself to save the host the work The scaling parameter controls this By default the mouse uses 1 1 scaling which means that the reported motion is the same as the actual motion However the host may select 2 1 scaling by sending the Set
274. f course The output of the demo displays on both the NTSC and VGA monitors The examples typically consist of the primary source file for the demo as well as The System API library module CHAM AVR SYSTEM VO010 c h The main SPI API library module CHAM AVR TWI SPI V010 c h The Sound driver API library module CHAM AVR SOUND DRV VO10 c h The NTSC VGA GFX driver or all of them And any other ancillary drivers keyboard mouse etc All the required files can of course be found in the Source directory on the DVD which you should have already copied onto your hard drive located here DVD ROM CHAM AVR SOURCE AVRStudio TIP The Arduino version will be in Sketch form already so all you need to do is load the Sketch in and upload and you re in business 222 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 29 1 1 Sound Demo This demo uses the Sound API and driver to play some chords up and down The chord frequencies are displayed on both the NTSC and VGA displays Figure 29 1 shows the demo in action Figure 29 1 Sound demo VGA output Playing Playing Playing Playing Playing Playing Playing Playing Playing Playing Playing Playing Playing Playing Compiling and Running the AVRStudio Version Demo Version Description Plays sounds on the speaker Main Source File CHAM AVR SOUND DEMO 01 Additional Files Required CHAM AVR SYSTEM V010 c h CHAM AVR TWI SPI DR
275. fault 0x00000000 Oxffffffff Linker script and memory map Address of section data set to 0x800100 LOAD d development xgs2 avr winavr bin lib gcc avr 4 3 2 avr lib avr5 crtm328p o LOAD CHAM AVR V010 0 LOAD CHAM AVR FLASH 10 0 LOAD CHAM AVR GFX DRV V010 0 LOAD CHAM AVR KEYBOARD DRV V010 0 LOAD CHAM AVR MOUSE DRV 10 0 LOAD CHAM AVR NTSC DRV V010 0 LOAD CHAM AVR PROP PORT DRV 10 0 LOAD CHAM AVR SOUND DRV V010 0o LOAD CHAM AVR SYSTEM 10 0 LOAD CHAM AVR TEST LOAD CHAM AVR SPI V010 0o LOAD CHAM AVR UART DRV 10 0 LOAD d development xgs2 avr winavr bin lib gcc avr 4 3 2 avr lib avr5Nlibm a LOAD d development xgs2 avr winavr bin lib gcc avr 4 3 2 avr5Nlibgcc a LOAD d development xgs2 avr winavr bin lib gcc avr 4 3 2 avr lib avr5Nlibc a LOAD d development xgs2 avr winavr bin lib gcc avr 4 3 2 avr5Nlibgcc a List File Example Iss List files are my favorite since you can change settings on the compiler and then see how the code generation changes Additionally you can see just how bad or good a compiler is at compiling simple statements In many cases you will be shocked at what the compiler s code generate outputs for something as simple as x Below is a small sample of a LSS file specially the code generated by one of the graphics functions in the
276. ffer for pixel 0 pixel 640 pixel Write VGA video buffer pixel 0 039721946 Of course you would need some might fast hardware to delay at a resolution of 39 ns but you get the idea This is a model of the algorithm for a line of video this coupled with the model for the horizontal timing vertical timing and put it all together as a state machine and you have a VGA generator The VGA drivers on the Propeller are more complex than this of course but that s the idea 43 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit To begin with there are many online and written sources for NTSC the primary online resource is located here http www ntsc tv com At the end of the discussion on NTSC there is a list of other resources as well Figure 11 1 The Chameleon AVR composite video hardware NTSC Video Summer R15 AURAL 0 gt ANT1 Antenna Port VIDEO_2 gt VIDEO_1 D vIDEO gt Referring to Figure 11 1 the composite video generation hardware consists nothing more than a crude 3 bit D A converter summing circuit along with a single signal for audio summed with the node as well The real magic of the video generation is up to the Propeller chip it not only generates the luma brightness but the chroma color in the proper format and timing for whatever the desired protocol is NTSC or PAL The Propeller chip video hardware is designed to be interfaced to a simple 3 bit D
277. fic to the Chameleon AVR only to the AVR 328p processor Now the hardware specific functionality for the Chameleon AVR we had to develop Referring to Figure 17 1 there are a number of library classes you can glean from the figure they are System Graphics Sound The system library module is a glue module that ties the other modules together and is used as a common place to put functions and constants that don t fit into any other category Currently the system library module is very small but it will grow in the future This library simply makes calls to the graphics drivers running on the Propeller chip So whatever they do this library tries to expose to the user The current drivers are tile graphics only and support text printing scrolling and crude control of color The default2 driver series adds some functionality with a gaming tile engine that supports fine vertical scrolling control of overscan colors large playfield tilemaps re definable character bitmaps 4 colors per tile and many other cool features This library interfaces to the Propeller sound driver object and exposes limited capabilities of the driver itself which can do a lot more The API gives you a few functions to play sounds control volume etc But you will probably want to enhance this API Keyboard Mouse There is a PS 2 port on the Chameleon which is connected to the Propeller The default UART SPI FLASH dr
278. from master MOSI SIMO Master Output Slave Input output from master MISO SOMI Master Input Slave Output output from slave SS Slave Select active low output from master Note You might find some devices with slightly different naming conventions but the idea is there is data out and data in a clock and some kind of chip select If you refer back to the Chameleon s SPI interface discussion in Section 9 0 of the Hardware Primer you can see that these signal pins are mapped from the AVR to the Propeller chip SPI is very fast since not only is it clocked but it s a simultaneous full duplex protocol which means that at you clock data out of the master into the slave data is clocked from the slave into the master This is facilitated by a transmit and receive bit buffer that constantly re circulates as shown in Figure 19 1 Figure 19 1 Circular SPI buffers Master Slave Lo 1 2 3 4 5 6 7 12 3 4 5 6 7 The use of the circular buffers means that you can send and receive byte in only 8 clocks rather than clocking out 8 bits to send then clocking in 8 bits to receive Of course in some cases the data clocked out or in is dummy data meaning when you write data and you are not expecting a result the data you clock in is garbage and you can throw it away Likewise when you do a SPI read typically you would put a 00 or FF in the transmit buffer as dummy data since something has to be sent
279. functions global that holds UART current baud rate extern int g_baudrate receiver and transmitter head and tail indices for circular buffers extern int g_uart_rx_head extern int g_uart_rx_tail extern int g_uart_tx_head extern int g_uart_tx_tail buffers for uart interrupt driver extern UCHAR g_uart_buffer_rx UART_RX_BUFF_SIZE receiver buffer for incoming characters extern UCHAR g_uart_buffer_tx UART_RX_BUFF_SIZE transmit buffer for outgoing characters First we have a global baud rate pointers to the circular buffers and finally the buffers themselves These are all declared in the C file of course these are simply the external references The API listing for the UART and RS 232 module CHAM_UART_DRV_V010 c is listed in Table 18 2 categorized by functionality Table 18 2 UART and RS 232 module API functions listing Function Name Description moe NU Initialization Pe lc int UART_Init unsigned int baudrate Initializes UART ISRs etc ae ee int UART putc unsigned char ch Transmits a character using interrupt buffer void UART Transmit unsigned char ch Transmits a single character immediately void UART Newline void Sends an ASCII newline CR LF void UART Print String char string Prints a NULL terminated string void UART Print Int int num Prints a signed integer void Terminal Clear Scree
280. g BM Ml gb gl lg Mllll M ld TT define __AVR_ATmega328P__ include everything include lt stdint h gt include lt stdio h gt include lt stdlib h gt include lt string h gt include lt ctype h gt include lt avr eeprom h gt include lt avr io h gt include lt avr sleep h gt include lt util delay h gt include lt avr interrupt h gt include lt avr pgmspace h gt include inttypes h include compat twi h gt include lt avr wdt h gt include headers required for demo notice the use of lt gt brackets for the ardunio version since it searches for headers differently than AvRStudio include gt you need this one always include you need this always include needed for NTSC driver include gt needed for VGA driver DEFINES AND MACROS TEE EE define CPU frequency in MHz here if not defined in Makefile or other includes 207 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit compiler will throw a warning ignore ifndef CPU CPU 16000000UL 2863636001 14318180UL 21477270 UL endi MAIN ITT TITTLE LTTE TTT TTT TET EE LL LES TLE EEE TELE MM P MB Mg M M M PPP PPP P P PP P Pg PM PPP PP P PP P PP P P P Pg P P M PP PP G
281. gs but broken out so you don t have to decode them yourself from the datasheet Also note that the and SPI defines declare very specific hardware and The interface for example uses the TWI hardware on Port C at bits 1 0 for the interface These are exported via the expansion port Similarly the SPI interface is the primary SPI interface in the AVR 328P not the USARTs in SPI mode Moving on the SPI channel connects to the SPI Mux as well as the Propeller chip and is exported to the I O headers So if you want to control an external SPI device you can use the other SPI Mux addresses the Propeller and FLASH use address 0 and 1 Next there are some timing constants that slow things down and make sure when SPI commands are sent to the Propeller the AVR waits long enough before issuing another command These don t matter too much as the drivers evolved but were needed in earlier driver development TIMING CONSTANTS FOR SPI COMMS PLAY WITH THESE IF THINGS GET FUNKY MI PPP PL P PP PP P P P PP P P P LTT PPP what rate to run the SPI at this effects the following constants faster rates longer delays define SPI_DEFAULT_RATE SPI_FOSC_32 SPI_FOSC_32 for optimization settings 01 02 03 05 SPI FOSC 16 for no optimizations 00 these defines throttle the SPI interaction with the virtual SPI software interface on the Prop which is slow define SPI PROP SLOW FACTOR 4 this number s
282. hameleon AVR 8 Bit The next step in the installation is the selection of the installation file directory Browse and select the same root directory you previously installed AVR Studio into By doing this everything will be conveniently located in a single directory Figure 15 15 illustrates this Figure 15 14 Selection of WinAVR s installation directory should be the same as AVR Studio WinAVR 20080610 Setup Hog Choose Install Location Choose the folder in which to install WinAVR 20080610 Setup will install WinAVR 20080610 in the Following Folder To install in a different Folder click Browse and select another Folder Click Next to continue Destination Folder F development avr E Browse Space required 127 0MB Space available 103 6GB Once you are satisfied with the installation directory location click Next for the installation components dialog as shown in Figure 15 15 below Figure 15 15 WinAVR software components selection dialog amp WinAVR 20080610 Setup o Choose Components Choose which Features of WinAVR 20080610 you want to install Check the components you want to install and uncheck the components you don t want to install Click Install to start the installation Select components to install Add Directories to PATH Recommended Install Programmers Notepad Space required 127 0MB The WinAVR components selec
283. haracter if ae UART_getc 1 special characters switch c case 0 00 carriage return case 0 line feed cmd_buff cmd_buff_index any command to process if buff index gt 0 process command upcase the string to normalize tokens strupr cmd buff copy cmd buffer to token buffer for processing memcpy token buff cmd buff strlen cmd buff 1 initialize command processor num tokens 0 initialize token processor token ptr strtok r token buff amp result ptr token ptr insert token into token array and inc number of tokens found tokens num_tokens token ptr token ptr strtok r NULL amp result ptr end while string has been entered and tokenized now return number of tokens return num tokens end if empty string return 1 break case 0x08 back space if uq gt 0 UART putc cmd buff index end if break default otherwise normal character insert into command string and echo 1 UART putc cmd buff buff index break Eo end ith end end while end Get string 237 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit This function is a bit overkill since its designed to parse the string into tokens that you might need later but it s a good starting point for you if you want to bre
284. has effect when Scan Code Set 3 is in use Resend should be sent when a transmission error is detected from the keyboard Reset Keyboard sends ACK and waits for system to receive it then begins a program reset and Basic Assurance Test BAT Keyboard returns a one byte completion code then sets default Scan Code Set 2 The mouse protocol is exactly the same as the keyboard protocol as far as sending and receiving bytes with the 11 bit packet The only difference of course is the data format the mouse sends to the host and the commands the host Propeller chip can send the mouse Again we will cover real programming examples in the Programming Manual but let s just review the technical details briefly to get acquainted with the commands and data 58 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 12 2 1 Basic Mouse Operation The standard PS 2 mouse interface supports the following inputs X right left movement Y up down movement Left Middle and Right buttons The mouse has an internal microcontroller that translates the motion of either a mechanical ball or optical tracking system The inputs along with the buttons are scanned at a regular frequency and updated are made to the internal state of the mouse via various counters and flags that reflect the movement and button states Obviously there are mice these days with a lot more than 3 buttons and 2 axes but we are not going to concern ourselves with these
285. he Propeller chip itself QFP package the 64K serial EEPROM for program storage a single LED and the Propeller Port I O header at J8 Additionally the Propeller is clocked by a 5 MHz nominal XTAL at X1 The only thing interesting about the design is the free Propeller Local Port at J8 it connects to Propeller I O pins PO P7 Thus you can connect other devices to this header or potentially drive another NTSC PAL VGA video device or you can just use it at 8 more digital I O ports Lastly the Propeller chip only needs a 32K EEPROM to load its runtime image into its local SRAM however we are using a 64K EEPROM which not only allows 2 images but potentially a single image with additional program assets like graphics sound or code 8 1 The Propeller Local 8 Bit I O Port The Propeller Local Port is an 8 bit port consisting of 8 free digital I O pins from PO P7 on the Propeller chip You can do anything you want with the port You can even power devices from the port by using some of the pins as power and virtual ground The Propeller can source up to 40mA per pin so if you tie 2 lines together and set them HIGH you can source up to 80mA more than enough for most applications 35 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 9 0 The SPI Bus and Communications System Figure 9 1 The SPI multiplexer design 5V VCC AN2 T SPI_SSOn SPI SS3n T lt AN3 lt gt SPI_SS1n SPLMISO T
286. he chip in a number of areas Thus we must set these fuses every time we program the processor so that they are correct Referring to Figure 15 38 you can see there are a lot of fuse settings and a lot of cryptic labels on the left hand side First simply mimic what you see in the figure and set your fuses to exactly these values Be specially cognizant of the settings for 102 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit BODLEVEL Brown out control disabled JTAGEN JTAG Enable SPIEN SPI Enable BOOTSZ Boot FLASH size size 1024 address 3C00 SUT_CKSEL Clock Select 8Mhz Start up time 16CK 14CK Oms However all of the fuse settings need to be exactly as depicted in the figure Additionally make sure the three checkboxes at the bottom of the window are all checked Auto read Smart warning and Verify after programming When your fuse settings are all exactly as shown in the figure above then the bottommost window will show you the actual binary encoding which should be Fuse Bank Name Value EXTENDED OxFF HIGH OxDA LOW OxDF If you weren t using this tool and using another tool that needed the actual binary bit values for the extended high and low fuse bits then you could use these values Once you have all the fuse bits and drop downs set to mimic the settings in Figure 15 38 you could click the Program button to write the fuses if you wish This will not program
287. he name of the AVRStudio version is CHAM AVR STATUS LED DEMO 01 and is located on the DVD here 253 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit DVD ROM CHAM_AVR SOURCE CHAM AVR STATUS LED DEMO 01 There is also the Arduino version sketch which is located on the DVD here DVD ROM CHAM AVR TOOLS ARDUINO SKETCHES CHAM AVR STATUS LED DEMO Which you should have copied all these files to your hard drive already Compiling and building these programs should be old hat to you now so won t waste time with that Let s just look at the code Referring back to the source listing above there are 2 things that make this program really First the addition of the message ids show here new commands for status LED control define STATUS LED ON 100 define STATUS LED OFF 101 And secondly the actual messages to the Propeller to turn the LED on and off the on message for example send command to turn on LED SPI Prop Send Cmd STATUS LED ON 0 0 And that s it It just works If you compile and run this program you will see the status LED blink on and off as well as the NTSC monitor display messages As you can see its very simple to add new functionality to the driver and if you are careful and make sure not to re use message ids then you can deploy your new driver for other Chameleon users both AVR and PIC and they can use the driver without change in their Chameleon
288. hem pretty Use them if you wish However once you have a really nice Propeller driver written you will definitely want to create more advanced API layers on the AVR side so you can write high level code But in this case most of the functions are 1 1 168 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit with the equivalent SPI_Prop_Send_Cmd code However in some cases the API functions are nice if you want to do a set of operations with a single function call and that s what APIs are all about The NTSC API module header CHAM DRV VO010 h has no globals or defines as of yet nothing more than the function prototypes The API listing for the NTSC module CHAM NTSC DRV 010 is listed in Table 20 1 categorized by functionality Table 20 1 NTSC module API functions listing Function Name Description int NTSC_ClearScreen void Clears the NTSC screen Positioning Se int NTSC GetXY int x int Gets the current cursor position on the terminal int NTSC SetXY int x int Sets the current position on the terminal C D Sa Printing a E int NTSC_Term_Char char ch Prints a single character to the terminal at the current cursor position int NTSC_Term_Print char string Prints a NULL terminated string to the terminal int NTSC Color int col Sets the color of the te
289. her character set If you move the pointer only one bitmap in length then it would have the effect of shifting all the character so A would be B etc not very useful Palette Entry and Color Format The palette entries are very simple Each tile in the tile map character is actually 2 bytes as discussed above The low byte is the character which is a direct index into the character bitmaps and the 2 byte is the color attribute which is an index into the palettes Thus a palette entry of 0 means use palette 0 a 1 means use palette 1 and so forth Each palette consists of 4 colors Each color encoded as a single byte which will discuss the encoding in a moment Currently the driver has 16 palettes allocated nothing special just made up colors black white blue basic colors kind of thing You will want to define your own palettes and your own colors as you define your bitmaps art and level designs for your games Below is a peek at the palette definition in the driver palettes extracted from file c64 font 04 8b bmp using palette color map 1 178 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit only palette index 0 1 are used right now for character font palette index 0 makes characters normal palette index 1 makes them look inverse video _tile_palette_map LONG C64 font 04 palette map LONG LONG 507 07 0c 02 palette index LONG 507 0c 07 02 palette index LONG 07 Oc 07 02 LONG
290. his Returns 1 Example s Scroll down a line Assumes 32x24 tile map important thing is the row pitch this defines how many bytes per row GFX Write Tilemap Ptr GFX Read Tilemap Ptr 32 2 Function Prototype unsigned int GFX Read Bitmap Ptr void Description GFX Read Bitmap Ptr reads the 16 bit bitmap pointer that points to the first bitmap indexed by tile 0 Each bitmap is 8x8 pixels 2 bits per pixel 16 bytes each The bitmap pointer is of course relative to the Propeller s 32K memory space and an absolute address Returns the 16 bit pointer value address Example s Read the current bitmap pointer unsigned int bitmap ptr bitmap ptr GFX Read Bitmap Ptr 188 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Function Prototype unsigned int GFX_Write_Bitmap_Ptr unsigned int bitmap ptr Description GFX Write Bitmap writes the 16 bit bitmap pointer bitmap ptr that points to the first bitmap indexed by tile 0 Each bitmap is 8x8 pixels 2 bits per pixel 16 bytes each The pointer must be a valid address and within open memory or part of memory declared for the driver itself otherwise you could crash the Propeller so watch out Typically you will adjust the bitmap pointer by one or more bitmaps to create animation effects of the tiles on screen or to swap out character sets on the fly Returns 1 Example s Adjust the bitmap pointe
291. hown in Figure 27 2 209 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 27 2 The Libraries directory which contains both the default Arduino libraries as well as our custom libraries amp libraries SEE File Edit View Favorites Tools Help ay 2 Search Folders E Address 2 D development chameleon cham_avr source arduino arduino 0017 h Go msn v i 2 CHAM AVR 5 DRV V010 Ethernet _ _ _ _ _ 010 Firmata CHAM_AVR_SOUND_DRY V010 Liquidcrystal CHAM_AYR_SYSTEM_V010 matrix C CHAM AVR TWI SPI V010 Ey hardware servo C3CHAM AVR UART DRV V010 My Documents _ 2 SoftwareSerial AVR V010 Shared Documents sprite 4 My Computer E My Network Places _ CJ CHAM AVR FLASH DRY VO10 C CHAM AVR GFX DRV VO10 C CHAM AVR KEYBOARD DRV VO10 C CHAM AVR MOUSE DRY 010 Other Places Details libraries bytes E My Computer If you haven t copied the new libraries into this directory then you should do so now They are located on the DVD ROM in the following location DVD ROM CHAM AVR TOOLS ARDUINO LIBRARIES Assuming you have the libraries directory setup with all the new Chameleon specific libraries for NTSC VGA sound FLASH serial keyboard mouse etc The next thing we need to d
292. ier by modulating the period or the duty cycle of the fixed frequency PWM carrier This is a VERY important concept to understand the PWM frequency period NEVER changes only the duty cycle of any particular cycle Thus by modulating the information onto the duty cycle we can then later demodulate the signal by integrating or averaging the PWM signal with a RC circuit and presto we have an analog voltage Figure 14 6 Indexing into a Sine look up table to synthesize a signal at a given PWM rate Sine Table 0 360 maps to 0 255 gt 8 bit entries 0 128 50 PWM Engine 90 255 100 25 15 0 90 Ground Reference at 50 Duty Cycle Vmax 1 0V Positive 315 37 0 5 359 127 Output voltage can t swing negative thus the ground refrence must be at 50 of the total signal strength or Vmax so the signal has room to swing around the ground The first thing we need to do is decide what kind of waveforms we want to synthesis remember they can be ANYTHING they can be periodic and simple like sine square wave redundant triangle sawtooth noise or even digitized speech But to start simple let s synthesis a single sine wave So first we need a look up table for sine wave let s call it sinetable and assume it has 256 entries and we generate it such that a single cycle has a low of 0 and a high of 255 and is encoded in 8 bits similar to an example in the references
293. ies of tones that play musical notes when you hit RESET Make sure to have the audio port plugged into your NTSC TV as well These will all be part of the final tests for each Chameleon Figure 15 69 The LED will blink whenever you reset the Chameleon once you have loaded the Propeller driver firmware T 2279 SONNET Propeller 21 ip Diiver Firmwas loaded this LED Will blink 3 tig after eeh RESET Propeller Of course all we really did was re download the SAME firmware back into the Propeller chip so whatever is loaded into the AVR at this point will ultimately direct the Propeller slave what to do But this is the process to load the Propeller chip with a program Additionally you just saw how to load the default driver that this manual uses 99 of the time which is loaded on the Chameleons when they ship But you can surely change this driver if you wish update it make it faster better change objects it relies on etc You will learn how to do this later in the manual update the Propeller driver but for now we aren t going to touch it other than knowing where it is and how to download it This is the idea of the Chameleon the Propeller chip is like a black box when things go right we shouldn t even know its there the Propeller should work like another other media processing chip and just execute the command we send it 127 2009 NURVE NETWORKS LLC Explo
294. if you just want to send out serial data to and from the Chameleon you are going to need a good terminal program we suggest PuTTY Chameleon AVR 8 bit Mini USB cable PC Running Terminal Program eg PuTTY Arduino Tool Propeller Tool The PC can talk to either the Propeller chip onboard the Chameleon via the USB port OR the standard serial port on the AVR chip this is accomplished via a mechanical switch at the bottom of the board shown in Figure 15 49 below Figure 15 49 The Serial port routing switch In the UP position it selects USB communication with the Propeller chip In the DOWN position it selects communication with the AVR chip em es Propeller bas Dite n s e it Power ON left Power On left At this point go ahead and make sure the serial select switch is in the DOWN position so the PC can talk to the AVR thru the USB serial port There are many serial terminal programs available Hyperterminal for example but we want you to use one that is very SIMPLE to setup and that works well with the Chameleon AVR we are going to use PUTTY From the DVD ROM install this program DVD ROM CHAM_AVR TOOLS COMMUNICATIONS putty_install exe It is called PuTTY and is very easy to use Once installed it will create a shortcut on your desktop Click the shortcut to
295. ify channel s current frequency and volume Of course the parameters must be in range frequency 0 2000 and volume 0 255 where 0 means to leave as is Returns 1 Example s Start channel 0 at 100 Hz and sweep to 1000 Hz at 10 msec intervals Sound Play 0 100 0 for Cint f 100 f 1000 f Sound Update 0 f 200 delay ms 10 end for 196 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 24 0 Keyboard Library Module Primer The basic premise of the Chameleon design is that it leverages drivers running on the Propeller chip to do all the media and graphics Thus whatever features the particular driver running on the Propeller side is the only features we can access via the AVR side That doesn t mean we can t abstract functionality and add higher level functions that build on the sub functions however this probably isn t productive since you will want to change drivers re write the Propeller driver and so forth Thus for the majority of the media IO drivers all the API functions do including the Keyboard is expose some of the base functionality in nice function calls so you don t have to send SPI messages yourself Now the one thing about keyboards and mice is they are really SLOW thus its typically a problem reading them since your CPU has to slow down to do so therefore its really nice for a core on the Propeller to completely handle the keyboard and
296. ight side of the pane Of course you can also add single objects as well with this sub dialog Next up click the Custom Options tab to the left this should bring up the dialog shown in Figure 15 26 Figure 15 26 The Custom Options tab of the Project Options dialog cham avr work 01 Project Options 4 Custom Compilation Options All files Wall Remove laal Linker Options gdwarf 2 Remove Include std gnu99 Directories 6000000UL m funsigned char 7 funsigned bitfields fpack struct T fshort enums Libraries os Memory Settings External Tools Use Win amp VR D development xas2 avrwinavr bin avr gcc exe make D development xgs2 avr winayr utils bin make exe OK Cancel Help Heb _ _ Custom Options 93 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Referring to Figure 15 26 the Custom Options tab controls the compiler linker settings for all files or specific files In our case we need to make a change to make sure the programs compile correctly On the left pane select All Files on the right you should see a list of options flags that are applied to all source files by the compiler You may recognize them from the General tab In any event this is where you can add delete very specific flags Right now we need to delete something notice the flag named std gnu99 Th
297. ignals are routed to both the Propeller and AVR chips where they are interfaced to the appropriate I O pins Additionally at the top of the schematic you see the signal USB_5VOUT this is the power coming in from the USB port header this is routed to the system as 5V power when there is no external 9V supply plugged in However if you are going to use the Chameleon without a 9V power supply and power it from the USB port highly recommend you use a powered USB hub since the Chameleon will draw up to 200mA or more as it throttles its performance and powers up all its peripherals 33 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 7 0 Atmel AVR 328P Subsystem Figure 7 1 The AVR 328P Subsystem not including SPI mux 5 18 10uF 5VCC C17 0 1 2 PCE PCS PDO PD1 PD2 PD3 PD4 PC3 PC2 PC1 PCO AREF PB6 PB7 PDS PD6 PD PBO PBS PB4 2 PBI C19 0 1 2 VVVVVV ozvy 222232 AAAAAA AAAA AA VVVVVV VVVV VV AAAAA AAAA Rozoex oong so VVVVV VVVV 22222 2222 az gozon PERTE gerge 509i SARAAN NR lt lt lt lt lt lt C23 Ella HH XTAL1 22pF x2 Ld CRYSTAL C24 XTAL2 22pF USB lt gt USB RXDaw T GND Referring to Figure 7 1 you can see the schematic refers to the ATMega 168 in the notation this is because the 168 and 328 are 10096 compatible but the 328P ha
298. igned int dest ptr unsigned int src ptr unsigned int num bytes Description GFX GPU Copy 6 copies a number of bytes from source to destination in the GPU memory space in WORD side chunks or in other words in the Prop s local memory of 32K you can use this to overwrite SPIN code so watch out The parameters are the destination address to copy to dest ptr the source address to copy from src ptr and finally the number of bytes always a multiple of 2 num bytes to copy Typically you will use this function to copy tile maps scroll page flip perform various animations etc Returns 1 Example s Assuming that the current tile map is 32x24 physically and virtually and there are two tile maps one located at 1000 and the other at 2000 copy the later to the former GFX GPU Copy Mem16 0 1000 0x2000 32 24 2 Function Prototype int GFX GPU Fill Mem8 unsigned int dest ptr unsigned int value unsigned int num bytes Description GFX GPU Fill copies a number of bytes from source to destination in the GPU memory space in BYTE side chunks or in other words in the Prop s local memory of 32K you can use this to overwrite SPIN code so watch out The parameters are the destination address of the fill dest ptr the 8 bit data value and finally the number of bytes num bytes Typically you will use this function to clear tile map bitmap memory and other repetitive operations that require the
299. ile associated with it just the main C file Figure 15 30 A screen shot of the test running JI rd BL ELO ur 09 Tt 6000 Yt TY 6 7 2509 250 9 Tr 0500 0500 M E a TI a Tor 1 3 5 D Sos Alt ATO ATO aos 1 5 LI p Ll 90 abo Lr Son aso be on T LI Lor E 1 5 E Lor m wee Lr Soa Tr 1 4 E E I de I On Lr e E AT 090 6 Lar Em La gt d e D gt a e o CINE 5000 Alright once you have all the files added to the source tree it s finally time to build the project Referring to Figure 15 31 select Build Rebuild All gt from the Main Menu This will start the building process which consists of compilation linking and finally hex file generation for the AVR target 96 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 31 Building our project at long last dio D developme ameleon cham_avr source cham_a 0 AM_AVR WORLD 0 File Project Build Edit View Tools Debug Window He
300. ilt in VSU video streaming unit Of course someone still has to write a driver for the VGA to work on the Propeller but that s been done 100x Referring to Figure 10 1 you see that there are 8 signals connected to the VGA port Table 10 1 shows the relationship between I O port bits and signals There are 2 bits for each channel Red Green and Blue as well as a single bit for HSYNC and VSYNC which are TTL level These outputs are connected directly to the HD15 connector via a series of 2 bit D A converters that sum each 2 bit channel pair R1 RO G1 GO and B1 BO and directly interface the sync bits The VGA spec dictates that for each channel 0 intensity is 0 0V and 100 intensity is 1 0V some references use 0 7V Also each channel input to the VGA monitor itself per input has a nominal impedance of 75 Ohms similar to the NTSC input impedance Table 10 1 The Video Hardware Prop Port Bit Chameleon Signal Description P23 VGA RED B1 Bit 0 of RED channel P18 VGA BLUE Bit 1 of BLUE channel 17 VGA HSYNC VGA HSYNC TTL level P16 VGA VSYNC VGA VSYNC TTL level 38 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 10 2 Electrical model of VGA inputs and 2 bit D A channels 3 3V Voc B1 A Bl 1 1 1 BO Virtual Impedence of display device VGA TV CRT 1 560 Ohm 1 RLOAD 1 75 Ohm 1 5 0 V Vcc 1 1 1 BO 0 1 2700hm
301. ime we get 39 72194638 ns This is how long a pixel takes anyway dividing this into our Hsync time we get Number of dot clocks for Hsync pulse 3 77 us 39 72194638 ns 94 90 clocks Call it 95 dot clocks thus you can simply use a counter and count 95 clocks drive Hsync LOW and that it The entire VGA signal can be generated like this Of course the tough part is when you get to video here you only have roughly 39 nanoseconds to do whatever you are going to do this amounts to more or less doing nothing but accessing a video buffer as fast as you can and getting the next data word ready to build the pixel 10 3 1 VGA Horizontal Timing Referring to Figure 2 13 b each of the 480 lines of video are composed of the following standard named regions A 31 77 us Scanline time 3 77 us HSync pulse C 1 89 us Back porch 25 17 us Active video time 0 94 us Front porch As you can see even the names are similar to NTSC However unlike NSTC VGA is very unforgiving you must follow the spec more closely otherwise the monitor s will typically ignore the signal The next interesting thing is that all the signals are riding on different lines For example the hsync and vsync both have their own signal lines and the R G and B signals do as well so its much easier to generate all the signals in a large state machine and then route them to the output ports as a single byte wide stream of data Therefore
302. in memory and can be access by reading their base address memory locations and then writing memory This is done via the register interface which we will discuss in a moment Finally you can control the top and bottom overscan color of the NTSC screen with a 8 bit register for each That s about all there is to it but this tile engine is more than enough to write 9096 of the games from the 90 s on 8 16 bit machines 22 1 1 GFX Driver Register Interface Before jumping into the header file contents overview want to re enforce that all communications to the GFX driver are thru a set of virtual registers These registers can be read written in most cases and each register usually has a bit of code that executes the read write and does what needs to be done to any low level variables or data structures in the ASM video driver itself Thus much of the functionality of the register interface isn t directly built into the driver but created via code the driver and other added elements to give the user an interface that is more robust Since the GFX driver is a special case want to re enforce that its worth reviewing the Propeller side driver as well so you can see what s really going on We are only going to cover the C AVR side of things here but all these registers functions API etc are all handled at some point on the Propeller running the enhanced graphics driver for NTSC tile graphics With that in mind let s crack open the C
303. ines set to NULL device 0 SPI CS PORT 0 lt lt SPI CS1 0 lt lt SPI CSO Additionally there might be timing constraints on how fast you can read bytes of data from the SPI device you are dealing with Thus you might have to put a delay after each read etc Function Prototype unsigned char SPI Write unsigned char data8 unsigned char SPI Read unsigned char data8 Description gt These functions are currently empty place holders you might want to fill them up with special non blocking versions of the write and read functionality or something else Example s None Function Prototype long SPI Prop Send Cmd int cmd int data int status Description SPI Prop Send Cmd is the workhorse of the entire inter processor communications system This single function is what is used to send and receive information to and from the Propeller chip Each command has 3 byte always The first byte cmd is the command 0 255 that represents what you want to do These are the same commands that are listed in the header file and the CHAM DEFAULT2 DRV V112 SPIN message dispatcher is listening for The second byte data is the first 8 bit data operand the 3 byte status is the 2 8 bit data operand For commands that require 16 bits then data and status are concatenated to form a 16 bit operand like this msb status data Isb Thus data is the lower 8 bits and status is the upper 8 bits For commands that only require 8
304. ing of 8 data bits and an acknowledge bit Now during a data transfer the Master generates the clock and the START and STOP conditions while the receiver is responsible for acknowledging the reception An Acknowledge ACK is signaled by the receiver pulling the SDA line low during the 9th clock cycle pulse on SCL If the receiver leaves the SDA line high a is signaled and the transfer is not completed In conclusion is a lot more complex that SPI and writing a software implementation is a lot harder as well due to the state machine bus contention and so forth However the AVR 644P has built in hardware as mentioned which makes it all much easier to implement Setting up the registers is still a bit challenging and you have to read the documentation quite a bit to get the hang of it suggest you review the following references for a more complete treatise on DVD ROM CHAM_AVR DOCS 12 avr315 TWI 12 DVD ROM CHAM_AVR DOCS 12 twi programming htm DVD ROM CHAM_AVR DOCS 12 12C_bus pdf Now let s move onto the SPI and library module that implements a very thin layer of software on top of the built in hardware Moreover you may wish to develop much higher level functionality yourself If you do make note that the SD card library uses the SPI functions in this module so you will have to emulate their functionality and linker names 157 2009 NURVE
305. ing the AVRStudio Version Demo Version Description NTSC version smooth scrolls array of space invaders Main Source File CHAM AVR NTSC SMOOTH SCROLL DEMO 01 Additional Files Required CHAM AVR SYSTEM VO010 c h CHAM AVR TWI SPI VO010 c h CHAM AVR VO010 c h CHAM AVR GFX VO010 c h General Requirements Video port connected to NTSC TV monitor Controls Required None Compiling and Running the Arduino Version Demo Version Description NTSC version smooth scrolls array of space invaders Main Sketch Source File CHAM_AVR_NTSC_SMOOTH_SCROLL_DEMO Additional Library Files Required imported automatically by sketch CHAM_AVR_SYSTEM_V010 CHAM AVR TWI SPI 010 CHAM AVR 010 CHAM AVR GFX 010 General Requirements Video port connected to NTSC TV monitor Controls Required None 215 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Technical Overview This demo uses the vertical scroll register to scroll an array of tiles Space invader characters up and down If we wanted to we could scroll the image continuously by course scrolling after each smooth scroll thru the scanlines 0 7 of each character Below is an excerpt that shows the space invader rendering code and the smooth scrolling main loop NTSC Clearscreen basic white NTSC Color 0 draw a matrix of space invaders with extended characters for P 0
306. ing the media cores themselves as well as handing SPI input from the SPI driver itself which is written in ASM running on its own core With the system in this know state let s cover exactly what happens in each phase when the system boots Initialization After reset the MCP software simply loads each of the drivers for NTSC VGA keyboard and serial Finally the main PUB start of the MCP is entered and it starts a core with the assembly language SPI driver Command Processing Loop SPI commands are sent over the SPI channel the virtual SPI driver listens and if it detects traffic it then processes the bytes and places them into a globally shared memory buffer The MCP is sitting a 132 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit loop listening for the SPI driver to place data into this shared memory region When it detects a packet of information it then immediately tries to determine of the command portion of the packet is valid Command Processing and Execution The command processor is a handler that interrogates the previously tokenized input command data form the SPI channel and looks for commands in the packet If a command is found then it continues to process the command pattern and look for the parameters that should follow the command The parameters if any are extracted then the proper handler is entered The handler is where the action happens Each handler is connected to its re
307. ingle AVR chip programmed with the Arduino bootloader and the Arduino software tool you can write code and immediately download to the chip Moreover they ported the tool to Mac and Linux so the experience from Windows to Mac OS X to Linux is more or less the same once you have the tool installed This is good since AVRStudio does NOT even work on Mac or Linux Anyway knew had to try and be compatible with the Arduino tool since it would be very cool if people could use Arduino software and tools on the Chameleons Of course was using the new Atmel 328P in my designs and Arduino was still using the Atmel 168 but hoped they would upgrade in time and they did So now the Chameleons will run the Arduino tool chain and you can use Chameleons as supped up Arduinos Of course our boards are physically different and our headers are slightly different but more or less with a little work any program designed for the Arduino can be ported to the Chameleon in a matter of minutes Then you get the power of the Propeller media processor to display text graphics read keyboards mice and make sounds etc As an example imagine you have an Arduino servo controller program and it uses one of the PWM ports on the AVR 328P Since we are using the same chip the Chameleon has the same PWM ports and we export the pins out to the digital and analog headers just like the Arduino But now imagine that instead of just sending a signal on the digital po
308. ingle pole filter You might want a sharper response in a more high end sound system like a 2 or 4 pole system You can achieve this by daisy chaining our little LPFs together OR you can use an active filter that consumes power based on a transistor or better yet simple Operational Amplifier Op Amp like the LM 741 Or better yet pick an 8 pole switched capacitor filter by National Tl or Linear Tech and the signal will hit a brick wall at the cutoff But for our purposes games simple music audio warnings sound effects etc a single pole passive filter will do fine if there is one thing know most people can t tell the difference between 16 bit 96 KHz sound and 8 bit 11 KHz so sound generation can be a little rough 14 1 3 2 PWM Setup Procedure As mentioned we will write some real code in the software section of this manual but just to get you thinking about it let s briefly digress a moment and work up an example with real numbers so you can see this all in your head Many of you are already sound experts and half of us have written MOD players and done DOS games for years so this is old news simple stuff but a couple of you may never have played with sound so this review can t hurt 70 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit So to PWM modulate a signal we encode the signal onto the PWM carrier by means of encoding the information or analog value of the signal onto the PWM carr
309. initializes the primary SPI hardware on the AVR 328 to master and sets it up so we can transmit and receive Also it s important to recall with SPI whenever you send a byte you receive a byte as well due to the circular buffering of output and input You can review the function yourself for details but it sets the clock polarity and phase polarity to default mode 0 in both cases Also the single parameter sent sp rate is used to set the speed of the SPI interface in the SPI Control Register 0 speed control bits The speed control bits control the divisor to the SPI hardware where the clock source is the input frequency of the AVR 328P thus the control bits set the divisor allowing a number of possible SPI clock rates Writing to the SPI Control Register is straightforward but some bit manipulation and shifting is needed to obtain the desired results thus the constants declared in the H file below can be used to set the clock speed SPI rate bit settings define SPI FOSC 2 0b100 define SPI FOSC 4 0b000 define SPI_FOSC_8 06101 define SPI_FOSC_16 06001 define SPI_FOSC_32 0b110 define SPI_FOSC_64 0b010 define SPI FOSC 128 06011 Finally the function de asserts the CS line so any SPI device connected to the expansion interface will be de selected if it s using the SPI CS line as the chip select recall that you can use any I O line you wish to enable disable a SPI slave but bottom line is only a single SPI devic
310. io 4 xx installer The file is located on the DVD here DVD ROM CHAM AVR TOOLS AVR AvrStudio417Setup exe At this point please launch the AVR Studio installation program You should see the initial splash screen as show in Figure 15 2 77 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 2 Initial splash screen for AVR Studio 4 installer Welcome to the InstallShield Wizard for AVRStudio4 mputer To continue click Next InstallShield Press lt Next gt this will take you to the licensing screen shown in Figure 15 3 below Figure 15 3 AVR Studio License Agreement License Agreement Please read th Welcome to AVR Studio from Atmel Corporation AVR Studio is a Development Tool for the AVR family of microcontrollers The AVR Studio is free of charge and may be freely copied and distributed in its original form AVR Studio enables the user to fully control execution of programs on the AVR In Circuit Eus or on the included AVR Instruction Set Simulator AVR Studio supports source level tion of Assembly and C C programs assembled with the Atmel Corporation s included AVR A or tools from 3rd party vendors AVR Studio runs under Microsoft Windows 98 Windows NT Microsoft Windows 2000 Windows XP Windows XP 64 and Windows Vista usb support for 32 bit only AVR Studio is continously developing In order to get latest upgrades of AVR Studio please visit our web site
311. io Include Example include myfile h The quotes indicate to the compiler to look in the working directory of the project for the header However with the Arduino tool there really aren t header files for your projects anymore that aren t part of an official Arduino library file And library files are located in the hardware libraries directory of your Arduino install directory In other words the location of your library C C code and the header are in the search path of the compiler not the project therefore like any system header stdio h etc you use angle brackets to include your header files Arduino Include Example include lt myfile h gt But usually the only reason you include your own header file is that you have created an Arduino library called myfile and therefore there is a MYFILE directory inside the hardware libraries and there is a myheader c cpp file along with a myfile h Now sometimes you just want to add a header file to your sketch but you don t want to create a library with C C code nor do you need it You just want a header maybe with some macros defines data whatever There is a trick to doing this Step 1 Add the header file to your sketch headers with the following syntax notice the and that quotes are used to enclose the header file this time include neaderfile h Step 2 Copy the header file into your sketch directory You can learn more about include files
312. ion This might be the case if you are using AVR Studio for testing simulation or you simply have a different programmer that is compatible But if you have the AVR ISP programmer then read on This process is actually VERY important since a wrong configuration in the programmer module can send the wrong data to the Chameleon AVR and ultimately to 328p chip If we send the wrong bits to the chip we can potentially damage it or lock it up for eternity which would be very bad Therefore it s prudent to pay close attention to the programmer setup and know exactly what all the tabs and configuration settings do We will spend a good amount of time on this First things first we have built the project thus if you navigate into the project directory cham_avr_work_01 default within the Source directory you will find a HEX file with the name cham_avr_work_01 hex within it This is the final result of all our hard work now we just need to get it into the Chameleon AVR so let s see how to do that now 98 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit From the Main Menu select Tools Program AVR Connect this is shown in Figure 15 33 below Figure 15 33 Launching the programmer selection tool AVR Studio D i File Project uv development chameleon cham_avr source cham_avr_work_01 CHAM_AVR_HELLO_WORLD_01 Build Edit View Tools Debug Window Hel
313. ion for our use Os 1 or O2 are a safe settings You can experiment later with various optimization settings but the Device and Frequency should be equal to the values above To the right of these settings are number of checkboxes these control some of the GCC compiler s options which you can read about in the GCC documentation However they are pretty straightforward and similar to every other compiler s settings They are only a subset of the dozens of compiler settings that you might want to set with GCC but are some of the most common embedded programmers like to play with In our case the only one we want checked is Pack Structure Members All this does is pack structures tight rather than pad them to put them on WORD or other various boundaries In essence saves memory Finally there are 3 checkboxes at the bottom of the page Create Hex File Create Map File Generate List File These are important and should be checked You should be familiar with the map and list file if you re a C C programmer but for those that don t here are some basic definitions MapFile A file generated by a compiler typically lists the memory organization usage and symbol allocation as well as bindings Very useful 90 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit List File This is the most useful output from a compiler it contains the actual ASM code generated by the compiler along with the
314. ion and plug it into some larger application Normally to get something interfaced with the PC is nightmare in the era or post legacy devices where only USB connectors exist and there are no parallel or DB9 serial ports But with the Chameleon its easy you just write your driver code on the Chameleon use the serial UART library to communicate to the PC and send the information Moreover you can display status and what s going on thru one of the local video ports of the Chameleon so even if the PC is remote the local Chameleon can display what s going on and what its being told to do by the PC 14 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit The possibilities are limitless with the Chameleon We wanted to take the work out of generating video audio reading keyboards and mice out of the picture for you but at the same time insulate you from what s going on under the hood unless you really want to know Next let s inventory your Chameleon AVR 8 Bit Kit Figure 1 2 Chameleon AVR 8 Bit kit contents DVD not shown BREAK AWAY SCORING t gt gt I Z i MIL 2 ak B3 3505 Z4 zc u cuurc PES PREPS Ree REC UY PEP SERRE EKER BET eer ee eee eee eee See es ee
315. is flag indicates certain compiler standards that we do not want to apply thus we need to delete the flag Simply highlight it and then click Removes in the upper right hand side of the dialog Finally make sure in the External Tools section at the bottom of the dialog the Use WinAVR checkbox is selected if you wanted to you could actually change the path to the compiler and make tools here to other versions but that s for advanced users only This completes the Project Options dialog settings click Ok and let s move on 15 1 4 2 Adding Files to the Project Now we are ready to actually add files to our project but first we need some files to add Before we get into that let s briefly recap what we have been doing since at this point you might have forgotten what all these steps where for So we created a new GCC project but before getting started we had to configure a number of components in the tool chain before we could do anything At this point AVR Studio is ready to go and we can actually add the source files we want to compile and hopefully the compiler and linker will build our application perfectly The first step is to copy the source files from the DVD ROM to the installation directory on your hard drive To do this you need to locate the Source directory inside your AVR installation it should look something like the listing shown in Figure 15 27 Figure 15 27 The Source directory in the AVR Studio installatio
316. is used as the memory increment stride each read write operation This comes in handy and reduces address updates when you access continuous memory There is of course a function to change tile_mem_autoinc_parm Example s Read the 16 bit WORD of memory currently pointed to by the source memory pointer datal6 GFX Read Mem Port16 Function Prototype unsigned int GFX Write Mem Port16 unsigned int data Description GFX Write Mem Port16 writes a 16 bit value to prop memory source ptr data note source pointer is always used for memory port operations read or write In the Propeller driver source ptr is the variable src parm and is set using GFX Set Src Ptr unsigned int src ptr defined below The idea of this function is that it provides a simple mechanism to access the Propeller s RAM This function also updates the source pointer automatically anticipating another read or write The actual code looks like update src pointer based on auto increment value tile src addr parm tile mem autoinc parm Thus the variable mem autoinc parm is used as the memory increment stride each read write operation This comes in handy and reduces address updates when you access continuous memory There is of course a function to change mem autoinc parm Finally the function always returns 1 Example s Write 1234 to the 16 bit WORD of memory currently pointed to by the source memory pointer GF
317. itor Font size 12 requires restart of Arduino Delete previous applet or application Folder on export C Use external editor Check For updates on startup Automatically associate pde Files with Arduino More preferences can be edited directly in the File C Documents and Settings NECRON Application DatalArduinolpreferences txtk edit only when Arduino is not running Then browse for the location where you copied the sketchbook SKETCHES from the DVD ROM and point the Sketchbook Location to this directory that contains the folder Click lt OK gt Setting the Proper Target Next we need to make sure that the Arduino tool has the correct serial port and the correct target chip To do this select the Tools Board from the main menu and select Arduino Duemilanove or Nano w ATMega 328 which is the top most item This is shown in Figure 15 55 116 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 55 Selecting the proper AT328P target for the Arduino tool m sketch sep24a Arduino 0017 Eak Edit Sketch 5 Auto Format Archive Sketch Fix Encoding amp Reload Board Serial Port Burn Bootloader Arduino Duemilanove or Nano w ATmeg Arduino Diecimila Duemilanove or Nano w ATmegal68 Arduino Mega Arduino Mini Arduino BT LilyPad Arduino w ATmega328 LilyPad Arduino w 168 Arduino Pro or Pro Mini 3 3V 8 MHz w ATmega32
318. iver on the Propeller has drivers for both keyboard and mouse support Thus we have developed a simple API to communicate to both the keyboard and mouse driver running on the Propeller one at a time of course The AVR 328p processor comes with two hardware UART s but we have developed a library of functions that abstracts the functionality so you can perform buffered I O very easily with interrupt driven drivers The AVR 328p has built in Serial Peripheral Interface hardware as well but there is quite a bit to set it up and communicate with it thus we have created a nice abstraction layer to initialize it read and write bytes The AVR 328p again has built in hardware for Inter Integrated Circuit communications but the hardware is tricky to setup and the I2C protocol is a bit difficult to work with so once again we have developed a software layer on top of it for your convenience The Chameleon AVR has a 1MB SPI FLASH memory on board which can be used for storage of assets data code whatever you wish This driver API runs 10096 on the client AVR chip and gives you the ability to read and write sectors pages in the FLASH memory erase etc Considering that you might want to write some software to abstract the FLASH memory into a FAT16 like device All you need are functions to read write sectors pages which we provide then you can use a 3 party library to add support so the FLASH memory feels like a FAT16 drive There are numer
319. k drives each processor clock and each processor executes one instruction per 4 clocks thus 20 MIPs on average Now if we want to go a little faster we could use a 6MHZ XTAL and then use the pll16x directive once again this results in a clock rate of 96 MHz and 24 MIPS per processor Depending on your Propeller chip this might work as is however the transitions are so fast that the noise margins etc of the signals become small and the capacitive loading too much for the 3 3V supply this you might need to increase the power supply voltage to 3 6 volts to get this speed to work But point is if you need a little bit more you can increase you oscillator xtal a bit and then see if it works Also the Propeller will get hotter as you overclock it thus you might have to heat sink it H 2 Overclocking the AVR328P Microcontroller The AVR is a little bit different than the Propeller chip a little more forgiving plus its already running at 5V The AVR is spec ed to max out at 20 MHz but we are running a 16MHz xtal for Arduino compatibility However if you do not want to use Arduino mode or the bootloader then go ahead and pop in a 20 MHz parallel resonant mode Xtal and you get 4 MIPs for the taking However if you want more than you can do it as well The max overclock of the AVRs is about 35 MHz before they simply fall apart and stop working find that 8xNTSC or 28 636636MHz is a nice compromise tested over 1000 units and they
320. l of 1 0V for the total SYNC gt WHITE video amplitude peak peak voltage 11 2 Introduction to NTSC Video A video image is drawn on a television or computer display screen by sweeping an electrical signal that controls a beam of electrons that strike the screen s phosphor surface horizontally across the display one line at a time The amplitude of this signal versus time represents the instantaneous brightness at that physical point on the display Figure 11 2 illustrates the signal amplitude relationship to the brightness on the display At the end of each line there is a portion of the waveform horizontal blanking interval that instructs the scanning circuit in the display to retrace to the left edge of the display and then start scanning the next line Starting at the top all of the lines on the display are scanned in this way One complete set of lines makes a frame Once the first complete frame is scanned there is another portion of the waveform vertical blanking interval not shown that tells the scanning circuit to retrace to the top of the display and start scanning the next frame or picture This sequence is repeated at a fast enough rate so that the displayed images are perceived to have continuous motion 11 2 1 Interlaced versus Progressive Scans These are two different types of scanning systems They differ in the technique used to render the picture on the screen Television signals and compatible displays
321. l the driver over the SPI link get absolute relative position and the buttons simple The Mouse module header CHAM_MOUSE_DRV_V010 h actually has nothing in it once again I told you this stuff was easy However the mouse does use a data structure located in the global system file CHAM_AVR_SYSTEM_V010 h the data structure is shown below generic input device data record type helps get back data from various multidata calls struct gid_event_type position data buttons bit encoded bit4 right side button i left side button center scrollwheel button right button left button int X y z int buttons o ct N Woo won i gid_event gid_event_ptr Its nice to think of input devices in all the same way and thus wrap a container around them This data structure was created with that in mind for future expansion So all mouse messages use this container The first ints are the x y position the 3 Z is usually the scrub wheel The next int buttons is a bit encoded representation of all the buttons on the mouse up to 5 different standard buttons The API listing for the Mouse module CHAM_MOUSE_DRV_V010 c is listed in Table 25 1 categorized by functionality Table 25 1 Mouse module API functions listing Function Name Description Mouse Driver Control int Mouse_Load void Loads the mouse driver int Mouse Unload void Unloads the mouse driver 201 2009 NU
322. lable and other languages if you search the Parallax site 25 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 1 31 Propeller Core COG Video Hardware Lastly let s talk about the video hardware for a moment Probably the coolest thing about the Propeller chip is that each core has a little state machine that can stream video data out These little devices are called Video Streaming Units or VSUs and every core has one Thus you in theory drive 8 different video signals at the same time The VSUs are not graphics engines GPUs even 2D stuff They are nothing more than serializers that send bytes out to port However they send bytes out at a specific rate and the analog signals they can generate can be timed to synthesize NTSC or PAL signals including blanking sync chroma and color burst signals In essence with each core you can use software to set up the VSU units then the unit will send out data representing one portion or chunk of the video signal then you feed it more Therefore you have to know how to generate NTSC PAL or VGA yourself but the VSU helps and offloads a lot of the timing and critical coding you would need to do usually Alas once again you don t have to worry about this Myself and numerous other programmers have written countless video drivers for the Propeller chip Everything from bitmap graphics text modes to sprite engines So if you want graphics you just find a driver add i
323. lack must be consistent In general here are the steps to generating an NTSC signal 49 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 11 7 NTSC Super Frame video signal reference for NTSC frame construction HD ODD FLD1 FIELD 1 Va i EVEN FLD2 Lil L L 1 l __8TART FIELD 2 A ODD i i i i i lt i i FLD3 lt STAAT FIELD 3 AV VERTICAL BLANKING INTERVAL 3 FLD4 PRE EQUALIZING VERTICAL SYNC PULSE POST EQUALIZING ja stant PULSES sennArION PULSES FIELD 4 i i i COMPOSITE BLANKING Al ee J EJ E COMPOSITE BLANKING VERTICAL 8YNC EVEN fono VERTICAL SYNC 11 2 5 1 Frame Construction Referring to Figure 11 7 This diagram represents the NTSC color Super Frame The complete NTSC spec actually has 4 fields per super frame if you want to follow the spec and interlace 100 We aren t going to follow the spec 100 but we are going to follow some of the more important parts of the spec one such area is in the vertical syne and equalization pulses area please concentrate your attention on this area of Figure 2 20 for the description below A Frame is composed of 262 5 lines non interlaced 262 will suffice Of those 262 lines
324. library named AVR Libc is installed which you can leverage for your C C programs It more or less implements the standard C C library but additionally has a multitude of AVR and embedded system specific functions and libraries along with it AVR Studio 4 xx and WinAVR are located on the DVD ROM at these locations DVD ROM CHAM_AVR TOOLS AVR AvrStudio417Setup exe DVD ROM CHAM_AVR TOOLS AVR WinAVR 20090313 install exe AVRISP MK II AVR ISP is simply a piece of hardware and Windows will detect it and install the drivers from the AVR Studio install thus there is no software per se that we need to worry about However if you wanted to install AVR ISP by itself then there are stand alone programming applications from Atmel But we aren t going to consider them since we will use AVR Studio which has programming and debugging built in 15 1 1 Installing AVR Studio 4 xx Optional Installing AVR Studio is relatively straightforward as long as you know what you re doing to begin with This is the problem with many IDEs and installation programs you have to install the tool to figure out what not to do and then in many cases un install the tool then re install it To save you all this grief we are going to install the tool together step by step with a complete set of screen shots of each step along with explanations Thus without further ado let s get this done The first step is to locate and launch the AVR Stud
325. linking demo and then modified it to directly send the new messages Here s the entire program AVRStudio straight C version INCLUDES AA Bg B lE LL Ma EL LL B M UE LH LL Bl LL EL LL lg EL LL d LH LP Ll MIU MM M IMP Pg gg M PP Lg P PP P gg M PL Pg Pg Ln P P P gg gg M TTT __AVR_ATmega328P__ AVR 168 252 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit define __AVR_ATmega328P__ include everything include lt stdint h gt include lt stdio h gt include lt stdlib h gt include lt string h gt include lt ctype h gt include lt avr eeprom h gt include lt avr io h gt include lt avr sleep h gt include lt util delay h gt include lt avr interrupt h gt include lt avr pgmspace h gt include lt inttypes h gt include compat twi h gt include lt avr wdt h gt include headers required for demo include CHAM AVR SYSTEM V010 h you need this one always include CHAM AVR SPI DRV V010 h you need this always include CHAM AVR NTSC DRV V010 h needed for NTSC driver APP M LLL LY S ML MM MIB B B B Bl l lE EAT g MeL EEE define CPU frequency in MHz here if not defined in Makefile or other includes compiler will throw a warning ignore HT fndef F_CPU CPU 1600000001 2863636001 1431818001 21477270 UL endi
326. ll all your applications and add the C file to your source tree for all applications as well Next we will take a look at some excerpts from the header file review key elements and any data structures that are of interest 15 1 1 Header File Contents Overview The header files for many of the API modules are rather large and we won t have time to list their contents out in their entirety however the System header is quite manageable so we are going to take a look inside To begin with the header contains some useful macros macros to manipulate bits define SET_BIT value bit value value 1 lt lt bit define sET bit 1 lt lt bit define RESET_BIT value bit value value amp 1 lt lt bit define RESET bit lt lt bit define WRITE BIT value bit num bit val value value amp 1 lt lt bit num bit_val lt lt bit num define SETPORTBITS b7 b6 b5 b4 b3 b2 bl b0 bz lt lt 7 b6 lt lt 6 b5 lt lt 5 04 lt lt 4 b3 lt lt 3 b2 lt lt 2 b1 lt lt 2 60 lt lt 0 conversion macros define HEX_TO_DEC n n gt 0 amp lt 9 n 0 gt A amp n lt F n a 10 0 a more useful random function define RAND RANGE x y x CrandO CCy OCO41 RESET MACROS T M M MlIMMIMMMIIIMMMMMMPMPWPUMBMLMLWMPWMPLGB B BN B BP IM B M P P M
327. lly when every key released there is another scan code referred to as the break code that in most cases is composed of E0 followed by the original make code scan value However many keys may have multiple make codes and break codes Table 12 2 lists the scan codes for keyboards running in default mode startup Table 12 2 Default scan codes KEY MAKE BREAK KEY MAKE BREAK N KEY MAKE BREAK 1C 0 1 0 46 E 54 54 Fr mz INSERT 0 70 70 pep pru 4E FO 4E HOME E0 6C EO F0 6C D 23 23 55 FO 55 PG UP 70 EO FO 7D Fx REN 5D F0 5D DELETE E0 71 EO F0 71 28 ro25 Besp 66 roee END E0 69 EO F0 69 34 34 SPACE 29 F0 29 PG DN E0 7A 33 F0 0D U ARROW E0 75 75 BEC F 20 58 L ARROW E0 6B E0 F0 6B L SHEET 12 roai2 D ARROW 72 72 FO 42 L CTRL 14 20 14 ARROW 74 74 ro 48 L GUI soar Eo ro ir NUM 2 F0 77 1 4 4 31 rosa 59 ross KP 7C FO 7C 14 FO 44 CTRL 0 14 E0 F0 14 7 FO 7B 4D 0 277 0 27 KP 79 79 1 0 15 0 11 11 E0 5A R 20 F0 2
328. lp sow TAS MEF YX AVR GCC Rebuild All x P BuildandRun Ctri F7 2 29 Source Compile Alt F7 E X Clean 12 Export Makefile CHAM_AVR_TWI_SPI_DRY_VO10 c CHAM AVR VGA DRY VO10 c Header Files AVR NTSC DRV vO10 h CHAM AVR SYSTEM VO10 h CHAM AVR TWI SPI DRV VO10 h E CHAM AVR VGA DRY vo10 h External Dependencies E Other Files If the build was successful then you should see the compiler output in the bottom window as shown in Figure 15 32 97 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 32 A successful build indicating data memory size warnings etc D develop ameleon cham_avr so am_a ork 0 R WORLD 0 DER File Project Build Edit View Tools Debug Window Help du ida dam c CO Fx Ua gt nE 0 Trace Disabled Some AVR GCC x DII E RC UEZZMJNZ ZZZ EDDIINEEBBE IZIBDEUNUEZAEEZTEZHNIUEZ ADNWI SSgHBNUUUUU cham avr work 01 default 23 Source Files E CHAM_AVR_HELLO_WORLD_O1 c E CHAM AVR NTSC DRV VO10 c Copyright Nurve Networks LLC 2889 Filename CHAM AUR HELLO UORLD 81 C E CHAM AVR SYSTEM VO10 c ne Original Author Andre Lalothe E CHAM_AVR_TWI_SPI_DRV_v010 c 77 E CHAM_AVR_VGA_DRV_V010 c Last Modified 9 22 09 Sy Header Files CHAM AVR NTSC DRV
329. lt 6 for x 0 x lt NUM SPACE INVADERS ROW X position next invader NTSC_SetXY x 2 SPACE_INVADERS_ORIGIN_X y 2 SPACE_INVADERS_ORIGIN_Y draw next invader NTSC Term Char SPACE_INVADERS_CHAR_OFFSET y 3 end for x end for y enter infinite loop while Cl1 set smooth scroll vertical position register 0 7 change scroll position scroll y scroll dy test for limit if Cscroll y gt 7 Cscroll y lt 0 scroll dy scroll dy scroll y scroll dy 3 end if slow things down a bit so we can read the text _delay_ms 50 end while have highlighted the single API call that sets the smooth scrolling register that s all there is to it Summary This demo shows how easy it is to smooth scroll vertically Additionally it shows some of the hidden special characters in our little character set to help make games 216 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 28 1 4 VGA Printing Demo This demo simply uses the VGA terminal API to print Hello World to the VGA screen Figure 28 4 shows the demo in action Figure 28 4 VGA terminal printing demo llo 11 o World Hello World 1 Hello World rid Hello World Hello World Hello World Hello World Hello World ello World Hello World lo World Hello World World Hello World
330. lt SPI CS1 0 lt lt SPI CS0 Function Prototype int SPI Set Speed unsigned char spi rate Description SPI Set Speed simply updates the speed of the SPI interface in real time allowing you to throttle 163 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit the SPI interface In many cases SPI protocols demand that the slowest speed is used to initiate communications with the SPI hardware then you can throttle the speed up and or read maximum speed supported from the SPI device itself In any event this function gives you the ability to change speed on the fly basically updates the SPI speed setting control bits The parameter spi rate is the same used in the initialization function so are the possible parameter values Returns 1 always Example s Assuming the SPI interface has already been initialized reset the speed to the maximum rate which is 1 2 the clock rate or 14 MHz roughly most SPI devices should easily be able to handle this speed SPI Set Speed SPI FOSC 2 Function Prototype unsigned char SPI Send Byte unsigned char data8 unsigned char SPI WriteRead unsigned char data8 Description Both of these functions are aliases for each other and have the exact same body thus we will refer to both as SPI WriteRead since it s a little shorter to type Recalling that the SPI protocol always writes 8 bits at a time and reads 8 bits at a time each
331. ly scroll the text screen up if printing on last line of display Additionally this function is sub command conduit to the terminal manager This 173 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit functionality should be maintained for any drivers that you develop so users can have a standard set of base terminal functionality You can send the following ASCII codes some functions are redundant 00 clear the screen 01 home the cursor to top left 08 backspace 09 tab 8 spaces per 0A set X position X follows 0B set Y position Y follows 0C set color color follows 0D return carriage return and linefeed Example s Clear the screen then print Chameleon VGA_Term_Char 0x00 VGA _Term_Char C VGA _Term_Char h VGA _Term_Char a VGA _Term_Char m VGA _Term_Char VGA _Term_Char 1 VGA _Term_Char VGA Term Char VGA Term Char n Function Prototype Example s Print the string Hello World to screen int VGA Term Print char string Description Term Print prints NULL terminated string to the screen with automatic scrolling etc if the string prints off the right of the screen or bottom of terminal Returns 1 Term Print Hello world Function Prototype int VGA Color int col D
332. m src gt dest in byte size chunks define GPU GFX SUBFUNC FILLMEM8 3 Fills memory with low byte of datal6 1 bytes at a time normal commands d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine efine GPU_GFX_TILE_MAP_R GPU_GFX_TILE_MAP_W GPU_GFX_DISPLAY_PTR_R GPU_GFX_DISPLAY_PTR_W GPU_GFX_TERM_PTR_R GPU_GFX_TERM_PTR_W GPU_GFX_BITMAP_R GPU_GFX_BITMAP_W GPU_GFX_PALETTE_R GPU_GFX_PALETTE_W 2 GPU_GFX_BASE_ID 3 GPU_GFX_BASE_ID 44GPU GFX BASE ID 54GPU GFX BASE ID 64 GPU GFX BASE ID 7 6 GFX BASE ID 84GPU GFX BASE ID 9 GPU GFX BASE ID SS SS SS SS Sl SL SS Fs Reads 16 bit tile map ptr which points to the current tile map displayed writes 16 bit tile map ptr which points to the current tile map displayed Reads 16 bit tile map ptr which points to the current display ptr into the tile map low level print functions use this pointer writes 16 bit tile map ptr which points to the current display ptr into the tile map low level print functions use this pointer Read
333. me as the HYDRA and Propeller Development boards but there are differences for example in what pin bank is used for the NTSC video or what pin for audio etc so when porting something make sure you look at the pinouts of the source and change them to match the Chameleon s Peripheral devices The Chameleon does have a NES game port for example so any game or program on the HYDRA that you want to port you will need to delete that peripheral code or swap it for something else Of course you can always hack a connector to the Propeller Local port and connect the controller there and switch the pins in the source code Also the Chameleon s uses a 2 line version of the keyboard and mouse drivers the HYDRA and other Propeller development boards might use a 4 signal version so watch out for that And lastly the Chameleon has a single sound PWM sound pin that routes to the RCA header some Propeller dev boards use stereo sound so in those cases you will want to route one of those pins to the Chameleon pin and leave the other dead or maybe out to the local 8 bit port Other than those 3 areas find that it takes a few mins to port anything from the HYDRA or a Propeller Development board to the Chameleon and use it in Stand Alone mode so pretty cool Appendix G Running on the Mac and Linux AVRStudio is currently only available for the Windows operating system Although many people love their Macs and Linux 90 of engineering d
334. mind c D 0016 E REM_AVR_NTSC_128_96_ULTRA_VO10 h op_Send_Cmd READ CHD 6x66 6x66 REM_AVR_NTSC_128_96_ULTRA_VO10 h Ses Program Verity Read F REM_AVR_NTSC_BMP_224_168_8_V010 h let prop finish transaction REM_AVR_NTSC_DOOM_FLOOR_8_ O11 h delay_us SPI_PROP_DELAY_LONG_US EEPROM REM AVR NTSC ROTOZOOM 8 V010 h E rem avr ultra sprites h rem avr ura tles h bg tiles h bg tiles h Use Current Simulate lator EEPROM Memory Input HEX File D development xgs2 avi source wgs_avi_test default Program Verity Read ELF Production File Format result EEEEEEEEEEEEEEEEEEE d development xgs2 avr source xgs_avr_test CHAM_AVR_TEST PGM_VERI c D development xgs2 avr source xas Build Input ELF Fie DAdevelopment wgs2 avi source ws_avi_test defauit Program Fuses and lockbits settings must be specified before EMG saving to ELF E Build Message Find in Files Breakpoints and Tracepoints ATmega644 Simulator 9 CAP NUM OVR AVR Studio is shown in Figure 1 7 it s a standard Windows application that is used to develop applications for the entire line of AVR microcontrollers It s very similar to Visual C but not as polished you will find little quirks with file management focus issues etc The IDE allows viewing of the
335. mo that is pre loaded on each unit To compile it you follow the same process as you would for all the other examples There are two versions one for the native AVRStudio mode and a Arduino based Sketch You can find the files for the AVRStudio version on the DVD here DVD ROM CHAM_AVR SOURCE DEMO CODERS _ The Arduino sketch version is located on the DVD here DVD ROM CHAM_AVR TOOLS ARDUINO CHAM_AVR_CRATE_IT You should have already copied this on your hard drive during the installation process earlier in the manual Any other newer demos will be located in the DEMO_CODER directory so take a look there in case we don t update this manual to match Similarly always check the product web pages on www xgamestation com as well as www chameleon dev com Epilog From Intel 4004 to the Multiprocessing Multicore Chameleon Well you made it If you got this far then you should be a quite comfortable with the Chameleon AVR 8 Bit and see the true power of multiprocessing and the synergy between the Atmel AVR and the Parallax Propeller chip Hopefully you can use the Chameleons in many of your projects now and in the future am really excited about these little machines and haven t had this much fun programming something in a long time they just work and allow to solve problems very quickly and get software done for real world applications It always amazes me to think about how far we have come in
336. mode to test if a mouse is connected and if its working 12 2 4 Sending Mouse Commands A mouse command similar to a keyboard command is sent using the standard 11 bit serial protocol outlined in the Keyboard Write section The commands supported are shown in Table 12 7 Table 12 7 Lists the set of command accepted by the standard PS 2 mouse Code Description FF Reset The mouse responds to this command with acknowledge FA then enters Reset Mode FE Resend The host can send this command whenever it receives invalid data from the mouse The mouse responds by resending the last packet it sent to the host If the mouse responds to the Resend command with another invalid packet the host may either issue another Resend command issue an Error command cycle the mouse s power supply to reset the mouse or it may inhibit communication by bringing the Clock line low The action taken depends on the host F6 Set Defaults The mouse responds with acknowledge FA then loads the following values into its driver Sampling rate 100 Resolution 4 counts mm Scaling 1 1 Disable Data Reporting The mouse then resets its movement counters and enters Stream mode F5 Disable Data Reporting The mouse responds with acknowledge FA then disables Data Reporting mode and resets its movement counters This only effects data reporting in Stream mode and does not disable sampling Disabled Stream mode functions the same as R
337. mpiler to the linker to the debugger Make is typically used by Unix Linux programmers and of course is part of the GCC tools we are using Thus you can use an external makefile if you wish Luckily WinAVR takes care of this for us and generates the make file so we don t have to Next the under Output File Name should be the name of the project itself with the extension elf Elf is the final output of the compiler and linker which is ready for conversion to the binary image downloaded into the AVR EIf stands for Executable and Linkable Format and is a very common file format for executable files binary objects and other objects that are ready to be loaded or executed on various platforms The WinAVR uses it as an intermediate format before the final binary AVR hex image is generated that we will download into the Chameleon each time Under the Output File Directory you can set anything you wish but for now set it to default as shown in the figure This is where the final output will go and the binaries will reside with the data ready for the programmer itself to download to the Chameleon AVR target The next settings panel has a lot of settings that need to be addressed let s talk briefly about each Device Sets the actual target device in our case set to atmega328p Frequency Sets a constant for the compiler equal to F CPU set to main frequency of 16 000 000 Hz Optimization Sets the level of optimizat
338. n AVR 8 Bit be sampled by the host computer on the data line on the falling edge of the CLOCK line driven by keyboard Below is the general algorithm for reading the keyboard Figure 12 3 Keyboard Serial Data Packet Parity St 8 Data Bits Sent d0 d7 B Scan Code 0x16 ASCII 1 12 1 2 Keyboard Read Algorithm The read algorithm makes the assumption that the main host has been forcing the keyboard to buffer the last key This is accomplished by holding CLOCK LOW Once the host releases the keyboard then the keyboard will start clocking the clock line and drop the DATA line with a start bit if there was a key in the buffer else the DATA will stay HIGH So the following steps are after the host releases the keyboard and is trying to determine by means of polling if there is a key in the keyboard buffer Step 1 Delay 5 us to allow hold on CLOCK line to release and keyboard to send buffered scan code Step 2 Start of frame If both CLOCK and DATA are low start bit then enter into read loop else return no key present Step 3 Start of data Wait until clock goes high Step 4 Read data Read data bits loop pseudo code for t 0 t lt 7 t wait for CLOCK to go low delay 5 us to center sample bit t DATA 3 end for Step 5 Read parity and Stop Bits Lastly the parity and Stop Bits must be read And that s it Of course if you want to be strict then you should read the
339. n any event referring to Figure 16 5 The objects used are shown in Table 16 2 136 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 16 2 Objects used for the Chameleon default MCP drivers Function Version Top object file MCP master control program 1 11 CHAM_DEFAULT2_DRV112 spin NTSC 1 1 CHAM_GFX_DRV_001_TB_001 spin TV Text Half Height 011 spin Note 1 Many of the drivers include other sub objects as well Note 2 There are two versions the MCP driver one is called CHAM DEFAULT2 DRV V112 spin this is used for all our examples However there is a slightly modified version called CHAM DEFAULT1 DRV V112 spin that uses the plain vanilla NTSC terminal that might work better on some LCDs You can drop down to it if you have trouble with the default2 driver Note 3 The Chameleon only has one PS 2 port so only one driver keyboard or mouse can be active at once However the default MCP driver can hot swap the drivers so you can unplug the keyboard mouse in real time and with software start the new device All of the drivers and their sub objects are included in the source directory for this chapter located on DVD ROM in DVD ROM CHAM AVR SOURCE PROPELLER DRIVER If you look on the Parallax Object Exchange you should be able to find most of these drivers as well however we will use the ones from my chapter and my sources since made slight modifications to each of them
340. n automatically install or update the driver For Parallax LISB based products like the Propeller Demo Board and Prop Clip Plug This driver is required to communicate with these products Automatically install update driver recommended Step 4 The tool is ready to be installed Figure 15 62 below shows the installation ready dialog click lt INSTALL gt to begin the installation Figure 15 62 The final installation dialog before the software is installed m The Propeller Tool v1 05 5 Installer x Ready to Install the Program t The wizard is ready to begin installation LL Click Install to begin the installation If you want to review or change any of your installation settings click Back Click Cancel to exit the wizard Cancel Step 5 As the software installs the first thing it will do is install the FTDI inc USB drivers that the Propeller Tool relies on so you should see a message box like that shown in Figure 15 63 below Figure 15 63 The FTDI USB drivers successfully installed FTDI Driver Installation 9 FTDI CDM Drivers have been successfully installed Step 6 Click OK and the final installation should take place you will see a dialog like that shown in Figure 24 0 below click FINISH and this should complete the installation of the Propeller Tool IDE and the associated USB drivers it needs 123 2009 NURVE NETWORKS LLC
341. n color so 15 gt 0 color color 1 lt lt 4 finally write it back GFX Set Bottom Overscan 1 color Function Prototype int GFX Set Overscan Color int col Description GFX Set Top Overscan Color sets the top overscan color to col where col is in normal Propeller color format chroma 4 bit chroma enable 1 bit luma 3 bit Returns 1 Example s Read the current color and increment the chroma portion of the color upper 4 bits retrieve the color int color GFX Get Bottom Overscan Color now add 1 to the upper 4 bit nibble allow wrap around rather than clamp on color so 15 gt 0 color color 1 lt lt 4 finally write it back GFX Set Bottom Overscan 1 color 23 0 Sound Library Module Primer The basic premise of the Chameleon design is that it leverages drivers running on the Propeller chip to do all the media and graphics Thus whatever features the particular driver running on the Propeller side is the only features we can access via the AVR side That doesn t mean we can t abstract functionality and add higher level functions that build on the sub functions however this probably isn t productive since you will want to change drivers re write the Propeller driver and so forth Thus for the majority of the media drivers all the API functions do including the sound is expose some of the base functionality in nice function calls so you
342. n one update so just use byte 2 and 3 to track motion The motion counters are updated when the mouse reads its input and movement has occurred The movement counters once again only record differential or delta motion rather than absolute With a 9 bit value recording each counter a total amount of 255 to 256 can be represented in 9 bit 2 s complement If this range is exceeded the appropriate overflow bit is set for either the X or Y counter Note that the movement counters are reset whenever a movement data packet is successfully sent to the host The counters are also reset after the mouse receives any command from the host other than the Resend FE command Next let s discuss the different mouse operation modes 12 2 3 Modes of Operation There are four standard modes of operation which dictate how the mouse reports data to the host they are RESET The mouse enters Reset mode at power up or after receiving the Reset command For this mode to occur both the DATA and CLOCK lines must be HIGH STREAMING This is the default mode after Reset finishes executing and is the mode in which most software uses the mouse If the host has previously set the mouse to Remote mode it may re enter Stream mode by sending the Set Stream Mode EA command to the mouse REMOTE Remote mode is useful in some situations and may be entered by sending the Set Remote Mode F0 command to the mouse WRAP This diagnostic mode
343. n or where you want your projects File Edit Favorites Tools Q sxx gt search lig Folders EJ J Address D development chameleonicham_avrisource mw cham avr work 01 File and Folder Tasks Other Places cham avr My Documents Shared Documents 4 My Computer My Network Places Details cham avr work 01 File Folder Date Modified Today September 23 2009 1 06 AM 1 objects selected 3 My Computer If you navigate into the directory this is where the project we created should reside in a directory called cham_avr_work_01 Yours should looks something like the listing shown in Figure 15 28 if you navigate into the project directory 94 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 28 A look inside the project directory cham_avr_work_01 Edi Favorites Tools Help Qs Q P Search 2 Folders E Address B D development chameleon cham_avr source cham_avr_work_01 cham avr work O1 aps File and Folder Tasks 3 cham_avr_work_O1 aws Other Places source E My Documents Shared Documents 4 My Computer My Network Places Details cham avr work 01 File Folder Date Modified Today September 23 2009 1 06 AM 3 My Computer Referring to the figure the sub directory cham_avr_work_01 is highlighted this is where yo
344. n t have to deal with it all yourself However it s good to understand the protocol if you need to manually build a SPI interface with I O pins For example maybe you need 4 SPI interfaces all at the same time on the Chameleon s expansion port the only way to do this will be to do it manually with pin toggling However the AVR 328P s USARTS basically UARTs with extra features both support SPI modes In other words even though the AVR 328P has a primary SPI controller the USART on the AVR 328P can be put into SPI mode as well giving you 2 fully functioning SPI devices interrupt driven etc This is very good news Moreover the Chameleon s expansion headers port exports out the master SPI device itself as well as the ancillary SPl mux selects Using the AVR SPI interface is straightforward the steps are Initialize the hardware set speed clock phase and polarity etc Send and receive bytes via a pair of registers and possibly interrupts That s all there is to it Of course there s a lot of detail to getting things to work and believe me had my share of frustration figuring out the little quirks but the library functions provided shortly will get you up and running very quickly with SPI interfacing Also you can always write you own or use external libraries The AVR Libc system does not have any SPI library of note but there are many out there like the Procyon library located here http hubbard engr scu edu embed
345. n there Yup this is where you are going to copy the SKETCHES from the DVD directory previously mentioned So do that now this is simply all the projects for the manual all pre built and ready to go Now go ahead and dive into the ARDUINO 0017 directory and take a look around go into all the directories as deep as you can then when you are done exploring come back to the root which should look like the folder shown in Figure 15 44 Figure 15 44 The Arduino installation directory contents amp arduino 0017 EIE Lj File Edit View Favorites Tools Help Bak Q2 pe Search Key Folders E Address 3 D development chameleon cham_avrisource ar msn D drivers arauino exe File and Folder Tasks examples 55 cygiconv 2 dll hardware 55 cygwint dll Biava 8 libusbo dl lib E readme txt arduino reference S xtxSerial dll My Documents tools 23 Shared Documents 13 objects My Computer As you can see there are a lot of files hundreds if not a couple thousands with all the GNU stuff and Cygwin files buried in there But we luckily don t have to worry about much of it we just want to update the LIBRARIES directory with the Chameleon packages so we can build Chameleon compatible programs To do this go ahead and dive down into the HARDWARE directory this is shown in Figure 15 45 108 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8
346. n void Clears the VT100 terminal with ANSI code for clearscreen ee Fe 9 int getc void Receives a character thru interrupt buffer int UART_Receive int wait Waits for incoming character in receive buffer directly Init unsi int UART Shutdown void Shuts down the UART The following lists each function a description comments and example usage of the function Function Prototype int UART Init unsigned int baudrate Description _UART_Init initializes USARTO the primary USART connected to the SER serial port The 148 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit parameter is the baud rate in bits per second and should be one of the following values 1200 2400 4800 9600 19200 38400 57600 115200 If you send any other values then a mathematical computation is performed to estimate the baud rate register settings and its not very accurate Additionally the initialization function enables serial settings of N81 that is no parity 8 data bits 1 stop bit You must set your PC or serial device to the same settings as well Finally the initialization function enables the interrupt handlers which are hidden in the C source file This function must be called before any other API functions The function returns 1 always Example s Initialize the serial communication system to a baudrate of 115200 with setting N81
347. n your case you aren t going to distribute the processor with some embedded application on it so you want to disable all memory protection Referring to the figure make sure that the LB BLBO and BLB1 are all set to no lock on each category as shown in the figure Additionally make sure that all the checkboxes at the bottom left of the tab are all checked Finally go ahead and click Program to write the lockbits Again this should initiate the writing process and you should list a number of status operations scroll down the bottom of the window all with OK if everything was successful The word fuses is really a bit out of date Technically early microcontrollers had actual metal fuses inside of them that the user program could blow with high current to enable disable specific features But once blown the fuse couldn t be changed also referred to as OTP One Time Programmable These days fuses can typically be programmed over and over and aren t fuses at all but FLASH EEPROM memory locations However the word fuses is used a convention for historical reasons more or less to this day At this point the programming tool is all set up for the Chameleon AVR and our development needs Finally it s time to actually download the HEX file we previously generated and is waiting in the cham avr work Oft default folder on your hard drive Re select the Program tab in the tool and under the FLASH section click
348. nal Conditioning lt gt RESn R3 C16 10K USB_DTRn USB_RTSn 01uF Q1 2N3904 Reset Switch SW2 RESn SW MOM 2 The Chameleon AVR can be reset externally via a number of sources including the reset switch SW2 the ISP programming port as well as pressing as thru the DTR or RTS lines of the USB UART The reset circuitry on the AVR 29 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 328P and Propeller don t require much conditioning thus the manual reset circuit is nothing more than a switch and a pull up resistor as shown in Figure 3 1 Typically you will reset the system yourself via the reset button next to the AVR but the Propeller tool as well as the Arduino tool both use the serial port lines DTR to control the reset of the respective chips during programming 4 0 Atmel 6 Pin ISP Programming Port The Chameleon AVR has two different programming ports 6 pin ISP In System Programming port used to program the AVR chip directly USB UART used to program the AVR with bootloader as well as Propeller chip For more technical information on these ports and protocols please refer to these documents on the DVD DVD ROM CHAM AVR DOCS ISP JTAG ATAVRISPUserGuide pdf DVD ROM CHAM AVR DOCS ISP JTAG AVR JTAG ICE USER MANUAL DOC2475 pdf Let s discuss both programming ports and their relevance beginning with AVR s built in ISP port 4 1 AVR ISP Programming Port The ISP port is for p
349. nction Prototype int NTSC Color int col Description NTSC_Color sets the color of the text and background depending on driver The col parameter should be from 0 7 and selects one of a number of different foreground background color schemes for the characters printed This function has different behavior between the Default driver and the Default2 driver The Default2 driver is more for graphics and gaming and thus the idea is to control the color more directly with palette manipulation Returns 1 Example s Print the character X in all colors int index for 0 index lt 8 index NTSC_Color index NTSC Term Char X end for index 21 0 VGA Library Module Primer The basic premise of the Chameleon design is that it leverages drivers running on the Propeller chip to do all the media and graphics Thus whatever features the particular driver running on the Propeller side is the only features we can access via the AVR side That doesn t mean we can t abstract functionality and add higher level functions that build on the sub functions however this probably isn t productive since you will want to change drivers re write the Propeller driver and so forth Thus for the majority of the media drivers all the API functions do including the VGA is expose some of the base functionality in nice function calls so you don t have to send SPI messages yourself In the case of the enhanc
350. nd then launches the ASM SPI driver on Core 1 Driver Layer Each object running on its own core p To I O devices gt oo NR e gt Messages passed to drivers Each object running on via sub function calls another core 249 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Referring to the figure the client master processor issues commands over the SPI interface which the master control program running on the Propeller chip processes in a large message dispatching loop to the proper driver object Thus to add messages or functionality we have to consider the following things 1 Will the Propeller driver need another object or driver If so we need to add this and then add code to the main message dispatcher loop that passes messages from the client to the new Propeller object 2 If we add messages to the system we need to make sure they are unique and don t overlap any other messages Its good practice to not use message ids we have already used since you want to be as compatible as possible Both the Propeller driver cham default2 drv 112 spin and cham twi spi v010 h contain the master message id lists copies and the various library API files have functions that wrap the use of the messages in higher level functions 3 There are three classes of messages we can add Class 1 Same object more functionality There is already a driver for the messages the driver
351. ne system you learn them both more or less The Chameleon s were designed to be application boards to solve real world problems that you might have day to day in your designs engineering classes or work The Chameleons philosophy is to be very powerful but very simple have always been very interested in graphics and media processing however its is very hard to get a simple embedded system or development board to output NTSC PAL VGA etc Thus set out to design something that wasn t a development or educational kit like our other products but was something you just use to solve problems that is also good at displaying information and interfacing to user input devices Nonetheless wanted the Chameleons to be able to do graphics produce sound interface to keyboards and mice and be as small as a credit card There are a number of approaches to this design but with multiprocessing and multicore so popular thought it would be interesting to use both concepts in a product The Chameleon is the culmination of these ideas To create a product that with very little coding you could output NTSC PAL graphics VGA graphics read keyboards and mice as well as communicate with serial ports and perform digital and analog I O The selection of the processors was difficult as it always is We have to balance price performance user base flexibility and a number of other factors Additionally since the Chameleon is a dual processor de
352. ng Example s Print out Hello World UART Print String Hello world Function Prototype void UART Print Int int num Description UART Print Int takes a signed decimal integer and prints it to the UART Returns nothing Example s Print the powers of 2 from 1 to 256 int pow2 1 lt 256 150 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit UART_Print_Int pow2 UART Newline pow2 2 end while Function Prototype void Terminal Clear Screen void Description Terminal Clear Screen simply uses VT100 codes to clear the screen If you are communicating with a terminal program that has VT100 emulation calling this function will clear the screen and place the cursor at the top left of the screen Example s Clear the screen and print my favorite computer Terminal Clear 5 UART Print String Atari 800 Function Prototype int UART_getc void Description _UART_getc retrieves the next character from the circular reception buffer Returns the next character in the buffer or 1 if buffer is empty Example s Echo each character that is received forever get next character ch UART_getc was there a character if ch 1 UART putc ch end while Function Prototype int UART Receive int wait Description UART R
353. ng or integration device A PWM signal is at fixed output frequency usually many times the highest frequency you want to synthesis for example a good rule of thumb is that the PWM signal should be 10 100x greater than the frequencies you want to synthesis Also the PWM period is fixed the modulation of information in the PWM signal is in the duty cycle of the signal Recall duty cycle is defined as Duty Cycle Time Waveform is HIGH Total Period of Waveform For example say we had a 1KHz signal this means the period is 1 1KHz 1mS 1000 us Now let s say we are talking about square waves in a digital system with a HIGH of 5V and a LOW of OV Furthermore let s say that the duty cycle is 20 what would the final waveform look like Figure 9 4 a depicts this As you can see the waveform is HIGH 20 of the total period or 200 us and the waveform is LOW 800 us Therefore if you were to average this signal f t over time you would find that the average is simply the area under the HIGH part divided by the total AREA of the waveform which IS Average Signal 20 duty cycle 5V 200 us 1000 1 00V This is a VERY interesting result by just varying the time we pulse a digital output HIGH we can create an analog voltage Thus we can modulate the analog voltage in any shape we wish to create a final waveform of any shape we want sounds explosions voices etc plus since this is all digital we can synthesis as m
354. ng on the Arduino editor creates projects in the form of Sketches these are nothing more than a primary file that you would refer to as you main file The file imports all your libraries via headers and a special directory structure that we will get to in a bit In any event you create a single sketch project then add include statements to it which then invokes the inclusion of all the libraries Now when you compile your program what happens is the GNU GCC C C compiler is called in the background from a command line The GCC compiler is also installed with the Arduino tool but you don t have to do any setup at all On Windows machines the GCC compiler actually runs in a Cygwin linux shell this is a system that allows you to run Linux programs in Windows you can learn about it below Again Cygwin is transparently installed and you don t have to worry about http www cygwin com So you edit your Sketch program in the Arduino editor you compile it with GCC under the hood then finally you need to download it to the Chameleon The Arduino tool calls another program AVRDude which does this and sends the binary image via the serial line with a special protocol agreed to between the bootloader and AVRDude And that s how it all works Now before we get into the Arduino tool installation a couple things to know The Arduino tool actually uses C C to program in its not some new language its not BASIC its straight up C C
355. ng the Chameleon AVR 8 Bit Tile Map and Playfield Size Now let s take a look at the specifics of this tile map engine Referring to Figure 22 1 the tile map starts off 32x24 displayed on the NTSC screen This is the physical resolution and never changes That is we can never display more than 32x24 tiles on the physical screen However the playfield can be much larger to facilitate scrolling or page flipping The engine supports horizontal tile pitches of 32 64 128 and 256 Thus horizontally the playfield can be quite large Vertically there are no power of 2 restraints so you can make the vertical pitch anything you want as long as you don t run out of memory The tile map itself starts at the declaration tile_maps make sure to take a look yourself in the driver portion of code and is controlled by changing the global variable tile_map_base_ptr_parm in the register interface The tile map represents what s on the screen physically and the entire playfield virtually which might be much larger than the physical screen of 32x24 The tile map pointer above points to the start of the tile map but how the tiles are interpreted that is how many per row is controlled by a register that controls the setup of the tile mode This variable in the driver is called tile_map_control_parm and controls a number of interesting things here s the initial default setup code for this variable on driver start up tile_map_control_parm
356. ng thru 8080 CMA instr Formally this is the ones complement lt cksum gt the sum of the data bytes only Toss any carry Considering the block format outlined above the downloader needs to check the checksum against the received data and can request a packet be resent if its not correct Also if packets are late etc the downloader can time out and the downloader can simply stop the transfer if it wishes thus the protocol is receiver driven Please review the web links above to get a better handle on this protocol Now the implementation we made was quick and dirty no checksum checking no timeouts etc it simply hopes that nothing goes wrong On the other hand its very easy to add things to the function to make it more robust we purposely wrote it this way so that you could understand the function and add to it if you wanted Implementing the complete X Modem protocol with all error handling cases makes the code look like spaghetti With that in mind here s the function itself that does the downloading XModem_Receive char file_buffer int buffer_size receives file from an xmodem sender standard XMODEM protocal as shown here http en wikipedia org wiki XMODEM http www techheap com communi cation modems xmodem htm 1 n function takes a pointer to the storage area of file along with the maximum size of the buffer if the file exceeds the buffer the funtion WILL read the file and
357. ngine with 40x30 characters max resolution limited scrolling no redefinition of characters Hopefully you can use the standard default2 driver which includes the more advanced graphics tile engine which supports game like applications But again the point is you can change the Propeller driver and re write it as you wish we simply give you a starting point to get going with So if you want to know what the driver supports you can always peek into the driver itself CHAM GFX DRV 001 TB 001 SPIN and to see the messages that are getting passed to it you always look into the CHAM DEFAULT2 DRV 112 SPIN driver itself With that in mind if you want to use the NTSC driver then you need the following files added to your project CHAM AVR NTSC DRV 010 Main C file source for NTSC module CHAM AVR 010 Header file for NTSC module 167 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit ARDUINO TIP 20 1 Sending Messages to the Propeller Directly Before we cover the itself let s take a look at how we would manually send a message to the Propeller chip and what these wrapper functions do This is the first time we are discussing this since the UART and SPI drivers run on the AVR side of things only so they are local libraries On the other hand the NTSC VGA Keyboard Mouse Sound and Propeller I O Port libraries all make calls over the SPI channel to the Propeller chip This
358. now send the command with a function call clear the NTSC screen this command takes no parameters thus send 0 0 for data bytes SPI Prop Send Cmd GFX_CMD_NTSC_CLS 0x00 0x00 Function Prototype 166 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit int SPI Prop Print String int device char string Description SPI Prop Print String is a legacy function that uses terminal NTSC VGA driver to print strings on the display Typically you will use the NTSC VGA API to print to the terminals but this was created as a quick and dirty function during testing you might find it useful The first parameter is the device you want to print on DEVICE NTSC or DEVICE and the second parameter is the ASCIIZ string you want printed Returns the last byte received from the SPI transmission of all the commands Example s Print Hello World on both the NTSC and VGA monitors SPI Prop Print String DEVICE NTSC Hello world SPI Prop Print String DEVICE VGA Hello world Note in this case we are directly using the SPI command function to send commands to the Propeller so you don t need the NTSC API source files 20 0 NTSC Library Module Primer The basic premise of the Chameleon design is that it leverages drivers running on the Propeller chip to do all the media and graphics Thus whatever features the particular driver running on the Propeller side is the only featu
359. now what the driver supports you can always peek into the driver itself CHAM GFX DRV 001 TB 001 and see the messages that are getting passed to it you always look into the CHAM DEFAULT2 DRV 112 SPIN driver itself With that in mind if you want to use the GFX NTSC driver then you need add both the base NTSC driver along with the GFX API as well to your project CHAM AVR DRV 010 Main C file source for NTSC module CHAM AVR VO010 h Header file for VGA module CHAM AVR GFX 010 Main C file source for GFX module CHAM AVR GFX DRV V010 h Header file for VGA module Arduino tool users you will use the Import Library command from the main menu to include CHAM AVR 010 as well as CHAM AVR GFX DRV 010 however all this really does is add the line of code include CHAM AVR NTSC 010 1 gt include CHAM AVR GFX VO010 h ARDUINO To your program which you can just do yourself The Arduino tool already knows where to look for other C C files since we copied them into the appropriate directories already thus for the Arduino tool simply add the header include manually or you can let the tool do it from the main menu Sketch Import Library The Arduino MAKE file is rather complex and knows how to add all the C C files we dumped into the library directory so there is little to do with the Arduino tool when accessing these libraries o
360. nsion headers where you can directly connect them to a TTL level serial device However in most cases the only serial device you need to connect to the Chameleon is the PC and thus the USB to serial connection suffices for most applications Setting up the Terminal Program If you are an expert at setting up serial terminals and connecting serial devices then you can skim this section but if you re not then follow along There are two parts to this demo physical connection from the Chameleon AVR s serial port to the PC s serial port Running a VT100 serial terminal program on the PC with settings N81 115 200 baud The first problem is fairly straightforward simply connect your Chameleon AVR to your PC with the mini USB serial cable The FTDI driver on the PC s side virtualizes the COM port so from the PC s point of view its just another serial port Once you have the physical connection made then the next step is to get a terminal program up and running on your PC There are literally dozens if not hundreds of serial communications programs that you can find on internet 9996 of them are free for a reason they are junk There are a few that are actually very good such as PuTTY http www chiark greenend org uk sgtatham putty Zoc http www emtec com zoc 233 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Absolute Telnet http www celestialsoftware net telnet You can also fin
361. o World Hello World Hello World Hello World ello World Hell dm 1 o 1 2 5 amp Ep O wb lb xL EE O m e 5 0 0 LI Ep TIGE deb x Le HO H 5 1 boL HO HN Q7ro z LI Oo aJo wO ux 0 of 9 px Ld lub x O Compiling and Running the AVRStudio Version Demo Version Description Prints Hello World to both NTSC and VGA displays Main Source File CHAM AVR NTSC PRINT DEMO 01 Additional Files Required CHAM AVR SYSTEM VO010 c h CHAM AVR TWI SPI VO010 c h CHAM AVR VO010 c h CHAM AVR VO010 c h General Requirements NTSC port connect to NTSC TV monitor and VGA port connected to VGA monitor Controls Required None Compiling and Running the Arduino Version Demo Version Description Prints Hello World to both NTSC and VGA displays Main Sketch Source File CHAM AVR NTSC VGA PRINT DEMO Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR TWI SPI 010 CHAM AVR VGA V010 CHAM AVR 010 General Requirements NTSC port connect to NTSC TV monitor and VGA port connected to VGA monitor 219 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit
362. o change cursor Compiling Running the AVRStudio Version Demo Version Description Draws on the screen with the mouse using ASCII art Main Source File CHAM_AVR_MOUSE_DEMO_01 C Additional Files Required CHAM AVR SYSTEM V010 c h CHAM AVR TWI SPI VO10 c h CHAM AVR NTSC 010 CHAM AVR VGA V010 c h CHAM AVR MOUSE V010 h General Requirements Video ports connected to NTSC or VGA monitors Controls Required PS 2 mouse plugged into Chameleon draw ASCII art with the mouse Left button to clear the screen right button to cycle thru different drawing characters 228 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Compiling and Running the Arduino Version Demo Version Description Draws on the screen with the mouse using ASCII art Main Sketch Source File CHAM_AVR_MOUSE_DEMO Additional Library Files Required imported automatically by sketch CHAM_AVR_SYSTEM_V010 CHAM_AVR_TWI_SPI_DRV_V010 CHAM_AVR_NTSC_DRV_V010 CHAM_AVR_VGA_DRV_V010 CHAM_AVR_MOUSE_DRV_V010 General Requirements Video ports connected to NTSC or VGA monitors Controls Required PS 2 mouse plugged into Chameleon draw ASCII art with the mouse Left button to clear the screen right button to cycle thru different drawing characters Technical Overview This demo uses the Mouse_Read API call to read the state of the mouse it uses this to allow you to draw on the NTSC VGA screen with
363. o go into the source files where printf is located and modify it to do something intelligent on the Chameleon AVR such as print to the UART or to the NTSC VGA screen But you get the idea Don t use standard C functions that make no sense on an embedded system Next embedded systems have multiple memory types RAM FLASH EEPROM And the AVR Libc library knows this Thus many functions only work in RAM or FLASH specifically Therefore you always have to keep in mind that you are working with a Harvard memory architecture and a separate RAM FLASH memory model The AVR Libc documentation has a lot to say about this subject so make sure to read it Alright so that s the story with AVR libc it s part of the GNU GCC WinAVR installation and when you build a C C application functions are pulled in from this library To give you an idea of what Libc supports Table 17 2 lists the header files you can include in your Chameleon AVR applications and what functionality they support Table 17 2 AVR Libc library functionality listed by header file Libc Header File Description General C C Library Functions ee a T lt alloca h gt Allocate space in the stack lt assert h gt Diagnostics lt ctype h gt Character Operations lt errno h gt System Errors lt inttypes h gt Integer Type conversions lt math h gt Mathematics lt setjmp h gt Non local goto lt stdint h gt Standard Integer Types lt stdio h gt Standard I O faciliti
364. o is actually copy the pre made Sketches into your local sketch directory so you don t have to build each sketch yourself Copying the Sketches from DVD To save you time for each demo construction have pre built a sketch for each demo In essence took the program as developed it in AVRStudio then create a sketch with the same root name then saved it Of course performed any porting operations like changing header include syntax changing main to loop etc But more or less just a couple minutes each to port each program in most cases All the ported sketches are located on the DVD here DVD ROM CHAM AVR TOOLS ARDUINO SKETCHES Simply copy the contents of this directory which contains a number of sub directories each representing a sketch into your local hard drive where you installed the Arduino tool and its Sketches directory After copying re start the Arduino tool to make sure they are scanned Now you are ready to go for the Arduino versions as well 27 1 3 Setting the Chameleon Hardware Up Finally let s take a brief moment to remind ourselves what s going on with the hardware If you are using AVRStudio then you are going to build a project for each demo or change a single project re build and FLASH the file to the Chameleon AVR with the AVR ISP MKII programmer If you don t own a programmer then you will use the Chameleon in Arduino mode and thus you need the bootlooder on the Chameleon which we d
365. o running Crate it The Chameleon AVR 8 bit is pre loaded with a demo programmed into the AVR s FLASH memory a screen shot is shown in Figure 1 3 that illustrates images of both the NTSC and VGA monitors during the demo We will use this to test your system out The following are a series of steps to try the demo out and make sure your hardware is working IMPORTANT c First Things First Before we plug the Chameleon in and test it a couple things to pay attention to First the Chameleon can be powered by either a 9V DC adapter or draw power from the USB port connection If you have a 9V DC adapter then you can use it for power However to talk to the Chameleon you are going to need a mini B USB cable no matter what Therefore when we get to the power setup in Step 3 you can either plug in both the 9V adapter and the USB cable or just the USB cable If you plug in the USB port cable then the PC will detect a new USB device and if you have Windows SP 2 3 then it should install the FTDI drivers itself If it doesn t its alright we will perform driver installation later during the software installation phase Point is the moment you plug the Chameleon into the Windows PC plug and play is going to detect the new USB device of the serial UART built into the Chameleon so don t panic Step 1 Place your Chameleon AVR on a flat surface no carpet Static electricity Step 2 Make sure the power switch at the front is in the
366. o the Chameleon once we have the FLASH demo loaded To do this you simply click the lighting bolt or connection icon on the Absolute Telnet interface Then once we want to initiate the X Modem transfer you are going to access the main menu and access the Transfer Send XModem gt menu item as shown in Figure 31 5 below select a file and download to the Chameleon But we are getting ahead of ourselves right now Just remember this process and keep it in the back of your mind lets switch gears to setting up the demo on the Chameleon and getting that ready to receive files 244 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Intitlec 1 fied soluteTelnet ISTERED 0 e ul A Fie Edit Options Help D E BUY NOW Courier New 12 v c Receive gt xModem crc SFTP xModem 1k zModem to find out what s in the latest version Connected COMS4 screen 80x24 cursor 1x1 xterm Compiling and Running the Demo s There are two demos in this group the AVRStudio version and the Arduino version They are nearly identical except that for the AVRStudio version has been ported to work on the Arduino with the usually porting tactics discussed previously in the manual The main file that we introduce to access the FLASH API is CHAM_AVR_FLASH_DRV_V010 C H Once you compile and FLASH the Chameleon with the demo it displays
367. o the P itself as shown in Figure C and the 2x5 header cable from the AVR ISP programmer is plugged into the Chameleon AVR 15 35 99 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 35 Plugging the AVR ISP into the Chameleon AVR properly When you are ready to go the Chameleon AVR is connected to the AVR ISP and powered up Go ahead and plug in the 9V DC power supply or make sure the USB cable is plugged into your PC then turn the unit on by sliding the power switch to the left Now hold your breath and click lt Connect gt If all goes well AVR Studio will start sending communication packets to the AVR ISP which in turn will communicate with the ISP port on the Chameleon AVR and talk to the chip querying it If a communications channel is successfully opened then the AVR ISP control panel will open up as shown in Figure 15 36 Figure 15 36 The AVR ISP control panel s Main tab AVRISP in ISP mode with ATMega328P Man rogram Fuses LockBits Advanced Hw Settings Hw Info Auto Device and Signature Bytes ATMega328P Md Erase Device x1E 0x95 Read Signature Signature matches selected device Target Settings Programming Mode and T arget Settings ISP ISP mode z ISP Freq 125 0kHz Attainable 125 0 kHz ISP Frequency 125 0 kHz Note The ISP frequency must be less than 1 4 of the target Getting isp parameter 50 0
368. oad simply loads the keyboard driver into a core on the Propeller If a keyboard driver is already running this function will have no effect Returns 1 Example s Start the keyboard driver Keyboard Load Function Prototype int Keyboard GotKey void Description Keyboard GotKey tests if a key is available for reading returns 1 key ready 0 no key ready Example s Testif a key has been pressed 199 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit if Keyboard_GotKey 1 do something end if Function Prototype int Keyboard_Key void Description reads the next keycode out of the keyboard buffer returns 0 if no key is available Example s Read the key out of the queue and do something if Keyboard_GotKeyQ read key key Keyboard_Key do something with hey end if key ready Function Prototype int Keyboard_State int key Description _Keyboard_State tests if keycode key is depressed 1 or released 0 and returns the values Example s Test if right arrow is down test for scancode right arrow if Keyboard state 1 6 do something end if 25 0 Mouse Library Module Primer The basic premise of the Chameleon design is that it leverages drivers running on the Propeller chip to do all the media and graphics Thus whatever features the par
369. oat memcpy input buff 4 Quy sizeof float memcpy input buffe 4 Quz sizeof float memcpy input buff 4 sizeof float memcpy input buffe 4 vy sizeof float memcpy RPC_input_buff 4 vz sizeof float d finally a call would be made to the RPC interface RPC Interface DotProduct RPC input buff RPC output buff Now that the parameters are packed into a single data structure we simply call the RPC interface and pass the starting address of the structure The RPC interface in this case takes a string as the function name and then two pointers one to the input parameters and one to where the output results are stored There is obviously and agreement and set of conventions between the caller and receiver on this function and how it works so the client can make RPC calls and the server can respond to them In this case the server or other process reads the first string determines the RPC function then calls a handler with the two pointers It s up to the handler to know how to unpack the parameters and generate the results via calling the local function Thus RPC calls necessitate a number of extra steps including RPC Steps 1 Encoding 2 Transport to server 3 Decoding 4 Execution 5 Encoding 6 Transport back to client Obviously not the fastest thing in the world however if the computation workload is 2x or more than all the interface
370. ock by block and you probably will need to Option 2 lists out the first 1K of the FLASH memory so you can see what s in it Point being you want to boot the program see what s in the FLASH it then download something see if it changes reset re boot try again And example of Option 2 running is shown in Figure 31 8 below Figure 31 8 The FLASH demo displaying a file 1 XModem receive to FLRSH 2 Dump FLASH to screen Selection 1 2 Opening FLASH memory Reading data from FLASH The Road Not Taken by Robert Fro st Two roads diverged in a yellow wood And sorry I could not travel bo th And be one travel Thus the usual order of operations will be to boot the Chameleon with the FLASH demo then you might hit Option 2 to see what s in the FLASH s first 1K of memory Then you might decide to overwrite it with something so you go to your PC set up the X Modem download start the file transfer and the PC program will wait Then you go back to the Chameleon s local keyboard and press Option 1 then you will see a 3 second countdown and the program will start downloading as it downloads you will see the test stream across the screen Finally have created a few files for you to download with X Modem that have short famous poems all located in the Source directory here DVD ROM CHAM_AVR SOURCE The Road Not Taken by Robert Frost xmodem test file road not taken txt O Captain My Capt
371. oes 86 15 14 4 Setting up the Project Options 89 Map File Example 12 22 ated pee toco pd oe Pee te Ades oe pea pe ee pepe deo RO A Qa ere sede 91 ListsPile Example 1 y o tea easel 91 Hex File Example e set oot Must d oe deest 92 1531 4 2 Adding Files to th Project hiess iieo eoe oe ete Doa ote perta 94 15 1 5 Setting up the AVR ISP Hardware eres eese eene eene nennen netta stets sse setas en sse sna seno 98 15 1 7 Final Words on AVR Studio Tool Chain Installation e atten sse tn ases sess seen seen ao 105 15 2 ARDUINO TOOLCHAIN SETUP iiia nina ndun o dun dank ada n Eu ua iav wb axis dura Ear a ya RR raga ddr 105 15 2 1 Installing the Arduino Toolchain in Windows cesse eese eese eese eene tense tense tensa senate tasse tease tense tensa esos sess sesenta sse tnse 106 15 2 2 Copying the Files to Your Hard Drive sten sse sse en stets sess ses en sse enao 107 15 2 3 Preparation to Launch the Arduino Tool for the First Time eee eese eene setas etate tentes 110 15 2 31 Installing a Serial Terminal 5
372. om file font file c64 font 05 16b bmp followed by 16 blanks for user definition of course you can overwrite these as well with direct memory access if you wish to The font file was hand made and based on the Commodore 64 and Atari 800 fonts as well as some extra characters for fun The font file is located on the CD here DVD ROM CHAM AVR TOOLS GRAPHICS c64 font 05 16b bmp Figure 22 2 shows a screen shot of the font file for reference 177 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Tile Bitmap Format Figure 22 2 the tile engine font I added a couple Space Invaders at the end for fun z E M d c ou QGABCDEEFGHITK MNOPORSTUUHXYZES 1 abcde f TS DVD ROM CHAM_AVR TOOLS GRAPHICS BMP2SPIN EXE The tool takes as an input a BMP file and outputs SPIN compatible data statements Read the C source file for the control parameters and to understand how it works For example the output of the tool for the character looks like this Extracted from file c64_font_05_16b bmp at tile 1 0 size 8 8 palette index 1 c64_font_05__tx1_ty0_bitmap WORD 26961 WORD 25631 1 12 2 11 1 WORD 275631 1 12 2 11 1 WORD 206601 1 12 2 11 1 WORD 205601 1 12 2 11 1 WORD 221 1 11 11 11 WORD 1_1 11 11 11 WORD 205601 1 12 2 11 1 WORD 221 1 11 11 11 The tool outputs a text line description of the location and file where the tile was extracted
373. on for the mouse are 60 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit STREAM Mode In stream mode the mouse sends movement data when it detects movement or a change in state of one or more mouse buttons The rate at which this data reporting occurs is the sample rate defaults to 100 samples sec on Reset This parameter can range from 10 to 200 samples sec on most drivers The default sample rate value is 100 samples sec but the host may change that value by using the Set Sample Rate command Stream mode is the default mode of operation following reset REMOTE Mode In this mode the mouse reads its inputs and updates its counters flags at the current sample rate but it does not automatically send data packets when movement occurs rather the host must poll the mouse using the Read Data command Upon receiving this command the mouse sends back a single movement data packet and resets its movement counters WRAP Mode This is an echoing mode in which every byte received by the mouse is sent back to the host Even if the byte represents a valid command the mouse will not respond to that command it will only echo that byte back to the host There are two exceptions to this the Reset command and Reset Wrap Mode command this is obviously the only way to get the mouse back out of the Wrap mode The mouse treats these as valid commands and does not echo them back to the host Thus Wrap mode is a good diagnostic
374. on then return back to this point This way you have an idea of what s coming If you make mistakes during the setup process they are easy to fix if you know you made them but very hard if you don t Thus take a few moments to skim the screen shots then return here and we set things up for real Alright we are going to approach all development with the Chameleon AVR is as simple as possible To that end we need to create a single project to work with then for each demo we will simply include the source files in the source tree that the demo needs and remove ones it doesn t This way we don t have dozens of projects hundreds of directories and a big mess The primary steps that we must follow are Create an initial project and directory within the AVR installation directory Set up the GCC tool chain properly the compiler linker etc Set up the AVR ISP programmer itself if you have one Copy all the source files from the DVD with all the demos and drivers into the Source directory locally on your hard drive Let s begin by launching AVR Studio 4 You should have an icon on your Desktop or link in the Start Menu locate AVR Studio 4 and launch it You should see something like the image depicted in Figure 15 18 Figure 15 18 AVR Studio starting up for the first time AVR Studio File Project Build Edit View Tools Debug Window Help amp 343 7m049 44 PtH d o Tra
375. ons dialog from the Main Menu via the lt Project Configuration Options gt as shown in Figure 15 23 below Figure 15 23 Locating the Configuration Options dialog i 2 Project Wizard New Project Open Project AYR Gt Save Projec e Close Project x Once you launch the tool then you should see the very complex interface shown in Figure 15 24 below Figure 15 24 The Project Options tool which sets up the entire tool chain cham_avr_work_01 Project Options Directories is Libraries Active Configuration defaut Edit Configurations Use External Makefile 1 Target name must equal project name 2 Clean rebuild support requires clean target 3 Makefile and target must exist in the same folder Output File Name cham avr work 01 elf Output File Directory default Exi Device atmega328p E Unsigned Chars funsigned char 15000000 ie Unsigned Bitfields funsigned bitfields Pack Structure Members pack struct Optimization os Short Enums fshort enums Create Hex File Generate Map File Generate List File 89 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit This is the most important tool of the entire application It s here that everything is configured If the settings are not correct here you will have nothing but
376. ons these are macro level functions that can fill and copy memory 8 16 bits at a time If you take a look at the listing above at the very top you will see the processing of GPU sub functions First we use the SPI command itself to identify a GPU function the register messages are GPU GFX SUBFUNC STATUS R and GPU GFX SUBFUNC STATUS W The or read message currently does nothing but the W or write message executes the GPU command which there are currently 4 of as shown in the header code below extract API subfunction and data GPU GFX subfunc g datal6 amp FF lower 8 bits defines sub function GPU GFX data g datal6 gt gt 8 upper 8 bits defines data for sub function case GFX subfunc 183 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit GPU_GFX_SUBFUNC_COPYMEM16 0 Copies numbytes from src gt dest in wordsize chunks wordmove tile_dest_addr_parm tile_src_addr_parm tile_numbytes_parm GPU_GFX_SUBFUNC_FILLMEM16 1 Fills memory with 16 2 bytes at a time wordfill tile dest addr parm tile datal6 parm tile numbytes parm gt gt 1 GPU GFX SUBFUNC COPYMEM8 2 Copies numbytes from src gt dest in byte size chunks bytemove tile dest addr parm tile src addr parm tile numbytes gt gt 1 GPU GFX SUBFUNC FILLMEM8 3 Fills memory with low byte of data16 1 bytes at a time bytefill tile dest addr parm tile datal6 parm amp
377. ons lower 4 bits 0 15 default 0 And that s about it for defines let s move on to the API roadmap The listing for the SPI and module CHAM TWI SPI V010 c supports a thin wrapper layer over the hardware functionality The SPI API is more developed since the 12 tends to have a lot state in it functions have to return with errors and other information hence you will probably want to write your own functions in the future Nonetheless have used the thin wrapper to show how to control an peripheral a digital potentiometer which we will cover in the Mechatronics section for reference So the functions work but you have to call them at a fairly low level Table 19 3 below lists the SPI and API functions categorized by functionality 160 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 19 3 SPI and module API functions listing Function Name Description ee TWI 12 related functions char TWI_Action unsigned char command Sends an action to the TWI hardware een ote ee ee ed SPI related functions re ce ee MEME int SPI Init unsigned char spi rate Initializes the primary SPI unit connected to SD SPI command function to communicate with Propeller aE eg ee Ss es te ee long SPI Prop Send Cmd int cmd int data int status Sends a 3 byte command packet to Propeller int SPI Prop Print St
378. ontains the master schematic of the Chameleon AVR 8 Bit and all its sub systems 257 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 6652992215 191 6950992215 2181 X1 ugsny 9ue1392J PZZ OTT SHONN SANN day uoojoureu 258 ET orama von CENE se sauer ven qo Ej HOT ose Ves HSV14 IdS INS a MS oraa von lt Ta 34 5 1 5 onaianedwios 5 5 ENY PERS Vosa Q naou 8 _ 2 SIBEB 22225 3933 3333958 O INO 4 585 60000 9 i LINY bed t euiung BPI OSLN x lt gt tia Ej ES Es a lt si E m ES t lt ES 6 ta 29114 MOT IPN Ae I on S E asn dues D EE as um E gu Q vere asn asuvas zi 097 Bngeq snes oe y 185 1 EMS lt 38 a E
379. ors Main Source File CHAM_AVR_NTSC_GLOW_DEMO_01 C Additional Files Required CHAM AVR SYSTEM VO010 c h CHAM AVR TWI SPI VO010 c h CHAM AVR VO010 c h CHAM AVR GFX VO010 c h General Requirements Video port connected to NTSC TV monitor Controls Required None Compiling and Running the Arduino Version Demo Version Description NTSC version animates overscan colors Main Sketch Source File CHAM AVR NTSC GLOW DEMO 01 Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR TWI SPI 010 213 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit CHAM_AVR_NTSC_DRV_V010 CHAM_AVR_GFX_DRV_V010 General Requirements Video port connected to NTSC TV monitor Controls Required None Technical Overview The demo simply uses the NTSC GFX to animate the top and bottom overscan colors this is only supported with the default2 version of the driver and the NTSC system Below is an excerpt of the code from the main while loop that performs the animation enter infinite loop glowing the top and bottom overscan tile engine functions required for this ud glow thru every color every brightness for col 0 col lt 15 col 2 bright lt 6 bright build up Propeller compatible color chroma 4 chroma bit 1 luma 3 color col lt lt 4 0b00001000 bright set top ove
380. otype unsigned int GFX Read Tilemap Ptr void Description GFX Read Tilemap Ptr reads the 16 bit pointer that points to the current tile map data displayed Each tile map entry is 2 bytes palette index character index and the current tile map width decides the pitch per row The tile map pointer is of course relative to the Propeller s 32K memory space and an absolute address Returns the 16 bit pointer value address Example s X Read the tile map pointer unsigned int tilemap ptr tilemap ptr GFX Read Tilemap Ptr Function Prototype unsigned int GFX Write Tilemap Ptr unsigned int ptr Description GFX Write Tilemap writes the 16 bit tilemap pointer that points to the current tile map data displayed Each tile map entry is 2 bytes palette index character index and the current tile map width decides the pitch The pointer must be a valid address and within open memory or part of memory declared for the driver itself otherwise you could crash the Propeller so watch out Scrolling page flipping and other memory effects can be achieved by changing the pointer For example say you want to scroll the tilemap one row down Assuming the current tilemap is 32x24 then we know there are 32 tiles per row and each tile is 2 bytes thus 64 bytes per row Therefore to scroll down a single row we simply need to add 64 to the current tile map pointer The example that follows will show t
381. ou could do the same with your transmission software and write a loop that constantly writes bytes to the transmit buffer while waiting for the bytes to transmit before writing another These methods are fine but wanted to give you a little bit more to work with as a starting point so you can see how you might develop a more robust serial communications system Referring to Figure 18 1 this is the architecture of the UART module we have developed The UART driver API is an interrupt driven system with circular buffers on both the incoming and outgoing characters The system is easy to understand from a design perspective interrupts are setup to fire when both a character has been received and when a character has been transmitted These interrupts both call interrupt service routines ISRs that have been developed to support circular buffers These circular buffers allow the calling functions to place characters in the outgoing buffer and queued for transmission as well as for characters to fill up the receiving circular buffer until the caller wants to read characters The idea of this being the functions that transmit and receive characters do not have to wait they make to functions that interrogate the circular buffers and either insert or remove characters This way the system is responsive and only if the buffers are overflowed is data lost For example say you want to transmit the string Hello World Normally you would have to transmit
382. our programs we just rename to loop and then add another function called setup which can be empty Setup is simply called first for all Arduino programs then the loop function is called just like main and the program stays in there 2 The Chameleon under AVRStudio has a number of libraries One of them that is redundant is the serial UART library We had to write one for the AVRStudio version but the Arduino has a serial library of its own So you will notice that a lot of the programs that use serial comment out the include file for the Chameleon serial library and we just use the Arduino built in serial library which is a C class 3 When including headers with AVRStudio its typically setup to look in the local directories for the headers so you put quotes header h around the header names Whereas the Arduino tool makes your headers part of its libraries so you use angled brackets lt header h gt That s really about it It takes less that 5 mins to port most Chameleon programs to Arduino mode and vice versa Of course we have done this for you for all the demos that follow to get you started So the question is which mode to use Arduino or AVRStudio Well depends on what you are doing and what you have If you do not own a AVR ISP MK II programmer then the decision is made for you you probably have to use Arduino mode But if you do have the programmer or something else supported by AVRStudio then you prob
383. ous open source drivers for SD cards and FAT16 so you are free to use them in your development For example the Procyon AVR Library that has FAT16 support but for read only Simple google a bit and you can find other libraries or write one yourself Mechatronics N A Some modules like the SPI and are actually in the same source file since they are NOTE so similar These compose the main library modules that make up the Chameleon AVR specific API functions mostly wrapper functions Now before we continue want to make a point about language here have been using the word library in a cavalier way Library as is relates to C C programming is a pre compiled container with many binary objects For example AVR Libc is a library hundreds of functions have been compiled into a single library file and that single file is linked against during builds with GNC GCC In our case we could have built an official library and put all the source 141 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit modules into it but this would be tedious since it would hide what you are including in each project Thus have decided to keep the library in a source format as a collection of C and H files so we can see what s going on include what we need and when we update one of the source files we don t have to rebuild the library we simply include the source file in the source tree with our main project file
384. ouse responds with acknowledge FA then enables 1 1 scaling default Lastly the only commands the standard PS 2 mouse will send to the host are the Resend FE and Error FC They both work the same as they do as host to device commands Other than that the mouse simply sends 3 byte data motion packets in most cases before sending any other commands This way the mouse won t keep trying to send the mouse is in Stream mode the host should disable data reporting command F5 N packets back while the host is trying to communicate with the mouse 62 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 12 2 5 Mouse Initialization During the mouse power up both the DATA and CLOCK lines must be pulled HIGH and or released tristated by the host The mouse will then run its power up self test or BAT and start sending the results to the host The host watches the CLOCK and DATA lines to determine when this transmission occurs and should look for the code AA ok followed by 00 mouse device ID However you can forgo this step if you like and just wait 1 2 seconds and assume the mouse was plugged in properly You do not have to respond to this code in other words If you wish to Reset the mouse you can at any time send the command code FF and the mouse should respond with a FA to acknowledge that everything went well Once the mouse sends the AA 00 startup codes then the mouse enters its
385. p amp 1 AVR Prog AVR GCC 1 50 Upgrade Sy Other Files cham avr work 01 default Sy Source Files JTAGICE mkII Upgrade Pur TUNE MIENE c CHAM AVR HELLO WORLD 0 AVR ONE Upgrade CHAM AVR NTSC DRV V010 CHAM AVR SYSTEM V010 c AVRISP Upgrade CHAM AVR TWI SPI DRV AVR Dragon Upgrade IE CHAM_AVR_VGA_DRV_VO10 c 6 0 Upgrade st Modified 9 22 09 15 42 Header Files External Dependencies Plug in Manager ICESO Selftest Networks LLC 2669 ilename CHAM_AUR HELLO UORLD 81 C riginal Author Andre Lahothe ast E CHAM_AVR_NTSC_DR _vo10 Customize escripti NTSC UGA demo of Hello World E CHAM AVR SYSTEM VO10 h Eu Options 3 eN lt H Fn tho 4 CHAM AVR TWI SPI DRV VO veruieu Simply prints out Hello World to the NTSC and UG E CHAM AVR YGA VO10 h Show Key Assignments 8 Program AVR m Connect Flip 3 3 2 Auto Connect AVR Wireless Studio Write Flash AVR Battery Studio g Write EEPROM AVR QTouch Studio e Read EEPROM Mile 1110 Start Auto 1722 EEE PEE _ __AUR_ATmegal168 __ 28 __ include everyt lt stdint h gt lt stdio h gt lt stdlib h gt lt string h gt lt ctype h gt lt aur eeprom h gt lt aur io h gt
386. p against an immovable object they can get stuck and you are out of luck These types of games are very easy to develop but hard to play You have to really think about what order you move blocks and you have to be weary about getting stuck This version requires an NTSC monitor and the local PS 2 keyboard plugged in Also make sure to have the audio port connected to your TV there is sound To play simply move the character with the arrow keys and push the blocks around The first level has the blocks on the left side and their resting positions on the right side so you have to push the moveable blocks from the left side to the right side without getting stuck or putting yourself in a corner The first level has 6 blocks that must be moved This concludes the Quick Start demo 17 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 1 4 The Atmel Mega AVR 328P packing for 28 Pin TQFP and PDIP packages PCINT19 OC2B INT1 PCINT20 XCK TO PD4 PCINT6 XTAL1 TOSC1 PB6 PCINT7 XTAL2 TOSC2 PB7 Top View RXD PCINT16 INTO PCINT 18 TXD PCINT17 31 1 PD1 30 1 2917 PC6 28 J 5 27 4 26 PCINT21 OCOB T1 PD5 O 9 O PCINT23 AIN1 PD7 11 PCINT22 OCOA AINO 10 RESET PCINT14 12 ADC5 SCL PCINT13 PB1 13 ADC4 SDA PCINT12 ADC3 PCINT 11 PB2 0 14
387. peller doing all the work Something that might be fun to do is add a bitmap NTSC or VGA driver to the master Propeller driver and then create a true paint program that allows pixel level painting filling etc and create something like the famous DPaint that we used to use to make games in the 80 s and 90 s 31 1 Serial FLASH and Port I O Device Demos The next group of demos illustrate the Serial port FLASH memory and Propeller Port functionality As usual the demos try to do something graphical so they always support NTSC output and some might support VGA output as well But they all usually use nothing more than text terminal graphics so added VGA support is a couple lines of code The examples typically consist of the primary source file for the demo as well as The System API library module CHAM AVR SYSTEM V010 c h The main SPI API library module CHAM AVR TWI SPI VO010 c h The serial API library module CHAM UART DRV V010 c h The FLASH API library module CHAM FLASH DRV V010 c h The Propeller local 8 bit port API library module CHAM PROP PORT DRV VO10 c h The NTSC VGA GFX driver or all of them And any other ancillary drivers keyboard mouse etc All the required files can of course be found in the Source directory on the DVD which you should have already copied onto your hard drive located here DVD ROM CHAM AVR SOURCE AVRStudio TIP The Arduino version will be in Sk
388. position X follows 0B set Y position Y follows 0c set color color follows 0D return anything else prints the character to terminal gfx ntsc Out Term g data The yellow highlighted code is in the Default2 SPI message dispatcher as you can see this highlighted section catches all the graphics function calls messages and pipes them to yet another function call inside CHAM GFX DRV 001 TB 001 SPIN which is the actual graphics driver Now let s take a quick peek into that PUB GPU GFX Process command g cmd g datal6 spi result this function can be called with parameters to execute various commands to the register model of the GPU the SPI client running on the control COG with the virtual SPI interface will typically catch the GPU command and then pass it along here for effiecient processing BEGIN REGISTER INTERFACE CAS HEIL HL M M L process command with proper handler case g cmd PU 5 5 5 GPU_GFX_SUBFUNC_STATUS_R Reads the status of the GPU OR Writes the GPU Sub Function register and issues a high level command like copy fill etc GPU_GFX_SUBFUNC_STATUS_W extract API subfunction and data GPU_GFX_subfunc g datal6 amp FF lower 8 bits defines sub function GPU_GFX_data g_datal6 gt gt 8 upper 8 bits defines data for sub function case GPU
389. powerful support functions to save you time Let s take some time to briefly discuss the overall architecture of the system so you know how it s all put together This will help understand how the API functions fit together and the data flow of the system Figure 28 1 The system architecture of the UART driver UART Hardware Module Receive Transmit Transmitter Circular Buffer Head Tail Transmitter ISR Physical Serial Port TX RX Hopefully you have read thru the application notes and data sheet on the AVR USARTS Nonetheless serial communications at the PC level is usually quite easy The PC has an API hardware interrupts and lots of sub systems 146 Reciever Circular Buffer putchar Head Tail Receiver getchar ISR 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit so that you are insulted from what s really going on This is not true with microcontrollers The AVR 328p series has hardware USARTs we are using for UARTs to take the load off the bit banging polling and transmission and reception of actual bytes but we still need to write a lot of software on top of the hardware to develop an API that is useful There are lots of ways to approach this for example if you are happy with waiting for characters you could write a receive function that simply waits for the reception buffer to get a character this is slow though since you have to poll for it Secondly y
390. queue up key presses for you For the keyboard we decided to use a base driver from the original Propeller objects development that was designed to communicate to a standard PS 2 keyboard nothing fancy The same driver is used in both Default1 and Default2 so the same idea apply to either driver you load on the Propeller CHAM_DEFAULT1_DRV_112 SPIN or CHAM_DEFAULT2_DRV_112 SPIN The actual driver object used for the keyboard is keyboard_010 spin Basic PS 2 keyboard driver originally written by Parallax However only exposed a portion of its abilities thru the current SPI messages no need to waste messages You can always add more Therefore the abilities you see exposed in the following API are just a taste of what it can do In other words if you need more functions that the driver supports then you will have to add messages to the SPI driver and add them yourself With that in mind if you want to use the keyboard driver then you need the following files added to your project CHAM_AVR_KEYBOARD_DRV_V010 c Main C file source for Keyboard module CHAM_AVR_KEYBOARD_DRV_V010 h Header file for Keyboard module The Keyboard module header CHAM_KEYBOARD_DRV_V010 h has no defines or globals itself since it literally nothing more than wrapper functions that call thru to the Propeller side driver But its worth while to take a look at some of the constants in the actual Spin ASM code keyboard driver KEYBOARD_010 spin
391. r based ship is drawn Figure 28 6 shows the demo in action Figure 28 6 VGA terminal text graphics demo Star Field 220 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Compiling and Running the AVRStudio Version Demo Version Description Vertically scrolls a star field and draws a little ASCII character space ship Main Source File CHAM_AVR_VGA_STARS_DEMO_01 C Additional Files Required CHAM_AVR_SYSTEM_V010 c h CHAM AVR SPI DRV VO010 c h CHAM AVR DRV VO010 c h General Requirements VGA port connected to VGA monitor Controls Required None Compiling and Running the Arduino Version Demo Version Description Vertically scrolls a star field and draws a little ASCII character space ship Main Sketch Source File CHAM AVR VGA STARS DEMO Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR SPI DRV 010 CHAM AVR V010 General Requirements VGA port connected to VGA monitor Controls Required None Technical Overview Here s just the main loop excerpt which shows the entire star field generator int main void run over and over again int ship x 12 ship y 0 initialize and set SPI rate SPI Init SPI DEFAULT RATE give Prop a moment before sending it commands the boot process is about a second if you like you can speed it up by removing the
392. r data strings on the other end and see what s going on 16 3 2 Compressing RPC for More Bandwidth The whole idea of RPC technology is to use it thus you might have a program running that makes 100 local calls with 100 RPC calls every time thru the main loop Thus you want the RPC transport process to be very quick hence compression of the RPC data and or caching is in order For example if you are sending large chunks of text or data that has repeating symbols then its better to compress it locally transport it then de compress and execute since computers are typically 1000 s of times if not millions of times faster than the communications links Additionally advanced RPC systems might use the same data over and over Thus there is no need to keep sending the data to the server and a caching system should be employed where on the first RPC call the caller indicates that a data structure being passed is static and cacheable Thus the server caches it after its first use then on subsequent calls the client need not send the structure until it needs refreshing For example say you have a 3D data base that you want a RPC to perform calculations on The database never changes so no need to keep sending it over and over once its in the servers memory space you can save the bandwidth 16 3 3 Our Simplified RPC Strategy Considering all these interesting methods the method used for the Chameleon is a 3 byte binary encoded SPI packets with
393. r down by 16 bitmap tiles 16 16 256 bytes GFX Write Bitmap Ptr GFX Read Bitmap Ptr 256 Function Prototype int GFX Get VScroll void Description GFX Get VScroll returns the current fine vertical scroll value from 0 7 The tile engine supports smooth vertical scrolling via the vertical fine scroll register This function reads that register Example s Read the vertical scroll register int fine scroll fine scroll GFX Get Vscroll Function Prototype int GFX Set VScroll int vscroll Description GFX Set VScroll sets the vertical fine scroll register with the sent value vscroll 0 7 Use this function and register to control smooth scrolling Each tile is 8 pixels high thus you can scroll the tilemap up and down a single pixel at a time with this register call To perform continuous smooth scrolling first fine scroll 0 7 then reset to 0 and course scroll a single row Returns 1 Example s Fine scroll 8 times in about a second from O 7 a tile height for Cint scroll 0 scroll lt 8 11 GFX Set VScroll scroll delay ms 100 end for scroll Function Prototype 189 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit unsigned int GFX_Read_Mem_Port8 void Description _GFX_Read_Mem_Port8 reads 8 bit value from prop memory source note source pointer is always used for memory port ope
394. r on the hardware and there is no synthesis opportunities really of course you can always synthesis the samples PCM is a viable option for the Chameleon AVR but there is so little FLASH memory relatively speaking you would have to stream off and external SD card Thus instead of digitizing sound effects the technique used to save memory is to synthesize sound effects with various techniques Still you can definitely do PCM with the Chameleon AVR and or develop a Mod player if you wish but at the output stage you only have a single bit thus you have to use PWM to output your PCM data More on this later 14 1 2 Frequency Modulation FM Frequency modulation with a fixed waveform is very easy to do and the Chameleon AVR can do this no problem The idea here is to output a square wave or sine wave directly to the output device and then modulate the frequency So if we use the Chameleon AVR s internal timers we can do this more on this later or we can write a software loop to do it For example if you wanted to hear a 500KHz 1KHz and 2KHz signal you just write a software loop that toggles the output AUDIO MONO at that rate and you will hear the sound on the attached output device Figure 14 3 shows this graphically Figure 14 3 Synthesizing a single frequency 1ms period 1 KHz I O Audio Out 0 5ms 1 5mS rsr Time t Use built in timer counter or dedicated software loop Square Wa
395. r the demos and the demos themselves are located on the DVD ROM in the usual directory DVD ROM CHAM AVR SOURCE During initial setup of the tool you should have copied this entire directory to your hard drive 27 1 3 Setup for Arduino Version of Demos The setup for the Arduino version of the demos is a little different than the AVRStudio version since Arduino deals with libraries and sketches rather than straight C C files Thus there is a little setup The first thing is that you should have already copied all the Libraries from the DVD ROM into your Arduino installation directory If you recall after you install the Arduino tool it creates a number of directories from the root installation directory They looks something like Figure 27 1 Figure 27 1 The root Arduino installation directory arduino 0017 64 File Edit Favorites Tools Help gt 2 Search li Folders Address D development chameleon cham_avrisourcejar Y ET Go msn E drivers arduino exe File and Folder Tasks examples 8 cygicony 2 dll hardware 8 cygwin1 dll des placas S libusbo dll lib E readme txt arduino reference 35 rxtxSerial dll My Documents Stools Shared Documents gt 13 objects dX My Computer Then if you drill down into the HARDWARE sub directory you will find the LIBRARIES sub directory the contents of that directory are s
396. rations read or write In the Propeller driver source ptr is the variable tile src addr parm and is set using GFX Set Src Ptr unsigned int src defined below The idea of this function is that it provides a simple mechanism to access the Propeller s RAM Returns the 8 bit value read directly from the Propeller s 32K RAM This function also updates the source pointer automatically anticipating another read or write The actual code looks like update src pointer based on auto increment value tile src addr parm tile mem autoinc parm Thus the variable mem autoinc parm is used as the memory increment stride each read write operation This comes in handy and reduces address updates when you access continuous memory There is of course a function to change mem autoinc parm Example s Read the byte of memory currently pointed to by the source memory pointer data GFX Read Mem Port8 Function Prototype int GFX Write Mem Port8 unsigned int data Description GFX Write Mem 8 writes a 8 bit value to prop memory source ptr data note source pointer is always used for memory port operations read or write In the Propeller driver source ptr is the variable src parm and is set using GFX Set Src Ptr unsigned int src ptr defined below The idea of this function is that it provides a simple mechanism to access the Propeller s RAM This function also updates the source pointer automatic
397. rcuit as if it were made of resistors then transform back when done This is all not that important but its fun to know a little about analog stuff so let s continue So given all that we want to know what the voltage or signal is at the top of C15 Vout since this signal or voltage will then affect the remainder of the circuit Using a voltage divider made of R14 and C15 we need to write a relationship between the input voltage at AUDIO MONO call it Vin t and the output voltage of the RC filter at the top of C15 call it Vout t Ok here goes a few steps Vout s Vin s 1 sC R 1 sC Then dividing both sides by Vin s we get Gain H s 1 sC 1 sC Simplifying a bit results in Gain H s 1 1 8 Then transforming back from the S domain to the frequency domain we get Gain 1 1 2 Note Technically there is another term in there relating to phase but it s not important for this discussion In any event now this is interesting this equation Gain H f 1 1 2 PI f RC Describes the amplification or more correctly the attenuation of our signal as a function of frequency f This is very interesting Let s try something fun Let s plug in some values really quickly and see what happens let s try 0 Hz 1 Hz 100 Hz 1000 Hz 1 MHz and see what we get Table 14 1 shows the results Table 14 1 The results of passing various frequencies thru a low pass singl
398. reak up the line into pixels once again and see how many can be displayed each line There are 52 6 us of active video time We have to generate a 3 589594 MHz signal and stuff it into each pixel given this how many pixels can fit into a line Calculation of Color Clocks Per Line 52 6 us 3 579594 MHz 188 This means that at best case you can have 188 colored pixels per active scanline but it gets worst That doesn t necessarily mean that you can have 188 DIFFERENT colored pixels across the screen it just means you can request that from the poor TV with limited bandwidth Again this is a give take world and in many cases you would never have 188 different colors on the same line it would look like a rainbow In most cases objects have constant color for a few pixels at a time In any case many video system over drive the video to 224 240 or 256 virtual pixels but the color will not change that fast you can do this if you wish however suggest using a nice 160 x 192 display or thereabouts which will always look pretty good has enough resolution and you will almost get a 1 1 color change per pixel even if you change each pixel s color However give everything a try and see what you get 52 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 11 2 8 NTSC Signal References Here are a number of web sites and documents to help you understand the NTSC PAL video formats http www ntsc tv com http www s
399. res we can access via the AVR side That doesn t mean we can t abstract functionality and add higher level functions that build on the sub functions however this probably isn t productive since you will want to change drivers re write the Propeller driver and so forth Thus for the majority of the media drivers all the API functions do including the NTSC is expose some of the base functionality in nice function calls so you don t have to send SPI messages yourself In the case of the enhanced NTSC driver CHAM DEFAULT2 DRV 112 SPIN we are using the following Propeller Object for the NTSC tile engine and text display CHAM GFX DRV 001 TB 001 SPIN NTSC tile engine with support for terminal mode graphics as well as tile graphics smooth scrolling color manipulation large playfields fixed font 8x8 with 32x24 characters on the screen at one time In essence the mode acts like a console or terminal you can print to it it will scroll when you print the last line etc Additionally it supports more advanced graphics like functions for gaming applications but we will discuss that in the next section If your TV LCD has trouble displaying this driver s output then you can use the other default driver that uses the generic Parallax NTSC tile driver not as powerful but more stable signal The name of that driver is CHAM DEFAULT1 DRV 112 SPIN Then it loads the following driver for NTSC TV Text Half Height 011 spin NTSC tile e
400. ring int device char string Legacy function uses terminal NTSC VGA driver to print strings on the display Cee ea a eC ee Note 1 Not implemented yet just a place holder The following lists each function a description comments and example usage of the function Function Prototype int TWI Init long twi clock Description TWI_Init takes a single parameter which is the speed in Hz that you wish the TWI hardware interface to be initialized to 100KHz is usually used although some devices can support 400KHz as well as 1MHz read your target device for details Recall that the TWI two wire interface is the interface for our purposes since we are setting it up to conform to Returns 1 always Example s Initialize the TWI interface to 400KHz TWI Init 400000 Function Prototype char TWI_Action unsigned char command Description The TWI Action function is very powerful since it really doesn t do much other than pass the 161 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit parameter to the TWI hardware control register listed as TWCR in the datasheet Then the function waits for the operation to complete by blocking on the TWINT flag Normally you use the TWI Action function to perform any and all operations by logically OR ing various TWI flags together The flags can be found in the AVR 328P datasheet Returns the TWI hardware module
401. ring the Chameleon AVR 8 Bit 16 0 Chameleon Inter Processor Architecture Overview In this section we are going to go into a bit of detail in relation to the software engineering techniques that the Chameleon s duel processor architecture is based on This section isn t necessary to use the Chameleon but its necessary to understand the design more completely Figure 16 1 System level modular schematic NTSC TV Audio Amp PS 2 Keyboard Pins 16 23 Pins 12 15 VGA Core COG i 1 CHAM_GFX_DRV_001_TB_001 spin NS sound 052 11khz 16bit spin TV Text Half Height 011 spin gt ASM SPI lt Interface 0 cham_default2_drv_111 spin top object Propeller Chip Slave Media Processor SPI signals Pins 8 11 MISO MOSI SCLK CS Atmel ATMega 328P Master Control Processor Referring to Figure 16 1 the Chameleon s Propeller co processor has a number of connections to various media I O devices These include NTSC PAL composite video VGA audio out serial not shown and PS 2 keyboard mouse devices This uses up a minimum of 5 processing cores leaving us 3 cores for other things and for future expansion Of course two cores are used for the Master Control Program that runs on the Propeller as well as the SPI virtual driver Thus we are left with 1 core ultimately for expansion unless we modify the default Propeller driver As shown in the
402. rite to have been erased first once they are erased you can write to them The erase function is Flash Erase and 247 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit as long as you have done that once before writing or know that the FLASH is already erased then you call Flash Write and write one or more bytes anywhere the FLASH once again call Flash_Close when you re done Summary In this chapter you not only learned about the cool 1 MB Flash memory the Chameleon has but got a taste of file transfer protocols Hopefully you can take our 30 minute X Modem file transfer function and spend a good day on it and really make it robust 32 1 Native Mode Bootloader mode Currently there are two ways to use the Chameleon AVR Bootloader Mode with the Arduino bootloader pre loaded into FLASH memory Native Mode with AVRStudio generating a complete FLASH image The bootloader mode is convenient since the Arduino tool can download to the Chameleon or Arduino with nothing more than a serial port The native mode is nice since you have full control and you can write large complex programs that take up all the space of the AVR download them into the AVR and not worry about the bootloader section getting corrupted etc However you do not have to use the Arduino bootloader alone There are a number of bootloaders in fact the Arduino bootloader is nothing more than the Atmel standard application
403. river code looks like this MEN EDO CES CO ARAN E eet Ce RE E oa d L a T E ERE CR CL CLR hen execute commands sent the longer this loop is pum slower processing will be thus you will want remove unnecessary driver support for youn custone drivers and of course port to ASM and blend this with the virtual SPI driver code as well for the est performance MIL M MB M MM PP L PP P P PP P P P Pg P ATT PP P g PP PL P P gg M P P P P P Pg LP P g g M P TTT TTT repeat wait for SPI driver to receive a command packet in shared memory if C g_spi_cmdpacket amp 1 00 00 00 gt 0 reset the reception flags spi buffer g spi buffer amp 20 1111 1111 g_spi_cmdpacket g spi cmdpacket 4 FF FF FF extract cmd 8 bit data 8 bit status 8 bit cmd spi cmdpacket gt gt 16 amp g data g_spi_cmdpacket gt gt 8 amp FF byte of 16 bit data g_data2 g status g_spi_cmdpacket gt gt 0 amp FF high byte of 16 bit data build 16 bit data may not be valid though based on command g_datal6 g_data2 lt lt 8 g_data now process command to determine what user is client is requested via spi link case g_cmd GFX_CMD_NULL 130 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit GFX GPU TILE ENGINE COMMANDS catch all commands right here
404. rogramming the AVR chip only Atmel and other 39 party manufacturers sell programmers that are compatible with AVR Studio The AVR product called the AVR ISP MKII is typically used from the Atmel line of products as shown in Figure 4 1 Figure 4 1 The Atmel AVR ISP MKII programmer The interface is typically 6 pin but some hardware uses a 10 pin interface as well The ISP interface was designed to be controlled by either a simple RS 232 or parallel interface with a modicum of hardware The Chameleon AVR uses the 6 pin interface variant as shown in Figure 4 2 a located right below the Propeller I O port header Figure 4 2 Diagram of the AVR ISP interfaces MOSI 1 2 VTG MISO 1 2 VTG GND 3 4 GND SCK 3 4 MOSI 5 6 GND RST 5 6 GND SCK7 8 GND ISP6PIN MISO 9 10GND b ISP10PIN The ISP programming port is directly connected to the AVR chip s SPI Serial Peripheral Interface interface and consists of the following signals as shown in Table 4 1 30 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 4 1 AVR ISP signals Signal 6 pin 10 VO Description OOo O MISO 1 Input Data from target AVR to AVR ISP MOSI 4 Output Data from AVR ISP to target 9 1 The ISP protocol supports little more than reading and writing AVR FLASH and EEPROM resetting it manipulating the fuse register settings and so forth Debugging is NOT supported However you can build a AVR ISP programmer f
405. ropeller Local I O Port Module Primer The Propeller chip on the Chameleon is more or less peripheraless if that s a word In other words if you want serial SPI A D D A etc you use a core and write one yourself using software Thus the philosophy of the Propeller chip is a lot of I O pins and a lot of processors what you do with them is up to you The Chameleon uses most of the I O pins for the video audio VGA and PS 2 port but we were able to tuck 8 I O pins away and export them out to what is called the Propeller Local Port With this you can hook up devices that are designed to interface to the Propeller us it for switches a D A A D even another video or VGA port That said what decided to do was write a very rudimentary interface to it so you can control the direction of each port bit input or output and then write read data to and from the port from the AVR So if you run out of digital I Os on the AVR headers you can use the Propeller port or if you just want to connect something to the Propeller that takes 8 or less I O pins that someone has developed a Propeller object for Either way in this section we will see the API for the Propeller Local Port One detail before we begin the Propeller Port does NOT have a driver object running on another core It s so simple that we wrote the code right into the master control dispatch program object There is a complete listing of the code below excerpted from CHAM DEFAULT
406. rrupt and can wait for the characters to transmit before the function returns Function returns nothing 149 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Example s Initialize UART to N81 38400 manually transmit Chameleon shut the UART down initialize to N81 always UART Init 115200 send the characters UART Transmit C UART Transmi UART Transmi UART Transmi t UART Transmit UART Transmi UART Transmi UART Transmi UART Transmi t Zomrmzrzr ANNIS YY shutdown the UART system UART Shutdown As noted the shutdown function really only disables the ISR s so you can still use the manual transmit and receive functions if you wish Function Prototype void UART Newline void Description ART Newline simply send a CR LF 0x0A OxOD to the UART Assuming a terminal program is connected to the Chameleon AVR this function is a nice helper to print newlines when needed Returns nothing Example s Assuming the Chameleon AVR is connected to a PC or other terminal with VT100 capabilities print 10 newlines for Cindex 0 index 10 index UART_Newline Function Prototype void UART Print String char string Description Print String prints a NULL terminated string The function first prints a newline then the string takes a pointer to the ASCIIZ string Returns nothi
407. rs already written for the Propeller which is the tactic we use for the Chameleon More or less every single device interfaced uses a standard pre written driver and all we do is make calls to it from the AVR chip But its nice to know how these things work so let s take a look Table 12 1 below lists the pins and I O map for the hardware interface 53 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Table 12 1 PS 2 connector interface to Chameleon AVR Prop Port Bit Pin Chameleon Signal Description P27 PS2_CLOCK Keyboard clock signal open collector P26 PS2 DATA Keyboard data signal open collector As noted the PS 2 interface works the same for keyboards and mice the protocols are different but the low level serial and hardware interfaces are the same Thus if you plug a mouse into the port it would work the same the clock and data lines would be in the same place Thus all you would have to do is write the driver In the section below general keyboard and mouse operation is described so you can write your own drivers if you wish The driver we used for the Propeller driver supports both keyboard and mouse but its not integrated thus a core is needed for each driver object a bit wasteful 12 1 Keyboard Operation The keyboard protocol is straightforward and works as follows for every key pressed there is a scan code referred to as the make code that is sent additiona
408. rscan GFX Set Top Overscan Color color amp OxFF set bottom overscan GFX Set Bottom Overscan Color color amp OxFF slow things down a bit so we can read the text _delay_ms 100 end for bright end for color end while The code simply formats a Propeller compliant color and then calls the API function to change the top and bottom overscan color that s it Summary This demo shows how easy it is to use the advanced GFX tile engine API functions in particular to animate the overscan color on the NTSC display 214 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 28 1 3 NTSC Smooth Scrolling Tilemap Demo This demo illustrates the smooth scrolling feature of the default2 versions of the Propeller driver The NTSC tile engine supports course horizontal and vertical scrolling simply by changing the tile map base pointer However the engine also supports pixel smooth scrolling in the vertical direction The allows you to smoothly scroll the tile map any number of rows you wish First you smooth scroll 0 7 pixels then you reset the smooth scroll register and course scroll and repeat To the user this will look like one continuous scrolling action Figure 28 3 shows the demo in action Figure 28 3 NTSC smooth scrolling demo t dot H z LI E NE Ls L gt et Las Compiling and Runn
409. rts to move the servo right or left you can use a PS 2 keyboard Or mouse And now imagine that you can display the position and angle on a VGA monitor and even draw the servo in color graphics on the screen So the Chameleon is like a super charged Arduino with support for graphics audio keyboard mice and much more And the cool thing is that the code you have to write to support the added features and capabilities of the Chameleon are usually just a few lines that call API functions to communicate with the Parallax Propeller media processor IMPORTANT So without further ado let s begin 12 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 1 0 Architectural Overview Figure 1 0 The Chameleon AVR 8 Bit NTSC Video Audio VGA Port i PS2 Mouse Keyboard Y i an 1 S5SO00000000008 INOIOIC O O O O 0 9 9 9 0 0 9 eee 2 0 099909 1 OOC RC 1O0OOc CC 009 9e o Power Switch left ON The Chameleon AVR 8 Bit or simply the Chameleon AVR is developed around the Atmel 8 Bit Mega AVR 328P28 Pin DIP QFP Figure 1 1 shows an image of the Chameleon AVR 8 bit annotated The Chameleon AVR has the following hardware features 28 Pin DIP Package version of the AVR 328P runs at 16 MHz with a maximum speed of 20 MHz suggested by Atmel However it can easily be over clocked to 25 30 MHz Paralla
410. s configurations etc for that particular configuration so don t mess with it However you can copy a sketch from the sketches directory to another system or the entire sketches directory usually without a problem In any event let s load a Hello World sketch into the Arduino tool compile and download to the Chameleon Here are the steps to get things ready Step 1 Make sure the Chameleon is powered the USB cable is plugged into it Step 2 Make sure you have the NTSC and VGA monitor connected at least one of them Step 3 Make sure you have the serial selection switch in the DOWN position to allow AVR serial traffic UP is Propeller traffic Step 4 On the main menu goto File Sketchbook Sketches and locate the sketch named cham hello world select it it should load into the tool This is shown in Figure 15 57 below 118 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 57 Loading our first Hello World sketch sketch_sep24a Arduino 0017 3 39 Edit Sketch Tools Help New Open Cctrl O Sketchbook arduino 0017 gt Examples sketches cham avr hello world Close Ctrl cham_avr_work Save Ctrl S Save As Ctrl Shift 5 Upload to I O Board Ctrl U Page Setup Ctrl Shift P Print Ctrl P Preferences Ctrl Comma Quit Ctrl Q Once you load the sketch the tool should load the source for the main program as shown in Figure 15 58 below
411. s state etc For example when the Propeller boots our driver it blinks 3 times to indicate that everything is good to go driver is ready to receive messages from the client master However after the we were all done designing everything and the drivers were written We left out messages to control the LED from the client master but thought hmmm will hold off on this and later us it as the perfect example of adding some messages to do something useful Thus this example was born of that motivation With that in mind this is a good exercise since at first you will want to make small changes to the master driver but not re write it Anyway so the first thing you need to do is decide what new functionality you need In this case all needed was to control the LED turn it on and off So the first thing you need to do is copy the Propeller driver and re name it something else In this case made a copy of cham default2 drv 112 spin and renamed it to cham default2 drv 112 modified spin This way if mess something up can go back to my original Then reviewed the messages at the top of the code and found where new messages can go and added two new commands 100 and 101 here s a snippet of what the constants looked like before and after Before REG WRITE 56 performs a 32 bit write to the addressed register 0 F from the output register buffer REG CMD READ i i i 57 performs a 32 bit read from the addres
412. s 16 bit tile map ptr which points to the current terminal ptr into the tile map terminal level print functions use this pointer Writes 16 bit tile map ptr which points to the current terminal ptr into the tile map terminal level print functions use this pointer Reads 16 bit tile bitmaps ptr which points to the bitmaps indexed by the tilemap Reads 16 bit tile bitmaps ptr which points to the bitmaps indexed by the tilemap 10 GPU GFX BASE ID Reads 16 bit palette array ptr which points to the palettes in use for the tilemap CL1 GPU GFX BASE ID writes 16 bit palette array ptr which points to the palettes in use for the tilemap GPU GFX TOP OVERSCAN COL 12 GPU GFX BASE ID Reads top overscan color drawn on the screen GPU GFX TOP OVERSCAN W 13 GPU GFX BASE ID Writes top overscan color drawn the screen GPU GFX BOT OVERSCAN COL 144GPU GFX BASE ID Reads top overscan color drawn on the screen GPU GFX BOT OVERSCAN COL W 15 GPU GFX BASE ID Writes top overscan color drawn the screen GPU GFX HSCROLL FINE R GPU GFX HSCROLL FINE W GPU GFX VSCROLL FINE R GPU GFX VSCROLL FINE W GPU GFX SCREEN WIDTH R GPU GFX SCREEN WIDTH W GPU GFX SRC R GPU GFX SRC ADDR W GPU GFX DEST ADDR R GPU GFX DEST ADDR W GPU GFX NUM BYTES R GPU GFX NUM BYTES W GPU GFX DATA R GPU GFX DATA GPU GFX RAM PORT8 R GPU GFX RAM
413. s 2X the FLASH and RAM Thus when we started the design only the 168 was available Moving on the chip is very simple to interface just power and an external XTAL which is removable at 16 MHz Take note of the SPI interface lines on the right these are very important since they are used to communicate with the Propeller chip as well as the on board 1MB FLASH 34 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 8 0 Parallax Propeller Subsystem Figure 8 1 The Propeller Subsystem Onboard Program Memory 32 128K EEPROM Status Debug LED 33VCC STATUS_LED xo 1 R2 CRYSTAL 330 a 24LC256 512 PACKAGE TSOPS VCC 33VCC P31 P30 P29 P28 P27 P26 P25 P24 BOEn pe BOEn 10x10mm body Xx JpRESn lt gt RESn 0 8mmlead pitch P23 P22 P21 P20 P19 P18 P17 P16 lt gt lt P VGA BLUE B1 T go To lt gt Bi lt T lt gt prop T USB T lt gt VGA_RED_BO VIDEO 1 T VIDEO 2 T SPI SS2n SPI MOSI lt T gt SP MISO lt T gt SPLSCK T VIDEO 0 lt gt AURAL 0 lt gt 70 3 VGA HSYNC lt gt BLUE BO PROP SCL PROP SDA PS2 DATA lt T gt PS2 CLOCK STATUS LED T AUDIO T VGA VSYNC T VGA GREEN GREEN gt VGA RED B1 USB RXD CONN SIL8 Figure 8 1 depicts the entire Propeller chip subsystem It consists of t
414. s a sound and silences the channel int Sound StopAll void Stops all sound channels and silences them Updating a Sound int Sound Update int channel int frequency int volume Updates a currently playing sound The following lists each function a description comments and example usage of the function Function Prototype int Sound Play int channel int frequency int duration Description Sound Play instructs the driver to play a single tone on one of the sound channels The parameters 195 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit are channel 0 3 frequency 0 2000 Hz duration 0 7 seconds where 0 means to play forever Returns 1 Example s nstruct sound channel 0 to play 440hz for seconds Sound Play 0 440 3 Function Prototype int Sound Stop int channel Description Sound Stop stops the sound playing on channel Returns 1 Example s Stop all channels manually for Cint ch 0 ch lt 4 che Sound sStop ch Function Prototype int Sound StopAll void Description Sound StopAIl stops all sound channels and silences them Returns 1 Example s Stop all playing sounds Sound 11 Function Prototype int Sound Update int channel int frequency int volume Description Sound Updater allows you to update a sound channel 0 3 on the fly without interrupting it You can mod
415. s and all their old programs will still work but you new functionality will be at their finger tips There is so much you can do with the Chameleon don t even know where to begin But some of the things you might want to try are Using the Propeller as the Master and writing a driver on the AVR chip so the Propeller can use its resources peripherals etc The Propeller has a local 8 bit port you can use this for anything One idea that is really easy to implement is adding a micro SD card adapter to it Sparkfun sells a little adapter that is mounted on a right angle header that will plug right into the 8 bit Propeller port You can then get a SD card object add some messages to the master control program driver and presto you have a FLASH hard drive you can access from the AVR chip Networking the Chameleons together The Chameleons are so small and powerful a cool idea would be to network 4 8 of them together each generating video VGA but being controlled by a super master unit to do something in unison Creating a Arduino Shield adapter board The Chameleon both AVR and PIC have similar I O headers to the Arduino but due to physical constraints they are different A cool piece of add on hardware would be a daughter board that mounts on top of the Chameleon to make it 100 I O compatible with Arduino shields 254 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 35 1 Demo Coder Applica
416. s for GPU operations Reads 16 bit number representing the number of bytes for a GPU operation Sub Function Writes 16 bit number representing the number of bytes for a GPU operation Sub Function Reads 16 bit data word uses for GPU operations or memory access operations Writes 16 bit data word uses for GPU operations or memory access operations Reads 8 bit data pointed to by the currently addressed memory location in the GPU pointed to by the src addr low hi After the operation the src addr ptr is incremented as per the GPU configuration Writes 8 bit data pointed to by the currently addressed memory location in the GPU pointed to by the src addr low hi After the operation the src add rptr are incremented as per the GPU configuration Reads to by After 16 bit data pointed to by the currently addressed memory location in the GPU pointed the src addr low hi the operation the src addr ptr is incremented as per the GPU configuration Writes 16 bit data pointed to by the currently addressed memory location in the GPU pointed to by the src addr low hi After the operation the src add rptr are incremented as per the GPU configuration Reads the current raster line being drawn from 0 191 or whatever the GPU s line resolution is set to Jl Reads current memory auto increment setting for read write operations lower 4 bits 0 15 default 0 Writes the current memory auto increment setting for read write operati
417. s related 1 1 to a source library file name Go ahead and dive into LIBRARIES as shown in Figure 15 46 Figure 15 46 The Arduino LIBRARIES directory amp libraries Edit View Favorites Tools Help ay sxx gt 27 Search Folders 1 Address D Adevelopmentlchameleonicham avrlsourcelarduinolarduino 0017Y1hardv Go msn File and Folder Tasks Ethernet Firmata Other Places LiquidCrystal Matrix Cg hardware 5 E My Documents SoftwareSerial Shared Documents B epper 9 Computer epp gt Ic wire X My Network Places Details O bytes E My Computer These are all the libraries provided by the Arduino development system Go ahead and take a look in a few to see what s in them then come back to the root directory as shown above Now what we need to do is copy our new Chameleon libraries into this directory So go back to the DVD in the Arduino folder and copy the contents of the LIBRARIES sub folder into your install folder When you re done it should look like the image shown in Figure 15 47 109 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 47 The Arduino Libraries folder after copying the Chameleon libraries into it amp libraries gt File Edit View Favorites Tools Help ay Qe 2 27 yo Search Folders EJ Address D development chameleon cham_
418. s shades of gray This gives us a total luma range of 6 values and still allows color to work which the Propeller is designed to be able output 16 phase shifts of the color burst This gives a total color luma range of 16 6 96 colors without resorting to tricks If you are really interested in how to write graphics drivers you should peruse the source code of the various graphics drivers written by various authors for the Propeller Additionally the only reference book that explains in detail how the graphics system works is Game Programming for the Propeller Powered HYDRA which you can find on Amazon com Parallax com and XGameStation com There is also some minimal 44 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit coverage of the Propeller s graphics hardware transcribed from the HYDRA book in the Propeller Manual itself located on the DVD here DVD ROM CHAM_AVR DOCS PROPELLER Propeller_Manual_WebPM v1 1 pdf Now let s discuss a little bit about NTSC video signal generation Figure 11 2 Horizontal scan versus display brightness Scan Line White Level 100 IRE Horizontal Blanking Interval Black Level Setup _ 7 5 __ Blanking Level 0 IRE IRE is an arbitrary unit that relates to the voltage of the video signal 100 IRE 1 0V these days however previously 140 IRE 1 0V There is an EXACT spec for broadcast but many video generation hardware units assume a tota
419. s status register TWSR this can be tested against common TWI status and success values to determine the results of any action Example s The complete listing of the digital potentiometer function excerpted from the Mechatronics library yore POT Set int pot value UPDATE TWI POT currently supports an Analog Devices AD5242 PDF datasheet can be found on DVD here Manufacture page here http www analog com en digital to analog converters digital potentiometers ad5241 products product html this function requires the use of the CHAM AVR SPI DRV VO10 c h function library send start command if TWI Action SET TWINT SET TWEN SET TWSTA TW START TWI Error now set slave address and high bit of 17 bit address page bit PO selects which 64K page TWDR 0x58 010 1 1 1 ADO R W gt 0101 1000 for write 0101 1001 for read if TWI Action SET TWINT SET TWEN TW MT SLA TWI Error now write instruction byte reset select pot A 00 on digital outputs TWDR 0x00 A B RS SD 01 02 gt 0100 0000 if TWI_Action SET TWINT SET TWEN TW_MT_DATA_ACK TWI Error now write pot value 0 255 TWDR pot value if TWI Action SET TWINT SET TWEN DATA TWI Error send stop condition TWCR SET TWINT SETCTWEN SET TWSTO wait until stop condition is executed and bus released while TWCR
420. s the Propeller chip all cogs disabled and I O pins floating Propeller restarts 50 ms after RESn transitions from low to high Crystal Input Can be connected to output of crystal oscillator pack with XO left disconnected or to one leg of crystal with XO connected to other leg of crystal or resonator depending on CLK Register settings No external resistors or capacitors are required Crystal Output Provides feedback for an external crystal or may be left disconnected depending on CLK Register settings No external resistors or capacitors are required The Parallax Propeller is really useful for doing many things at once without trying to use interrupts multitasking and round robin programming techniques to perform multiple tasks You simply write your code and run it on acore Then if that code crashes is broken it does not affect the other cores at all This is exactly what the Chameleon needs a way to run multiple processes that each perform some kind of media task and then these processes wait for the master the AVR to send commands Each core does not care what the neighboring cores are doing only what it is doing Luckily if this all sounds like this is way too complicated you don t have to worry about it You do not have to program the Propeller chip at all if you do not want to The AVR communicates to it via a simple API and from the AVR your perspective the Propeller is just a media slave that generates NTSC
421. second concern might be there is no ground on the 8 bit port so how does this work Well when we set an I O to digital 0 it s at a virtual ground and being pulled to GROUND by a transistor switch so as long as the amount of current your draw thru the circuit isn t too much the virtual ground will remain very close to 0 If you draw a lot of current then the ground will rise or float up due to the voltage drop over the transistor switch pulling the pin LOW Figure 31 1 A screen shot of the NTSC output left and the actual LED blinking on the Chameleon right Compiling and Running the AVRStudio Version Demo Version Description Blinks and LED on the Propeller Port Main Source File CHAM AVR PROPPORT DEMO 01 Additional Files Required CHAM AVR SYSTEM VO010 c h CHAM AVR TWI SPI VO010 c h CHAM AVR VO010 c h CHAM AVR PROP PORT DRV V010 h General Requirements Video port connected to NTSC TV monitors LED plugged into the Propeller Port leftmost 2 pins orientation doesn t matter 231 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Controls Required None Compiling and Running the Arduino Version Demo Version Description Blinks and LED on the Propeller Port Main Sketch Source File CHAM AVR PROPPORT DEMO Additional Library Files Required imported automatically by sketch CHAM AVR SYSTEM 010 CHAM AVR SPI DRV 010 CHAM AVR D
422. sed register 0 F and stores in the input register buffer REG WRITE BYTE 58 write byte 0 3 of output register g reg out buffer byte 0 3 250 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit REG_CMD_READ_BYTE 59 read byte 0 3 of input register g_reg_in_buffer byte 0 3 system commands SYS_RESET 64 resets the prop his range mands j HT HH TL PT T MM advanced GFX commands for GFX tile engine GPU GFX BASE ID 162 starting id for GFX commands to keep them away from normal command set GPU_GFX_NUM_COMMANDS 37 number of GFX commands Reads the status of the GPU writes the GPU Sub Function register and issues a high level command like copy fill etc writes status of the GPU writes the GPU Sub Function register and issues a high level command like copy fill etc GPU_GFX_SUBFUNC_STATUS_R 0 GPU_GFX_BASE_ID GPU_GFX_SUBFUNC_STATUS_W 1 GPU_GFX_BASE_ID After Adding New Messages 56 performs a 32 bit write to the addressed register 0 F from the output register buffer REG CMD WRITE 57 performs a 32 bit read from the addressed register 0 F and stores in the input register buffer REG CMD READ REG CMD WRITE BYTE 58 write byte 0 3 of output register g reg out buffer byte 0 3 REG CMD READ BYTE 59 read byte 0 3 of input register g reg in buffer byte 0 3 system commands SYS RESET 64 res
423. serial UART 22 AVRIPIC gt E 2 FTDI virtual COM port drivers running Remote Keyboard Chameleon AVR PIC to interface to USB Rev A serial UART on Chameleon PC connection is not required Only needed for development Referring to Figure 1 1 this is a system level diagram of the relationship of the Chameleon to all the system components First everything to the right is optional and only needed for programming the Chameleon Once the Chameleon is programmed it s a stand alone application that you can put anywhere you like With that in mind let s take a quick look at how things work To begin with there are two processors on the Chameleon AVR the AVR ATMega 328P and the Parallax Propeller chip The AVR chip is used as the master processor You write your application on there in C C ASM or with the Arduino tool and then using a very simply you send messages to the Propeller chip The messages direct the Propeller chip to perform tasks These tasks can ultimately be anything but for now we have set the Propeller up so it can generate NTSC and VGA graphics audio and read keyboards and mice So the Propeller does all the work for you the AVR does very little thus freeing the AVR to take the role as master controller The messages sent to the Propeller are transferred over a high speed SPI serial peripheral interface link The AVR has SPI hardware built in so sending b
424. ses installation Device Manager File Action Help Here 2 Multifunction adapters 88 Network adapters 7 Communications Port COM1 7 Communications Port COM2 ECP Printer Port LPT1 PCI Parallel LPT3 Sound video and game controllers System devices Universal Serial Bus controllers Generic USB Hub Intel R 82801BA BAM USB Universal Host Controller 2442 Intel R 82801BA BAM USB Universal Host Controller 2444 PCI to USB Enhanced Host Controller B1 NEC PCI to USB Open Host Controller NEC PCI to USB Open Host Controller Make note of the USB Serial Port in this case the driver installed on COM30 yours might be different but you will need this when running the Arduino tool Propeller took and any terminal programs to talk to the Chameleon AVRs for the serial RS 232 demos So write this number down for the next step of the tool setup Also we might as well install a good serial program now so you don t have to do it later The Arduino tool has one built in as does the Propeller tool but for general terminal experiments Hyperterminal won t cut it 111 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 2 3 1 Installing a Serial Terminal Program The Chameleon AVR has a USB serial port that is used to communicate with the Arduino tool as well as the Propeller tool Both of these programs have built in serial communications but
425. sessesescssscssssssssesssssssesses 19 1 3 The Parallax Propeller Chip 24 1 31 Propeller Core COG Vide Hardware 26 1 4 System Startup and Reset Details 26 PART I HARDWARE DESIGN PRIMER ras oninia prag ob rad Ra pa dcs Eo eu Ra Rn nad ao Ee DE RR EVEN YR E Ma ro 26 2 0 5 0V 8 3 3V POWER SUPPLIES Iu wo FEX P YER Ra SIR 29 RESET CR OUT akin iater eaa 29 4 0 ATMEL 6 PIN ISP PROGRAMMING 30 4 1 AVR ISP Programming RR 30 5 0 SERIAL USB UART PROGRAMMING PORT 31 6 0 USB SERIAL YAR T 33 7 0 ATMEL AVR 328P SUBSYSTEM cubrir aen Ce ba HAUS nex UE 34 8 0 PARALLAX PROPELLER SUBSYSTEM 35 8 1 The Propeller Local 8 Bit Port eee eee eee eese eene tenentes stesse tas etta setis sesta sess se sen seen seen se 35 9 0 THE SPI BUS AND COMMUNICATIONS SYSTEM 36
426. setup should be the same Thus the workflow moving forward will be to add subtract files from the Source Files folder of the same project then Rebuild All from the Main Menu s Build menu then using the AVR ISP programming tool control panel Program the Chameleon AVR with the new binary That s it 15 2 Arduino Toolchain Setup The Chameleon AVR ships with the Arduino bootloader pre loaded into the AVR s flash memory This allows you to immediately use the Chameleon as an Arduino more or less but with added media abilities via the Propeller chip Without the Arduino bootloader on the AVR chip you would have to use the AVR ISP programmer or something else to get code into the AVR chip But with the Arduino bootlooader the Arduino tool talks to the AVR chip over a serial port via the USB serial port on the Chameleon and you can compiler and download programs Figure 15 41 shows the relationship between the components of an Arduino like setup Figure 15 41 The Arduino system setup with the Chameleon AVR GNU GCC Arduino IDE JAVA based spen Link Make AVR LibC lt gt Gas Stdlib Runtime The Arduino IDE makes calls down to the AVR GNU GCC toolchain transparently and is installed as part of the Arduino tools Startup All the AVR libraries needed to build applications This is the main application you will develop your code with Chameleon AVR 8 Bit
427. sign had to think of a clean way to interface the processors such as shared memory SPI etc Taking all those factors into consideration decided to use the Atmel AVR AT328P processor for the Master and the Parallax Propeller chip for the Slave The PIC version uses a PIC24 16 bit processor but the idea is the same Thus the idea is that the AVR or PIC with its huge fan user base will be the ring leader you code in C ASM on the AVR processor and then over a SPI interface you send commands to the Propeller chip which is running a SPI driver and then issues the commands from the AVR to various processors more on this in the Architecture Overview This is the perfect fusion and balance of the two processors From the AVR s perspective the Propeller chip is simply a media processor the programmer need not know a single thing about the Propeller if he doesn t want to On the other hand this setup is incredibly flexible The Propeller can run any set of drivers on it that we wish and thru an agreed on communications protocol the AVR can control these drivers remotely and get work done Finally when started designing the AVR version of the Chameleon a couple years ago kept hearing about this product called the Arduino finally went to the site and checked it out but was surprised that there was no Arduino per se The Arduino isn t a product so much as it s an ideal or methodology of software and tools There is nothing but a single
428. sing the VSU video streaming unit For example each line consists of the following areas Front Porch The spec calls for a front porch of 1 5 us consisting of black therefore you would tell the Propeller hardware to send out black then you would delay for 1 5 us talking into consideration the amount of time to execute the actual instruction that turns black on Sync Tip The next part of the spec is the horizontal sync or HSYNC this should be approximately 4 7 us therefore you would tell the video hardware to output a 0 0V for 4 7 us The next portion of the video signal is the Color Burst which consists of a pre burst phase called the Breezeway the burst itself called the Color Burst and finally the post burst called the Back Porch Breezeway This part of the spec says to output black for 0 6 us Color Burst This is the most complex part of the specification and the one that would be nearly impossible to do without the extra hardware support of the Propeller s VSU In any case we will explain how this works shortly but for now you need to know that you must generate 8 10 cycles of color burst tone This is a 3 579594 MHz tone signal that the TV locks onto and uses as a phase reference for the remainder of the video line The color of each pixel is determined by the 51 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit phase difference from the color burst
429. spective driver and can send and receive messages from that driver So when a NTSC command is parsed for example the handler simply calls the NTSC driver and passes the request for execution When the processing is complete the MCP loops again and waits for the next command to process Even if you don t have a degree in Computer Science you have probably used remote procedure calls or RPCs in one form or another or even invented them unknowingly The idea of a remote procedure calls came about in the 1970 s actually so it s a really old concept The basic idea is very simple for one process program to be able to call use a subroutine or function in another process program More or less a form of interprocess communication Figure 16 4 RPC call from process to process in contrast to a DLL call RPC Call Overview DLL Call Overview Process 1 Process 2 Process 1 Process 2 RPC call from process 1 to 2 Local DLL DLL call BA subroutines amp memo subroutines amp i 1 memo Void foo DLL call process s dynamically y lisse links to common code in DLL library code is loaded and executed by process s However code is not part of a seperate Call across process process but rather simply loaded into boundaries into other common memory space and executed by processes subroutines calling processes void foo 1 code void 01 lt
430. src addr low hi After the operation the src add rptr are incremented as per the GPU configuration define GPU GFX RAM PORT16 R 324GPU GFX BASE ID Reads 16 bit data pointed to by the currently addressed memory location in the GPU pointed to by the src addr low hi After the operation the src addr ptr is incremented as per the GPU configuration define GPU GFX RAM PORT16 334GPU GFX BASE ID Writes 16 bit data pointed to by the currently addressed memory location in the GPU pointed to by the src addr low hi After the operation the src add rptr are incremented as per the GPU configuration define GFX RASTER LINE R 34 GPU GFX BASE ID Reads the current raster line being drawn from 0 191 or whatever the GPU s line resolution is set to Jl gpu configuration registers define GPU_GFX_SET_AUTO_INC_R 354GPU GFX BASE ID Reads current memory auto increment setting for read write operations lower 4 bits 0 15 default O define GFX SET AUTO INC 36 GPU GFX BASE ID Writes the current memory auto increment setting for read write operations lower 4 bits 0 15 default 0 Each register is actually a message to the SPI driver so we cleverly pass these register access requests right thru and tunnel them thru the SPI interface Now there are a lot of registers 37 to be exact currently but they are all more or less self explanatory if you read the comments To start we se
431. ssing is achieved by 7 bit address sent down the bus to all devices only the listening device with the matching address responds and communication begin Let s discuss this process more in detail 19 2 1 Understanding Bus States The protocol is rather complex compared to SPI protocol In fact there is no SPI protocol per se SPI is a simple serial packet much like RS 232 The only protocol that SPI devices have are inherent in the devices themselves and what the bytes sent and received mean on the other hand has this very complex arbitration system to handle multiple Masters on the bus this is facilitated via the electrical design as well as a state machine that is based on Considering this is rather complex We are only briefly going to cover some of the high level concepts of the protocol and its primary states START and STOP To begin with data is transfer is always initiated by a Master device remember Slaves can only respond to Masters A high to low transition on the SDA line while SCL is high is defined to be a START condition or a repeated START condition Everything begins with the START condition that s the first thing to remember with FG Figure 19 4 below show the timing waveforms for this event 156 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 19 4 Timing waveforms for START Condition Addr MSB Addr LSB R W ACK 1
432. state XSTATE_EOT break 3 end if fuser packet number s e 1 ch UART_getcQ if 1 ch CHR CTRLZ break end while xpacketnum ch if DEBUG_XMODEM gt 2 sprintf sbuffer Packet d r xpacketnum NTSC Term Print sbuffer endif packet number complement de e 1 ch UART_getcQ if 1 ch CHR CTRLZ break end while ch if DEBUG_XMODEM gt 2 sprintf sbuffer Packetn 255 packet d r xpacketnumn NTSC_Term_Print sbuffer endif now get the packet 241 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit xchecksum_computed 0 if DEBUG_XMODEM gt 2 NTSC Term Print DATA NTSC Term Char OxOD endif for index 0 index lt 128 index wait for next byte while 1 ch UART_getcQ if 1 ch CHR_CTRLZ break end while insert into buffer Cif still room if C Cindex xpacketnum 1 128 lt buffer size file buffer index xpacketnum 1 128 update checksum xchecksum computed ch if DEBUG_XMODEM gt 1 test for printable m ch gt 32 amp amp ch lt 127 ch 0x0D NTSC Term Char ch Term Char ch end if printable else non printable character print something for place holder NTSC Term char C Di NGA Term Char mi DE end else non printable endif end for index add bytes read
433. steps then it s worth it or if the local process or machine can t perform the computation etc Thus RPC calls and technology allow a process or machine to use subroutines and resources running in another process or another processor or an entirely different machine In our case we use the concept of RPCs to make calls to another processor from the AVR s SPI interface thus it s a machine to machine call where each call packet is only 3 bytes But let s keep exploring the general idea of RPCs and some strategies that might help you later as you update modify the default drivers shipped with the Chameleon 16 3 1 ASCII or Binary Encoded RPCs When designing an RPC system you can make it really complex or really simple The main idea is that you want to be able to call functions in another process processor machine Decisions have to be made about the RPC protocol and how you are going to do things There are no rules for RPC calls unless you are using a Windows Linux Sun etc machine and want to use one of the official OS s RPC call APIs When you design your own RPC protocol it s up to you In our case its tempting to make RPC calls ASCII based and human readable This of course eats bandwidth and is slower than binary However since it is human readable the RPC calls take a format that look more like commands rather than strings of bytes representing data Thus one model might be to use ASCII format which would be easy to use and remem
434. sting Reference eese eee eese eene eene teens et desos sse snso 148 18 4 API Functional Declarations RR eae ne 148 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 19 0 SPI AND LIBRARY MODULE PRIMER eerte tnt 152 19 1 SPE Bus ad e aee esas pi epa dde 153 19 1 1 Basic SPI Communications 155 19 2 PC DD e 155 19 2 1 Understanding Bus States ciscus ned en RR AREE EHE ACHSE 156 19 3 Header File Contents Overview sscsssccssssccssecsssecsssscsssscssssecsssscssssessssesssscsssecsssscssssessssecsssscsssscssssessssscssssosssscossseosees 158 19 4 Listing Reference 160 19 5 API Functional Declarations RR 161 20 0 NTSC LIBRARY MODULE PRIMER 167 20 1 Sending Messages to the Propeller Directly scssscsssscsssscssscsssssscssecsssscssssessssessssscsssecsssscsssssssssscsssscsssssssssessssesseseoes 168 20 2 Header File Con
435. subtle difference is very important you do NOT need these libraries anything you can do with the libraries you can do directly with the SPI_Prop_Send_Cmd but to make life a little easier wrapped many of the commands in function calls for convenience For example to print a character to the NTSC screen you can do it directly without the NTSC API like this SPI Prop Send Cmd GFX CMD NTSC PRINTCHAR ch 0x00 Or you can call the NTSC API function to do it NTSC Term Char ch But let s dive into NTSC Term Char and take a look int NTSC Term Char char ch this prints a single character to the NTSC terminal all drivers Default1 2 etc also supports translation commands supported by the NTSC terminals clear screen home backspace tab 8 spaces per set X position X follows set Y position Y follows set color color follows return other characters are not translated but simply printed to the terminal 5 o Hg ow oH Hn n d SPI Prop Send Cmd GFX CMD NTSC PRINTCHAR ch 0x00 wait a bit driver takes time to respond delay us SPI PROP DELAY SHORT US return success return 1 end NTSC Term char As you can see other than comments the functionality of the two methods is identical So the point is these API functions are very thin wrapper functions that more or less give function names to the commands and make t
436. t most so once again we see that the technique works perfectly Also notice that it takes only 100 cycles of the PWM clock to iterate thru one complete cycle of the sine table which makes sense as well In conclusion the software is where the magic is here The PWM audio circuitry couldn t be simpler as shown in Figure 14 5 Additionally you can synthesize multiple channels by simply having multiple phase accumulators and phase increments in fact to synthesize a 64 channel system you would just need something like int phase_inc 64 phase_acc 64 And you simply run a loop over everything and at sum up all the phase accumulators each cycle and use the sum as the index into the sine table Of course the sine table itself has to scaled in the amplitude axis and you must do a auto scale so that the sum doesn t overflow but you get the idea Moreover you can store other waveforms like square triangle sawtooth and so on and then mix various waveforms Finally you can easily overlay a ADSR attack decay sustain release envelope to a note based system and create just about anything The only downside to PWM is that it must be VERY accurate your ears are VERY sensitive to frequency shifts so the timing loops must be perfect thus a hardware timer or a tight loop needs to be used that doesn t vary otherwise you will hear it In conclusion that s a taste of what goes into generating sounds on the Propeller chip Then there is
437. t to your program and then make calls to it More on this later when we learn how to modify the Chameleon drivers at the end of the manual The Chameleon AVR has no operating system or external peripherals that need initialization thus the AVR 328P more or less is the entire system When the AVR powers up out of reset it will either load the boot loader if there is one or begin execution from the primary application memory of the FLASH The initial configuration of the chip is defined by the fuse bit settings which are controlled by the programming of the chip In our case the fuse settings are mostly default with the Arduino boot loader and set to clock from an external high speed xtal We will discuss exact details when we get to the software and IDE configuration Once the AVR 328P boots and starts executing code whatever is in the application program area is executed simple as that While this is all happening the Propeller chip boots as well and will start up doing whatever its programmed to do Normally this will be to load the default SPI driver system and wait for commands from the AVR However there is no reason the Propeller couldn t be programmed with a game or other application and ignore the commands on the agreed to SPI interface pins Therefore the Chameleon can be used as a stand alone AVR or Propeller controller if you wish However the point is to use them together than leverage their strong points the AVR s simple progr
438. take a look at the directories on the DVD ROM one level above These are shown in Figure 15 42 below Figure 15 42 Directory structure of the Arduino tools the DVD ROM 8 arduino Ld File Edit View Favorites Tools Help Bak QJ 27 x Search lg Folders Address le dvd v1 0 rev alicham avritools arduino Go msn libraries File and Folder Tasks linux mac sketches Other Places windows tools a My Documents Shared Documents 4 My Computer a My Network Places 0 bytes 4 My Computer Referring to Figure 15 42 you see the Windows Linux Mac directories which each contain a ZIP file or appropriate set of tools for the platform But there are two other directories that we are going to need in a moment LIBRARIES and SKETECHES These two directories are needed to augment the Arduino default installation so we can compile Chameleon programs with the Arduino tool The LIBRARIES directory has all the Chameleon libraries ported over to work with the Arduino tool very simple changes in most case and the SKETCHES directory has all the programs and demos from this manual in Arduino format for you Later in the installation am going to direct you to copy the contents of these folders into their respective locations in the Arduino installation directory This is important since you will perform this step on all three platforms Windows Linux Mac whiche
439. tallation With that in mind let s keep moving on with the installation of AVR ISP 80 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 1 2 Installing the AVR ISP Hardware Optional Now that AVR Studio is installed we could install WinAVR next but find that installation the programming hardware is a better idea so the drivers can load and it can register itself so that WinAVR will find it during its installation This way we don t get into a chicken and the egg problem and have to install something two times E Of course if you do not have a AVR ISP MKII then you can skip this section since you TIP are probably planning on using the pre flashed bootloader in Arduino mode over the USB serial connection Installing the AVR ISP MKII programmer consists of nothing more than plugging it into your PC with a USB cable Go ahead and do this now as Once you plug it in the PC should detect it and begin the installation process as shown in Figure 15 8 below Figure 15 8 Window s detecting the Atmel AVR ISP Found New Hardware Wizard Welcome to the Found New Hardware Wizard This wizard helps you install software for AVRISP mkll If your hardware came with an installation CD or floppy disk insert it now What do you want the wizard to do
440. tched 35 to the proper drivers running on other COGS Here s a visual of what s going on VGA_Text_010 spin Cemi Se gt Prop virtual SPI Interface ASM language 39 a a 2 lt 5 s ES gt TV monitor I L ee VGA driver gt VGA monitor Keyboard driver gt PS 2 keyboard 5 driver gt PS 2 mouse 7 driver Rudio amp or 49 50 drivers 51 52 55 57 CONSTANTS SECTION 59 CON R1 Propeller Source z j gt Close Object Info Form The Propeller IDE allows you to program the Propeller chip in its native BASIC like language called Spin as well as assembly language The editor has lots of features like syntax highlighting and code marking to help you keep things straight Spin uses tabs for block nesting so a little tricky if you re a BASIC or C C programmer and not used to spaces tabs indicating nesting In any event if you want to program the Propeller you will use Spin ASM primarily However there are 3 party C compilers a FORTH is avai
441. te machine xstate_running 0 end if break default break end switch end while if DEBUG XMODEM gt 1 sprintf sbuffer rDownload Complete r d Blocks NrFile Size d r xbytes read 128 xbytes read NTSC Term Print sbuffer Term Print sbuffer endif return bytes read return xbytes_read end xModem Receive All that conditionally compilation code is to help you modify the function to add features to it since this is really the only way to get data from the PC into the FLASH memory at the moment unless you make something yourself Alright now that you have an idea about X Modem protocol let s take a step back and see how we are going to send X Modem files from the PC Sending X Modem Files from the PC Sending X Modem files from the PC is almost the same as setting it up for serial communications that is you need a program capable of X Modem file transfer Luckily there many of them available but once again suggest that you use two of my favorites Absolute Telnet and ZOC which you can find online here Zoc http www emtec com zoc Absolute Telnet http www celestialsoftware net telnet Copies of them are also on the DVD ROM here DVD ROM CHAM AVR TOOLS COMMUNICATIONS For this example let s use Absolute Telnet Similarly you need to install the program then create a communications profile for your USB serial COM port but this time there is a difference
442. tents Overview eee eee ee eene eene ss tasses se set en seen ases sse 169 20 3 API Listing Reference 169 20 4 API Functional Declarations RR 169 21 0 LIBRARY MODULE PRIMER iiscisscccissscnccdcesicccdsevensaasedacntdsnsanidsnseewddeenesstuansanntdcudaestenniaana 171 21 1 Header File Contents Overview scscccsssscssssccsssecsssecsssecsssscssssessssscsssscssssessssessssesssssssssecssssessssessssscnssscossssssssessssssoeseoes 172 21 2 API Listing Reference 172 21 3 API Functional Declarations R 173 22 0 GFX LIBRARY MODULE PRIMER 175 22 1 GFX Driver Architectural Overview eee eee e eese eene ases setas etes 175 22 E GEX Driver Register Interface cae Dee eoo Hoe esta Decke cot Re Eee aee E Horses boned 180 22 2 Header File Contents Overview eee eee sees eene eene tenant ersa e seen aotsa saeua seno 180 22 3 API Listing Reference
443. the then wait e then wait etc But with interrupt driven architecture and the buffers the string is simply copied into the circular output buffer and the interrupt sends the string out for you The receiver is the same you can interrogate the circular buffer anytime you wish For example say that you know the transmitter on the other end is going to send a single string The World is Fine back to you This string fits into the circular buffer so you don t have to interrogate the buffer immediately and worry about loss of data You can finish you activities maybe a disk I O or some rendering then at your leisure call the receive function which will check the buffer for data and send it to you Referring to Figure 18 1 once again you can see some of the details of the system There are two functions similar to the C putc and getch called UART putc and UART_getc these functions directly access the transmit receive buffers for you Thus from a software perspective all the work of polling the transmission and reception hardware is taken care of for you and all you have to do is use these two functions and pay attention to their return values The Arduino uses similar serial methods from the serial class named serial begin TIP serial print serial read eic learn about them in the Arduino documentation So the idea of our UART module is that it loads up the ISRs for communi
444. the Chameleon API as well as the data sheet for the FLASH memory located on the DVD here DVD ROM CHAM AVR DOCS DATASHEETS Atmel AT26DF081A FLASH doc3600 pdf To use the FLASH is relatively easy you open the FLASH memory up then read or write then close it Basically four API calls to do everything However that s pretty boring so we decided to do something a little more interesting We were concerned that many newbies would have a hard time putting the FLASH to use since there isn t a direct way to access it from the PC For example if you could read and write files to it over the USB port that would be ideal Moreover if the Chameleon could act like a FLASH FAT drive that would be great But no one has written software to do that and that s a good 1 2 weeks work so if you re up to it please do However as a conciliation prize we developed a little X Modem protocol driver that allows you to download files of any type from the PC to the Chameleon into a RAM buffer Then you can do what you want with the RAM buffer like write it to the FLASH memory Figure 31 3 shows a flow diagram of what s going on 238 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 31 3 The various elements an X Modem file transfer Absolute Telnet any X Modem protocol program tnt modified AbsoluteTelnet 6 28 UNREGISTERED EVALUATION 7 days left BUY NOW courer new Chameleon AVR PI
445. the driver allows you to change the color The returned color value will be in Propeller color format chroma 4 bit chroma enable 1 bit luma 3 bit Example s Retrieve the current bottom overscan color int bottom overscan color GFX Get Bottom Overscan color Function Prototype int GFX Get Top Overscan Color void Description GFX Get Top Overscan retrieves the top overscan color of the NTSC driver The top overscan is a few lines at the top of the screen that no tiles are drawn into Usually this area is black on normal broadcasts of TV programs but the driver allows you to change the color The returned color value will be in Propeller color format chroma 4 bit chroma enable 1 bit luma 3 bit Example s Retrieve the current top overscan color int top overscan color GFX Get Top Overscan color Function Prototype int GFX Set Bottom Overscan Color int col Description GFX Set Bottom Overscan Color sets the bottom overscan color to col where col is in normal 193 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Propeller color format chroma 4 bit chroma enable 1 bit luma 3 bit Returns 1 Example s Read the current color and increment the chroma portion of the color upper 4 bits retrieve the color int color GFX Get Bottom Overscan Color now add 1 to the upper 4 bit nibble allow wrap around rather than clamp o
446. the following format 8 data low8 data high8 Where command8 is an 8 bit command code data low8 and data high8 are the operands for the command Thus each SPI packet is rather small and can t do much However with proper design you can use these small SPI command packets to create larger commands For example say you want a command to print a character to the VGA screen Well that s easy enough you can use a specific command code for print to VGA then a single one of the 8 bit data words can hold the 8 bit character But what if you wrote a sound driver that plays wav files and you want to send down 1000 bytes Well that s easy you just have to break the process into to states or steps and then create a command for each state For example you could create a memory write command that consists of 3 sub commands Command 1 Set memory pointer addr Command 2 Write memory mem with x So Command 1 needs a 16 bit address you can fit that in the two operand bytes and command 2 needs only a single 8 of data Thus you can write 1000 bytes from addresses 2000 to 2999 with this simple algorithm for mem addr 2000 mem addr 2999 mem_addr send_spi_command COMMAND1 mem_addr amp OxFF mem_addr gt gt 8 send_spi_command COMMAND2 data 0 end for As you can see the 3 byte SPI command packet isn t a limitation In fact most SPI and devices use 2 byte comman
447. ther than including the header in your program TIP 22 1 GFX Driver Architectural Overview The idea of the Chameleon is that you use other people s drivers make your own and change them as you need them on the Propeller side Thus we don t want to spend too much time explaining how any particular driver works since you will 175 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit probably change it However the NTSC GFX API is worth covering for a little so if you do want to create a game or something more graphical you can Please refer to Figure 22 1 for the following paragraphs will assume you have some experience in tile mapped graphics and game programming for the following explanations Figure 22 1 GFX Architectural Overview Flow Diagram tilemap ptr Virtual Width 32 64 128 256 powers of 2 Tile 0 0 Virtual Height en 24 Rows UC 32x24 Tiles Each tile is composed Physical View i 2 bytes The upper byte is the palette index the lower byte is the tile index Palette Tile i index Index i High Byte Low Byte M palettes ptr ge tile bitmap ptr ud PaletteO selects color Each bitmap is 8x8 pixels Color 0 00 Each pixel is 2 bits 1 01 Each 2 bit pattern refers to 2 10 a color in the palette for that gt 3 11 Color Palette index from each tile 1 01 selects which palette to use 2 10 for 4 color set 3
448. ticore processor with a very simple design and programming model Referring to Figure 1 8 take a look at the block diagram of the chip The Propeller chip consists of 8 symmetrical processing units cores that are identical Each core has a 32 bit CPU 512 32 bit words of memory a pair of counters and a crude video streaming unit The cores run at 80MHz nominal and take 4 clocks to execute an instruction Therefore each core is capable of running at 20 MIPs Additionally each core has access to the 32 I O pins of the chip as well as a shared 32K Byte RAM and 32K Byte ROM Access to the RAM is arbitrated by a hub that gives each core access to the RAM in lock step thus its impossible for one core to access RAM while another core is thus no potential for corruption of memory For complete details on the processor please review the datasheet located on the DVD ROM here DVD ROM cham_avr docs datasheets PropellerDatasheet v1 2 pdf Referring to the pinout of the Propeller as shown in Figure 1 9 the philosophy of the Propeller is to keep things really simple therefore there are no peripherals other than the video hardware on the chip The idea is that if you want a SPI port UART D A A D etc you will write one with pure software and run it on one of the cores as a virtual peripheral Therefore chip space and silicon aren t wasted on peripherals you will never use Rather the Propeller is 100 programmable and you simply loa
449. ticular driver running on the Propeller side is the only features we can access via the AVR side That doesn t mean we can t abstract functionality and add higher level functions that build on the sub functions however this probably isn t productive since you will want to change drivers re write the Propeller driver and so forth Thus for the majority of the media IO drivers all the API functions do including the Mouse is expose some of the base functionality in nice function calls so you don t have to send SPI messages yourself Now the one thing about mice and keyboards is they are really SLOW thus its typically a problem reading them since your CPU has to slow down to do so therefore its really nice for a core on the Propeller to completely handle the mouse for you For the mouse we decided to use a base driver from the original Propeller objects development that was designed to communicate to a standard PS 2 mouse nothing fancy The same driver is used in both Default and Default2 so the same idea apply to either driver you load on the Propeller CHAM_DEFAULT1_DRV_112 SPIN or CHAM_DEFAULT2_DRV_112 SPIN The actual driver object used for the mouse is mouse_010 spin Basic PS 2 mouse driver originally written by Parallax 200 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit However only exposed a portion of its abilities thru the current SPI messages no need to waste messages You can alwa
450. tile bitmaps unsigned int GFX Write Bitmap Ptr unsigned int bitmap ptr Writes the pointer to the tile bitmaps De ee ee Scrolling functions ERES int GFX_Get_HScroll void Not implemented int GFX_Get_VScroll void Retrieves the vertical smooth scroll value int GFX_Set_HScroll void Not implemented yet int GFX_Set_VScroll int vscroll Sets the vertical smooth scroll value eee Memory port functions ee 1 8 unsigned int GFX_Read_Mem_Port8 void Reads Propeller memory 8 bit port int GFX_Write_Mem_Port8 unsigned int data Writes to the Propeller memory 8 bit port ed unsigned int GFX_Read_Mem_Port16 void Reads the Propeller memory 16 bit port unsigned int GFX_Write_Mem_Port16 unsigned int data Writes the Propeller memory 16 bit port E _ ee Oe ee oa Sn Source and destination pointer access a ee ee ee unsigned int GFX_Get_Src_Ptr void Retrieves the source GPU operation pointer unsigned int GFX Get Dest Ptr void Retrieves the destination GPU operation pointer one unsigned int GFX_Set_Src_Ptr unsigned int src_ptr Sets the source GPU operation pointer unsigned int GFX Set Dest Ptr unsigned int dest ptr Sets the destination GPU operation pointer SEEN GN AEN SSeS Tilemap width functions 2 2 int GFX_Get_Tilemap_Width void Retrieves the width of the tilemap in encoded format
451. ting is a simple matter of changing a couple function calls below in Table 27 1 is a quick list of the function call mappings for the serial calls Table 27 1 Chameleon AVR vs Arduino Serial UART Library Mapping CHAM AVR UART DRV 010 Arduino Serial Library Version Function Name Function Name SE E int UART_Init long baudrate Serial begin baudrate 208 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit void UART_Print_String char string Serial print data Serial println data int UART_putc unsigned char ch Serial print data int UART getc void Serial read You will notice that the right side Arduino functions that there no data types as the parameters This is because this is an overloaded C class with overloaded data types Thus you can send characters strings numbers etc to the print and printin functions Therefore to port in either direction you just replace the functions with their counterparts and maybe a cast or two and you re done 27 1 2 Setup for AVRStudio Version of Demos The AVRStudio of the demos are relatively straightforward to setup We have already covered how to setup AVRStudio to compile build a FLASH image and download with the AVRISP MKII programmer Thus for each of the demos all you need to do is add the source C files to the project along with the main program and build the program and download All the source API libraries fo
452. tion dialog is straightforward and mostly redundant of course want to install the files In any event simply check all checkboxes and then click Install to initiate the installation process The installation progress dialog should display as shown in Figure 15 16 below 84 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 16 WinAVR installation progresss dialog amp WinAVR 20080610 Setup uo Installing Please wait while WinAVR 20080610 is being installed 2 Extract libc a lt Next gt Cancel The installation is rather quick under a minute When complete the installation finished message box will display click lt Finish gt to complete the process and you can stop holding your breath Figure 15 17 WinAVR successfully installed amp WinAVR 20080610 Setup uo Completing the WinAVR 20080610 Setup Wizard WinAVR 20080610 has been installed on your computer Click Finish to close this wizard Cancel 85 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit 15 1 4 Building a Project and Testing the Tool Chain Congratulations you have installed the tool chain and if you are still with me then everything must have went correctly At this point we have to set up the tools themselves which includes a lot of detail highly recommended you first skim over this secti
453. tions Games and Languages When developing any product we always like to give a select few master programmers the hardware early to see what they come up with Not only is this a good way to find potential bugs in the hardware but its interesting to see what some of the best programmers in the world can do with it For this release of the Chameleons we have a couple applications that will be very useful to you 35 1 1 Chameleon BASIC by David Betz Figure 35 1 A BASIC Life program running on the Chameleon The Chameleon BASIC is a complete compiled BASIC that runs on both the Chameleon AVR and PIC platforms Figure 35 1 shows an example of a Life cellular automata running written in BASIC You write your programs on the PC with and editor then download to the Chameleon The Chameleon runs a VM virtual machine that executes the compiled byte codes You can find the latest copy of BASIC on the DVD here DVD ROM CHAM AVR SOURCE BASIC Simple locate the newest directory version and everything you need to get BASIC up and running is in there including documentation the compiler examples etc 35 1 2 Crate It by JT Cook Figure 35 2 Crate it running on the Chameleon AVR Hat Enter www chameleon dev com lla els by Hiroyuki Imabay 255 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Crate It shown in Figure 35 2 is used for the Chameleons as the Quick Start de
454. to older versions Please contact Nurve Networks LLC for any questions you may have Visit www xgamestation com amp www chameleon dev com for downloads support and access to the Chameleon user community and more For technical support sales general questions share feedback please contact Nurve Networks LLC at support nurve net nurve_help yahoo com 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Exploring the CHAMELEON AVR 8 Bit User Manual and Programming Guide LICENSING TERMS 8 CONDITIONS rk cer n re rx cx irl ist ne cati e ic Cio irc ig rl 3 VERSION amp SUPPORT WEB a rd 4 EXPLORING THE CHAMELEON AVR 8 BIT USER MANUAL AND PROGRAMMING GUIDE 5 0 0 INTRODUCTION AND ORIGINS au accendi sick ad exte Cam ra E eed ndis ed dir dob 11 1 0 ARCHITECTURAL OVERVIEW nina aco carni dai rana tura dada rara ER XX Rada RE DUM REX da air aus 13 1 1 Package Contents 15 1 2 Chameleon AVR Quick Start Demoo ecce eee eee ete eas assess eee essen assesses esee esas a sese e eese sese esee sena 16 pic EET 16 Playing LE 17 1 3 The Atmel Mega AVR328P Chip sscsssccssssccssecsssecssssessssssssscssscssssssssessssecsssssssssessssssssscsssscsss
455. trouble Alas in the next few paragraphs and screen shots we are going to painstakingly setup every single little detail The number one problem with using tools like this is the setup so take your time it will pay you back in hours or days of frustration Referring to Figure 15 24 there is a lot going on with this tool interface First there are a number of categories on the left that can be selected such as General General settings across the compiler Include Directories Sets various search directories for the compiler Libraries Add remove libraries that the linker might need Memory Settings Manipulate the initial memory configurations of the AVR Custom Options Set flags and controls for the tools like GCC and MAKE We aren t going to need to make changes to all the tool settings but nonetheless highly recommended that you view all of them and read about them in the documentation and help since these settings control everything In any event let s begin with the General settings as shown in Figure 15 24 Make sure the General tab is set on the left hand side and highlighted First off at the top of the tool under Active Configuration we are altering the default configuration so make sure that s selected properly Next make sure Use External Makefile is un checked For those that aren t familiar with command line tools Make is a tool that reads in a Makefile containing commands for everything from the co
456. ty rights law moral rights law trade secret law trademark law unfair competition law or other similar protections regardless of whether or not such rights or protections are registered or perfected the Intellectual Property Rights in the computer software and hardware together with any related documentation including design systems and user and other materials for use in connection with such computer software and hardware in this package collectively the Licensed Works ALL INTELLECTUAL PROPERTY RIGHTS IN AND TO THE LICENSED WORKS ARE AND SHALL REMAIN IN LICENSOR RESTRICTIONS a You are expressly prohibited from copying modifying merging selling leasing redistributing assigning or transferring in any matter Licensed Works or any portion thereof b You may make a single copy of software materials within the package or otherwise related to Licensed Works only as required for backup purposes c You are also expressly prohibited from reverse engineering decompiling translating disassembling deciphering decrypting or otherwise attempting to discover the source code of the Licensed Works as the Licensed Works contain proprietary material of Licensor You may not otherwise modify alter adapt port or merge the Licensed Works d You may not remove alter deface overprint or otherwise obscure Licensor patent trademark service mark or copyright notices e You agree that the Licensed Works will not be shipped transferr
457. u need to copy the source files from the DVD ROM into Additionally note that there are some external project files at the end of the listing with the extensions APS and AWS these are the Project Files themselves and contain all pertinent settings paths and other information for AVR Studio to load them up Thus if you ever want to copy a project you have to copy these files as well as the project directory itself Of course just copying the files isn t going to be good enough since there are hard coded paths in them but they are there if you want to play with them To copy the source files from the DVD ROM you simply need to drag or copy the contents of the directory SOURCE located on the DVD ROM here DVD ROM CHAM AVR SOURCE Into the project directory on your hard drive cham avr work 01 This way we will have all the sources in a single directory which will make organization and finding things a lot easier True the directory will have a lot of files in it but that s better than dozens of directories with copies of everything Go ahead and copy the files now from the DVD Now we are ready to add some files to our project and compile something The first step is to gain access to the file adding mechanism Like all IDEs there are a couple ways to do this but the most straightforward is to highlight the Source Files folder under the project tree and right click the mouse to get a context menu This is shown in Figure 15 29 belo
458. ually the decimal value 27 This sequence is called CSI for Control Sequence Introducer or Control Sequence Initiator There is a single character CSI value 155 or Ox9B hexl The ESC two character sequence is more often used than the single character alternatives Devices supporting only ASCII 7 bits or which implement 8 bit code pages which use the 0 80 0 9 control character range for other purposes will recognize only the two character sequence Though some encodings use multiple bytes per character in this topic all characters are single byte You can run a terminal program on the PC in ANSI mode and then send these commands to it from the Chameleon ANSI Codes Most Popular Name CSInA Moves the cursor n default 1 cells in the given direction If the cursor is already at the edge of the screen this has no effect CUU Up CUD Down CUF Forward CUB Back Moves cursor to beginning of the line n default 1 lines down next line Moves cursor to beginning of the line n default 1 lines up previous line CSIn mH CUP Moves the cursor to row n column m The values are 1 based and default to 1 top left corner if omitted A sequence such as CSI 5H is a synonym for CSI 1 5H as well as CSI 17 H is the a same as CSI 17H and CSI 17 1H CSI n J ED Clears part of the screen If n is zero or missing clear from cursor to end of screen If n is one clear from cursor to beginning of the screen If n is two clear
459. ue the installation process Figure 15 5 AVR Studio extra installation features dialog InstallShield Wizard tup will install Select the features you want to install anc features you do not want to install 2 InstallShield Figure 15 5 shows the AVR Studio features installation dialog As you can see there s not many features Actually they all come by default In any event select the USB driver upgrade to save you the time of installing it later This option includes the needed driver for any external USB based programmer debugger which we need Press Next and the final installation confirmation dialog will display as shown in Figure 15 6 79 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 6 AVR Studio final installation dialog the Program The wizard is ready to begin installation Click Install to begin the insta ur installation settings click Back Click Cancel to exit the InstallShield Unless you want to go back and make changes simply press lt Install gt and the installation will begin If all goes well then the installation complete message box will be displayed as shown in Figure 15 7 Figure 15 7 AVR Studio installation complete message box Install Shield You re probably thinking that was easy agree but installation isn t really the hard part it s the setup of the tools after ins
460. ulator is of some use but you will find its capabilities limited Moreover it only simulates the processor not any the hardware connected to it Thus in the future you might want to purchase the AVR JTAG ICE debugger or other similar 3 party tool 87 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Moving on click lt Finish gt once you have the Debug Platform filled out appropriately This should open AVR Studio up to its default view which we might need to make adjustments to so the correct tools are displayed Take a look at Figure 15 21 below to accomplish this Figure 15 21 Selecting the active tools in AVR Studio AVR Studio File Project Build Edit View Tools Debug Window Help Standard Toolbar drip o gt 52 5 s OB Q 4 iz d S DF tree disabled ee Bi Edit VO View Debug gt Debug Windows Vane MDI Tabs D AD_CONVERTER AVRGCCPLUGIN E T ANALOG_COMPARA STK500 Ecru cane EJ EEPROM QEXTERNAL_INTERR yo PORTB Processor E Ponte PORTD Build Output Ses Message Output S TIMER COUNTER 0 S TIMER COUNTER 1 S TIMER COUNTER 2 B J USARTO Z2 WATCHDOG 5 98 cham avr work 01 defa Source Files Header Files 2 External Dependencie Other Files JE Es Es ls ES E e Es Hs ls DE Find Output Address Bits
461. vO10 h Description NTSC UGR demo of Hello World P CHAM AVR SYSTEM V010 h Zz CHAM_AVR_TWI_SPI_DRV_VO10 h Overview Simply prints out Hello World to the NTSC and UGA screens in a few lines of code E CHAM_AVR_VGA_DRV_VO1O h 23 External Dependencies vi Other Files INCLUDES RUR RTmega328P _ 168_ idefine __AUR_ATmega328P__ include everything include lt stdint h gt include lt stdio h gt iinciude lt stdlib h gt include lt string h gt tinclude lt cetype h gt ttinclude lt avr eeprom h gt include lt avr io h gt 3 lt aur sleep h gt 3 lt util delay h gt include lt avr interrupt h gt 3 lt avr pgmspace h gt include lt inttypes h gt include lt compat twi gt include lt aur udt h gt include headers required for demo include CHAM_AUR_SYSTEM_U616 h 7 you need this one always include CHAM_AUR_TWI_SPI_DRU_U616 h you need this always include CHAM_AUR_NTSC_DRU_U616 h needed for NTSC driver iinclude CHAM_AUR_UGA_DRU_U616 h n
462. ve out Now there are a couple problems with this first its not readily apparent how to add signals and play more than one sound at once In fact it s nearly impossible directly using this technique Secondly the only signal you can output is a square wave you can t out put sine waves This tends to make the sounds have a textured sound since harmonics are in the square wave That is if you output a square wave at frequency f then you will find that there are harmonics at 3f 5f etc all these sine wave are what really make up a square wave Take a look at Fourier transform theory to see this http homepages inf ed ac uk rbf CVonline LOCAL COPIES OWENS LECT 4 node2 html Of course our little low pass filter is going to filter most of these harmonics but you aren t going to hear a pure sine until you increase the frequency to about the 3dB cutoff which maybe desired In any event if all you need is a single channel some noise pure tones then FM with the AUDIO MONO port at P24 is more than enough You can use software or the built in timer in PWM mode to accomplish this as well but you won t have any control over amplitude since you would be running the output at audio frequencies and not at PWM frequencies 14 1 3 Pulse Width Modulation PWM Pulse width modulation or PWM is a very clever way to create any kind of sound with a single bit of output The bad news is that the generation of the output and the algorithms needed are
463. ven though the Arduino folks call the language Processing its just good old C C The tool of choice for native AVR development is of course AVR Studio This tool was developed by Atmel and supports source level debugging various programmer and ICE debuggers etc However the C C compiler is a plug in based on GNU GCC called WinAVR We will discuss the installation of the tool chain shortly but keep in mind the separation Additionally we will be using straight for coding C is supported but due to its overhead and lack of 100 support for embedded applications we will avoid it C is much more compatible with all embedded systems and C is just asking for trouble especially with the compiler Figure 1 7 Atmel AVR Studio 4 in action File Project Build Edit View Tools Debug Window Help 1 c 4 BAG SW 44 64 9 AVR GCC x avr test default return success Source Files 1 E CHAM AVR FLASH VO10 c i sj i d 9 OH 9 Ss 111 1 trace Disabled e e BS x E CHAM_AVR_GFX_DRV_VO10 c gt end ottom 00 CHAM AVR KEYBOARD DRV VO10 c E AVR MOUSE DRY VO10 c E CHAM AVR NTSC DRV VD10 c CHAM AVR PROP PORT DRV VO10 c E CHAM AVR SOUND DRV V010 c E CHAM AVR SYSTEM VOID c CHAM AVR
464. ver you are using 15 2 2 Copying the Files to Your Hard Drive Go ahead and locate the main ZIP file on the DVD named DVD ROM CHAM AVR TOOLS ARDUINO WINDOWS arduino 0017 zip And decompress it into your development directory do all my work in a directory called SOURCE on my computer and this is where you should have copied all the C H files in previous installation steps Go ahead and create a directory called ARDUINO inside SOURCE then decompress the ZIP file right inside the ARDUINO folder and enable directory names This way the unzip will create a sub directory named ARDUINO 0017 for you Then in the future as you get new versions of the tool you can do the same and keep them organized if you want to roll back Thus you should have something that looks like the directory structure shown in Figure 15 43 when done 107 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 15 43 Setting up the main directory for the Arduino tool chain amp arduino AS Fie Edit View Favorites Tools Help Bak CJ C Search Folders 7 Address DB D development chameleonicham_avr sourcetarduin Go msn Cj arduino 0017 File and Folder Tasks sketches Other Places source My Documents Shared Documents 4 Computer 44 My Network Places O bytes 3 Computer Referring to Figure 15 43 you will see there is a SKETCHES directory i
465. w Figure 15 29 Adding source files to the project AVR Studio File Project Build Edit View Tools Debug Window Help Show File Paths 9 3 Head Edit Configuration Options E CHAM_AVR_NTSC_DRV_VO10 h t CHAM AVR SYSTEM V010 h t CHAM AVR TWI SPI DRV V010 h 5 CHAM AVR DRV VO10 h External Dependencies Other Files 95 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Clicking the Add Existing Source File s selection will launch a standard Window s file browser navigate it into the project directory with all our recently copied files and then add the following files to the project Drivers CHAM_AVR_SYSTEM_V010 C This is the main system file that is needed for all applications CHAM_AVR_TWI_SPI_DRV_V010 C This contains the SPI software API needed for all applications CHAM_AVR_NTSC_DRV_V010 C This contains the NTSC API wrapper CHAM_AVR_VGA_DRV_V010 C This contains the VGA API wrapper Of course each of the above C files has an associated H file These must be added to the project as well in the headers section or make sure the tool has the path to them so after you add the C files to the project s Source Files folder then add the associated header files to the Header Files folder Main Program CHAM_AVR_HELLO_WORLD_01 C The demo program that prints Hello World to both the NTSC and VGA monitors This of course does not have a header f
466. w its complete path from the AVR to the Propeller to the media driver itself The next subset of commands are specific to the default2 driver and support the added graphics abilities of the tile map engine for NTSC modes wrote the tile engine to give you more performance and the ability to do some game like applications These commands are more complex and it will take a bit to explain them but for now just peruse them below 159 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit d d d d efine efine efine efine GPU_GFX_BASE_ID GPU_GFX_NUM_COMMANDS advanced GFX commands for GFX tile engine 192 37 GPU GFX SUBFUNC STATUS 0 GPU GFX BASE ID command like copy fill etc GPU GFX SUBFUNC STATUS W GFX BASE ID command like copy fill etc starting id for GFX commands to keep them away from normal command set number of GFX commands Reads the status of the GPU Writes the GPU Sub Function register and issues a high level Writes status of the GPU writes the GPU Sub Function register and issues a high level sub function constants that are executed when the GPU GFX SUBFUNC STATUS W command is issued define GPU GFX SUBFUNC COPYMEM16 0 Copies numbytes from src gt dest in wordsize chunks define GPU GFX SUBFUNC FILLMEM16 1 Fills memory with datal6 2 bytes at a time define GPU GFX SUBFUNC COPYMEM8 2 Copies numbytes fro
467. w will source current if the pull up resistors are activated The Port C pins are tri stated when a reset condition becomes active even if the clock is not running Note even though Port C only has 7 pins bonded out on the chip the port register is still 8 bits wide but the 8 bit is simply ignored Port D PD7 PDO Port D is an 8 bit bi directional I O port with internal pull up resistors selected for each bit The Port D output buffers have symmetrical drive characteristics with both high sink and source capability As inputs Port D pins that are externally pulled low will source current if the pull up resistors are activated The Port D pins are tri stated when a reset condition becomes active even if the clock is not running Port D also contains the UART signals 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit RESET Reset input A low level on this pin for longer than the minimum pulse length will generate a reset even if the clock is not running XTAL1 Input to the inverting Oscillator amplifier and input to the internal clock operating circuit XTAL2 Output from the inverting Oscillator amplifier VCC Main power 5V GND System ground AVCC AVCC is the supply voltage pin for the Analog to digital Converter It should be externally connected to VCC even if the ADC is not used If the ADC is used it should be connected to VCC through a low pass filter AREF This is the analog referenc
468. widtli 2 2 nde Ie b ge te pere PER eia 135 16 3 3 Our Summplitied Strategy dee o a d noa Hb Hee bti 135 16 4 Virtual Peripheral Driver Overview eene tenet een natns sten sse tns setas etes sees s sess sess s es ens sense 136 16 4 1 Normalization of Drivers for Common RPC Calls in 137 17 0 CHAMELEON AVR API OVERVIEW n nnns nnne antenne 137 17 1 Library amp 142 15 1 1 Header File Contents Overview iets 21 5 nie gene HC e e EE 142 IT L2 APELas ng Reference 12 ini in tee Ue E GEHE EO UE ER RUE EO LATER LU Eti HELL Re Eee Ha ESL LE do 143 17 1 3 API Functional Declarations iiciin aaite eiere eaei oaae ea ae kaar ro eaae iaeei Ci oisit 144 18 0 UART AND RS 232 LIBRARY MODULE 145 18 1 The Architecture of the UART API Library and Support Functionality eeeseesseesoeesoeesoeesoeesoeesoessoesooesoeesoeesoeesoeesoeesosesoe 146 18 2 Header File Contents Overview sscsssccsssccssecsssecssscessssescssscsssscssssessssessssscnssecssssenssssssssscsssscnssscssssesssssccssosssscosssoosees 147 18 3 Li
469. with a simply subset of commands where used In the sections below we will cover the exact drivers used but the point is they were chosen more or less for ease of use and user base 131 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 16 3 Another view of the complete system dataflow model CORE 1 COG 1 AVRIPIC Processor Running main app lication as master Virtual SPI Interface CORE 0 COG 0 This process starts first and then launches the ASM SPI driver on Core 1 Driver Layer Each object running on its own core p I O devices gt BSMJSASSMYR gt Messages passed to drivers Each object running on via sub function calls another core 16 2 1 Complete Data Flow from User to Driver Now that you have seen all the pieces of the puzzle from a hardware and software point of view let s review exactly how these pieces all fit together To begin with the Propeller is running a number of drivers on multiple cores NTSC graphics terminal VGA graphics terminal keyboard mouse driver and sound driver Each one of these drivers takes a single core Now by themselves they don t do much So the glue of the system is the MCP which is pure SPIN program that not only issues commands to the drivers but is the interface to the AVR via the virtual SPI driver s shared memory Thus the MCP runs on its own core controll
470. write operation really is a read operation and each read a write Confusing huh Well its due to the circular buffer the system uses You might ask what if you want to read something how can you write something when you are trying to read The answer is that when you want to read data you simply put a dummy value usually OxFF in the transmit buffer which the Slave will ignore Same thing when you are writing data and not reading The receive buffer will have some data in it after you write a byte but you can ignore it Thus in operations that write and read at the same time full duplex in other words you get 2 pieces of data at the same time this is the beauty of SPI in full duplex mode 2x the clock rate for intent purposes But if you are only writing or reading at any time then this feature is irrelevant Moving along the function takes a single parameter data8 which is the data you want written to the SPI interface The function returns the data received after the data you sent is transmitted In other words the function waits for the 8 bits you sent to shift out as it shifts in the new 8 bits from the Slave Thus the data in the receiver buffer from the previous transaction is lost Moreover the function is a blocking function and the transaction must complete before the function returns Of course you can code your own variations that just dump the data into the transmit buffer and return But then you would need a status function to
471. x Propeller multicore processor 32K RAM 32K ROM QFP 44 Pin package running at 80 MHz per core with 64K Byte serial EEPROM for program storage 2x required memory RCA Video and Audio Out Ports HD15 Standard VGA Out Port Single PS 2 Keyboard and mouse Port Single 9V DC power in with regulated output of 5 0V 500mA and 3 3V 500 mA on board to support external peripherals and components the AVR 328P is 5V Propeller is 3 3V Removable XTALs to support faster speeds and experimenting with various reference clocks Expansion headers that exposes I O power clocking for both the AVR and Propeller USB UART built in with Mini B connector 6 PIN ISP In System Programming interface compatible with Atmel AVRISP as well as other 39 party programmers 1 MByte of SPI FLASH storage chip that can be used as local storage or a full FAT file system Break Away experimenter prototyping board that can be snapped off for prototyping and adding extra hardware to the Chameleon 13 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit Figure 1 1 Chameleon system level diagram NTSC TV VGA Monitor FE n Emulator PC is running tools such as the Propeller IDE AVRStudio B and Arduino IDE Local Mouse AUDIO vcA reme PS 2 Keyboard or Mouse SEE Serial packets to i z a lt H VT100 Custom etc EEE Processor H Mouse E SPI Intertece USB
472. xbytes_read 128 read the checksum while 1 ch UART_getcQ if 1 ch CHR_CTRLZ break end while xchecksum ch if DEBUG_XMODEM gt 2 NTSC Term Char OxOD sprintf sbuffer Checksum Sent d Calc d r xchecksum xchecksum computed NTSC Term Print sbuffer NTSC Term Char OxOD endif send the ACK test if packet was good later xstate XSTATE_SEND_ACK break case XSTATE_SEND_ACK packet was good please send another if DEBUG_XMODEM gt 2 NTSC Term Print XSTATE SEND NTSC Term Char OxOD NTSC Term Print S ACK NTSC Term Char OxOD _ 1 ms 100 endif send ACK and wait UART putc CHR_ACK _delay_ms 100 wait for a packet xstate XSTATE RECEIVE PACKET break Case XSTATE EOT possible end of transmission 1 if DEBUG_XMODEM gt 2 NTSC_Term_Print XSTATE_EOT NTSC Term Char OxOD NTSC Term Print S NAK NTSC Term Char OxOD endif send NAK wait for another EOT UART_putc CHR_NAK wait for result while 1 ch UART_getcQ if 1 ch CHR_CTRLZ break end while 242 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit test for final EOT if ch CHR_EOT final EOT send ACK finish UART_putc CHR_ACK if DEBUG_XMODEM gt 2 NTSC Term Print S ACK NTSC Term Char OxOD endif exit sta
473. xlist com TECHREF io video ntsc htm http www bealecorner com trv900 tech RS170A jpg http www bealecorner com trv900 tech http www maxim ic com appnotes cfm appnote_number 734 In en http pdfserv maxim ic com en an AN734 pdf 12 0 Keyboard amp Mouse Hardware PS 2 keyboards and mice are very similar from a hardware interface point of view The interface is a simple serial system with two lines DATA and CLOCK Both lines are open collector thus each end point typically can drive the line LOW but there is a pull up that pulls the line s HIGH Also PS 2 interfaces are 5V so when interfacing to a 3 3V system then some voltage translation must be performed Additionally we are interfacing the PS 2 port directly to the Propeller chip and since it s a 3 3V device care must be taken Figure 12 1 The Chameleon AVR keyboard and mouse interface hardware PS2 DATA T PS2 CLOCK T2 Female Computer Side 6 PIN MINI DIN As noted above the keyboard and mouse are controlled via two bi directional data lines CLOCK and DATA To interface to the Propeller a pair of I O lines are all that is needed It would be nice if the serial protocol for keyboards and mice was identical to RS 232A then things would be a little easier and we could use one of the Propeller serial drivers but the hardware and protocol is slightly different so we have to use I O pins and write our own driver Or use one of the mouse keyboard drive
474. xt The following lists each function a description comments and example usage of the function Function Prototype int NTSC ClearScreen void Description ClearScreen simply clears the NTSC terminal screen and fills the screen with spaces Returns 1 Example s Clear the screen NTSC Clearscreen Function Prototype int NTSC GetXY int x int y Description GetXY returns the position column row of the virtual cursor Depending on the driver 169 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit you are using the x y values have different possible ranges For the Default2 driver they are 0 31 0 23 The function takes two pointers to the integer variables you want to receive the values Returns 1 Example s Retrieve the current cursor position int x y NTSC GetXY amp amp y Function Prototype int NTSC SetXY int x int y Description SetXY sets the current cursor position on the NTSC terminal screen The position ranges depend on the driver but for Default2 they are 0 31 0 23 Returns 1 Example s Read the current cursor position and then move the cursor one position to the right int X y NTSC GetXY amp x amp y NTSC SetXY 1 y Function Prototype int NTSC Term Char char ch Description Term prints an ASCII character to the NTSC terminal
475. y API we provide here only scratches the surface of what you can do with the USART hardware They can even be used to stream audio or video data if you are really creative since they are more or less interrupt driven high speed shifting devices In any event let s talk about some preliminary materials 145 2009 NURVE NETWORKS LLC Exploring the Chameleon AVR 8 Bit before we begin You should review the data sheet on the AVR 328p especially the USART The data sheets is located here on the DVD DVD ROM CHAM_AVR DOCS DATASHEETS ATMega48 88 168 328 doc8161 pdf And here are some application notes specifically on using the USART DVD ROM CHAM_AVR DOCS WHITEPAPERS avr_uart_doc2547 pdf DVD ROM CHAM_AVR DOCS WHITEPAPERS avr_usart_spi_doc2577 pdf Finally the UART and RS 232 API libraries are contained in the following files CHAM_AVR_UART_DRV_V010 c Main C file source for UART and RS 232 module CHAM_AVR_UART_DRV_V010 h Header file for UART and RS 232 module ARDUINO TIP 18 1 The Architecture of the UART API Library and Support Functionality The UART library is relatively complex in as much as to save you a lot of grief trying to program the AVR USARTs we wanted to give you some ready to go software and API functionality so you could perform basic serial and have some fun To that end we developed a buffered interrupt driven UART communications system with some moderately
476. ys add more Therefore the abilities you see exposed in the following API are just a taste of what it can do In other words if you need more functions that the driver supports then you will have to add messages to the SPI driver and add them yourself With that in mind if you want to use the mouse driver then you need the following files added to your project CHAM AVR MOUSE DRV_V010 c file source for Mouse module CHAM_AVR_MOUSE_DRV_V010 h Header file for Mouse module Mice typically have two axes and a number of buttons The two axes X and Y are decoded as they move either mechanically roller mice or optically Inside the mouse is a microprocessor that actually handles all the decoding and sending of the information There are two ways that mice send messages absolute and relative In absolute mode the X Y position is accumulated and in relative mode the mouse sends the current change from the last positions Additionally mouse have sensitivity settings that you can control that slow or speed the relative mouse message values to the surface they are moving on Finally some mice have a Z axis which is usually the scrub wheel this is just like the X Y Finally the mice have a number of buttons these are encoded by the mouse as simple switches There is a whole mouse message API that most mice respond to but for our purposes we will let the Propeller driver deal with it All our API needs to do is cal
477. ytes to the Propeller is as simple as setting up a few registers and writing some bytes However the Propeller has no SPI hardware so we had to write drivers that emulate the SPI protocol with software This means there are limits to the speed you can send SPI traffic as well as the software SPI drivers are not very robust they are just starter drivers for you suggest you improve them As an example of how the system works let s say you have a AVR C C program you developed with AVRStudio or maybe the Arduino tool It has a A D convertor and measures temperature The temperature is then sent out to a crude LCD screen and looks ugly Also there are some controls for the program that you must use some external push button switches to set but it would be nice if you had a keyboard or mouse for user input This is no problem for the chameleon You would take you original program compile it for the Chameleon then add a few lines of code from our NTSC or VGA API that command the Propeller to draw text on the screen Then you can print out your temperature information nicely on a little NTSC VGA monitor Moreover you can write some simple GUI controls so with the mouse or keyboard you could make command selections on the NTSC VGA screen Very slick As another example you can use the Chameleon s built in USB serial port to communicate to the PC So say you want to control some motors or do some A D but you want the PC to take that informat

Download Pdf Manuals

image

Related Search

Related Contents

Curtis Sylvania  MEJORE SU POSTURA. MEJORE SU SALUD      VTech ML17939 telephone  CSA - Bandi on-line  Betriebsanleitung Enthärtungsanlage WINNI-mat® VGX  Medidor de aislamiento  Laundry Presses Installation Manual  5.2MB  

Copyright © All rights reserved.
Failed to retrieve file