Get JBit at SourceForge.net. Fast, secure and Free Open Source software downloads

[ Home | Documentation | Gallery | Download | Demo | GameKit ]
[ Index | Tutorial | Sheets | Pack | JB | Hello | Paint | MicroIO ]

Doc (Tutorial)

[ English | Italian | Spanish ]

In lavorazione...

VM

JBit e' un ambiente di programmazione completo ed e' piu' complicato di una tipica applicazione per cellulari. Questo tutorial ti assistera' nei primi passi dell'uso di JBit.

La prima cosa da capire e' che, quando stai scrivendo un programma usando JBit, non stai scrivendo un programma per il tuo cellulare, ma per la JBit Virtual Machine (MicroIO Edition), o VM.

Qui c'e' un'immagine della VM e come puoi vedere assomiglia a un brutto cellulare. Ora, la VM potra' anche essere brutta, ma di sicuro non e' un cellulare. Innanzi tutto, con la VM non puoi fare o ricevere chiamate, ne spedire o ricevere SMS. Inoltre il display puo' mostrare solo una matrice di 10x4 caratteri e il tastierino supporta solo i tasti standard (ovvero: 0-9, * e #).

Visto che la VM non puo' fare le cose di un cellulare, a che cosa puo' essere utile? Beh,a dire il vero quasi a niente. Pero' imparare a programmarla puo' aiutarti a capire come funzionano i computer. I computer sono macchine complicate e il loro nucleo e' nascosto da molti livelli di astrazione, ma alla fine hanno un nucleo che non e' molto piu' complicato della VM.

Main Menu (Editor)

Un'altra cosa da capire e' la differenza tra la VM e JBit. JBit include la VM, ma non e' solo quella. Include anche strumenti per aiutarti a scrivere e organizzare programmi per la VM.

A dire il vero, non puoi accedere alla VM senza prima avere scritto un programma per essa. Infatti, la VM non ha niente di paragonabile al Desktop; e' completamente vuota. Quindi il nostro primo compito sara' quello di scrivere un programma minimo, in modo da poter dare uno sguardo alla VM.

Seleziona Editor dalla lista.

New

L'Editor ha bisogno di sapere quanto e' grande il programma. Per ora non ci interessa e quindi possiamo semplicemente confermare 4 Code Pages (it. Pagine di codice) e 3 Data Pages (it. Pagine dati).

Seleziona OK (o Conferma, o simili).

In alcuni cellulari OK e' assegnato direttamente a un tasto, mentre in altri OK e' disponibile usando un menu (es. Opzioni o Menu). Se non vedi la schermata Size (New) (it. Dimensione - Nuovo) probabilmente vuol dire che hai gia' un programma caricato e devi riavviare JBit.

Empty Prog.

Dovresti vedere una matrice di zeri; questo e' il programma. Ci ritorneremo dopo. Per ora vogliamo solo arrivare rapidamente alla VM.

Seleziona Debug.

CPU (1)

Ecco la VM. Come vedi non assomiglia per niente all'immagine sopra. Questo perche' stai guardano dentro la VM!

Premi # per passare alla visuale esterna.

Display (Empty)

Adesso stai guardando lo schermo della VM. Non ha molto senso mostrarti il tastierino della VM, visto che quello del cellulare puo' fare le veci di quello della VM.

C'e' una piccola complicazione. Se avessimo attivato la VM normalmente, si sarebbe fermata subito, perche' il programma e' vuoto. Invece, abbiamo attivato la VM in una modalita' "congelata" che ci permette di ispezionarla. In questa modalita', e' piu' usuale guardare lo schermo che usare il tastierino, quindi, in questo momento, il tastierino del cellulare non sta' facendo le veci di quello della VM, ma e' usato solo per ritornare alla visuale interna.

Premi # un'altra volta per ritornare alla visuale interna.

CPU (BRK)

Vediamo cosa c'e' dentro la VM.

Hai probabilmente gia' sentito il termine CPU (Central Process Unit, it. Unita' di Elaborazione Centrale), visto che e' uno dei criteri di scelta quando si compra un computer. La CPU usata dalla VM e' fondamentalmente un 6502, una CPU popolare negli anni 70 e 80. Paragonata a una moderna CPU, e' piu' piccola e piu' lenta, ma, da un punto di vista teorico, non meno potente.

Imparare a conoscere la CPU e' lo scopo principale di JBit e richiedera' un po' di tempo. Possiamo cominciare cosi': la CPU e' un agente che opera in un mondo virtuale in nostra vece. Prima di farci rappresentare dalla CPU, opereremo un po' in questo mondo virtuale direttamente.

Premi 0 per passare alla visuale MEMory (it. memoria).

Memory (Empty)

A differenza del mondo reale, dove siamo liberi di posizionare gli oggetti come ci pare, in questo mondo virtuale, gli oggetti sono posizionati in celle (ing. cells) e le celle sono disposte in un'unica riga.

Inoltre, a differenza del mondo reale, dove ci sono vari tipi di oggetti, in questo mondo virtuale, c'e' solo un tipo di oggetto: il byte, un piccolo intero dai valori compresi tra 0 e 255.

Infine, a differenza del mondo reale, questo mondo virtuale e' finito. Ci sono esattamente 65536 celle. Per organizzare meglio questa lunga sequenza di celle, la dividiamo in 256 segmenti (chiamate pagine, ing. pages) di 256 celle ciascuna. Questo ha il vantaggio di consentirci di riferirci alla locazione delle celle usando due bytes: il numero di pagina (usando 0 per la prima pagina e 255 per l'ultima) e la posizione (o scostamento, ing. offset) all'interno della pagina (usando 0 per la prima posizione e 255 per l'ultima). Questa coppia di bytes e' chiamata indirizzo (ing. address) della cella e la scriveremo come due numeri separati dai due punti. Per esempio, la prima cella e' all'indirizzo 0:0, l'ultima e' all'indirizzo 255:255 e la 260esima e' all'indirizzo 1:3 (ovvero, la quarta cella della seconda pagina). Spesso scriveremo semplicemente la cella Pagina:Scostamento per riferirci alla cella di indirizzo Pagina:Scostamento.

La visuale MEMoria e' una visuale su questo mondo virtuale. Per sfruttare al meglio il piccolo display di un tipico cellulare le celle sono mostrate in una matrice, ma tieni presente che in realta' sono disposte in una singola riga.

La cella corrente (ovvero la cella che stiamo esaminando in questo momento) e' segnata dal cursore. Puoi muovere il cursore usando 4 (o sinistra) per andare alla cella precedente e 6 (o destra) per andare a quella successiva. Puoi anche usare 2 (o su) e 8 (o giu').

Vai alla cella 3:25 e seleziona Edit.

Edit

Questa schermata ti permette di cambiare il contenuto di una cella.

Inserisci 56 nel campo Value (it. Valore) e seleziona OK.

Memory (56)

Il contenuto della cella e' cambiato. Muovi il cursore in giu' fino a che la cella 3:25 non e' piu' visibile (es. quando reggiungi 3:50) e poi ritorna alla cella 3:25. Puoi vedere che la cella ha mantenuto il valore che hai inserito. La cella 3:25, come la maggior parte delle celle e' una cella di memoria (ing. memory) ovvero, una cella che semplicemente conserva il valore che viene inserito.

Seleziona GoTo (it. VaiA).

GoTo

Questa schermata ti permette di muovere rapidamente il cursore ad una cella particolare.

Inserisci 2 nel campo Page, inserisci 40 nel campo Offset e seleziona OK.

Memory (IO)

Le celle della pagina 2 non sono celle di memoria. Sono invece dei collegamenti a un dispositivo chiamato IO chip. In particolare, le celle dalla 2:40 alla 2:79 sono connesse allo schermo in questo modo:

     0  1  2  3  4  5  6  7  8  9
 40  .  .  .  .  .  .  .  .  .  .
 50  .  .  .  .  .  .  .  .  .  .
 60  .  .  .  .  .  .  .  .  .  .
 70  .  .  .  .  .  .  .  .  .  .

Inserire un byte da 32 a 126 in una di queste celle provochera' l'apparizione di un carattere sullo schermo, secondo la seguente tabella:

     0  1  2  3  4  5  6  7  8  9
 30           !  "  #  $  %  &  '
 40  (  )  *  +  ,  -  .  /  0  1
 50  2  3  4  5  6  7  8  9  :  ;
 60  <  =  >  ?  @  A  B  C  D  E
 70  F  G  H  I  J  K  L  M  N  O
 80  P  Q  R  S  T  U  V  W  X  Y
 90  Z  [  \  ]  ^  _  `  a  b  c
100  d  e  f  g  h  i  j  k  l  m
110  n  o  p  q  r  s  t  u  v  w
120  x  y  z  {  |  }  ~

Memory (88)

Seleziona Edit (it. modifica), inserisci 88 nel campo Value e seleziona OK.

Display (X)

Premi # per passare alla visuale esterna.

Come puoi vedere il carattere X e' visibile nell'angolo in alto a sinistra del display. Su cellulari con un ampio display, il carattere sara' probabilmente un po' piu' verso il centro, visto che il display della VM e' molto piu' piccolo di quello del cellulare.

Adesso che abbiamo una comprensione migliore di cosa significa "operare in un mondo virtuale" siamo pronti per dare un altro sguardo alla CPU.

Premi di nuovo # per tornare alla visuale interna e poi 0 per passare alla visuale CPU.

CPU (BRK)

La CPU puo' eseguire un numero limitato di azioni elementari chiamate istruzioni (ing. instructions) o operazioni (ing. operations). Per esempio: leggere un byte da una cella, scrivere un byte in una cella, sommare due byte, ecc...

Un programma e' fondamentalmente una lista di operazioni che la CPU deve eseguire per produrre il comportamento desidertato.

La CPU prende le oprazioni da eseguire dalle cell, a cominciare dalla cella 3:0. Quello che per noi e' solo un numero come tutti gli altri, per la CPU ha un significato particolare. Per esempio, 0 significa BRK (abbreviazione di BReaK, it. pausa) per la CPU. Il nome BRK viene dal fatto che, su un vero 6502, BRK poteva essere usato per sospendere il programma. Questa e' una delle poche differenze tra un vero 6502 e la CPU della VM. Sulla CPU della VM, BRK causa la terminazione del programma.

Le aree della CPU sono chiamate registri (ing. registers) invece di celle. Ne esamineremo solo alcuni qui. Prima di tutto, c'e' il PC (o Contatore Programma, ing. Program Counter). Ha spazio per due bytes e contiene l'indirizzo della cella contenente l'istruzione successiva da eseguire. Poi ci sono tre registri che hanno spazio per un solo byte ciascuno. Sono: l'em>Accumulatore (ing. Accumulator, abbreviato con A), X ed Y.

Memory (232)

Premi 0 per passare alla visuale MEMoria.

Scrivi 232 nella cella 3:0. Ovvero: seleziona GoTo, inserisci 3 nel canpo Page, inserisci 0 nel campo Offset, seleziona OK, seleziona Edit, inserisci 232 nel campo Value e poi seleziona OK.

Premi 0 per tornare alla visuale CPU.

CPU (INX)

232 significa INX (abbreviazione di INcrement X, it. incrementa X) per la CPU. INX causa l'incremento di 1 del registro X. Se il registro X gia' contiene 255, viene resettato a 0.

Premi 1 per avanzare di un passo (ovvero, fai eseguire un'operazione alla CPU).

CPU (BRK - 2)

Come puoi vedere l'operazione e' stata eseguita: il registro X adesso contiene 1 e il PC punta alla prossima cella (ovvero la cella 3:1, contenente l'istruzione successiva da eseguire).

Adesso potremmo cambiare il contenuto della cella 3:1 e continuare cosi', ma questo non e' il modo migliore di procedere. Scrivere sequenze di istruzioni e' piu' comodo usando l'Editor.

Premi 1 per avanzare di un passo e terminare il programma.

Halted

Ti viene data un ultima possibilita' di guardare il display, prima di spegnere la VM e ritornare all'Editor.

Seleziona End (it. Fine).

Empty Prog.

L'Editor e' un editor modale, overro gli effetti della premuta di un tasto dipendono dalla modalita' operativa corrente. Ci sono due modalita' principali (NAVigation ed EDiTing, it. NAVigazione e modifica) combinate con due modalita' secondarie (MEMoria e ASseMbly, it. MEMoria e ASseMblato).

La modalita' NAV MEM si comporta come la visuale MEMoria descritta sopra. Come sopra, puoi muovere il cursore usando 4 (o sinistra), 6 (o destra), 2 (o su) e 8 (o giu'). La differenza e' che non puoi raggiungere le celle oltre i confini del programma. Questo perche', quando scrivi un programma, non stai modificando la memoria della VM, ma semplicemente un modello di bytes che verrano usati successivamente per inizializzarla.

Prog. (2 232 2 EDT)

Assicurati che il cursore sia in 3:0 e premi 5 (o il tasto centrale, in alcuni cellulari).

La modalita' EDT MEM permette la digitazione dei bytes del programma "sul posto" (ovvero, senza aprire una nuova schermata).

Premi 2, *, 2, 3, 2 e 2.

Nota quanto segue:

  1. Non sei limitato a digitare un solo byte, ma puoi digitare un'intera sequenza.
  2. Per bytes con meno di tre cifre, puoi andare al prossimo byte premendo *.
  3. Per bytes con esattamente tre cifre, andare al prossimo byte e' automatico.

Se commetti un errore digitando la sequenza, puoi selezionare Cancel (it. Cancella) per svuotare il byte corrente. Se il byte corrente e' gia' vuoto, selezionare Cancel ritorna la byte precedente. Se in fine ha raggiunto il primo byte e selezioni Cancel, tornerai alla modalita' NAV MEM senza fare alcuna modifica al programma.

Premi OK per confermare le modifiche e ritornare alla modalita' NAV MEM.

Prog. (2 232 2 NAV)

I primi tre bytes del programma dovrebbero essere: 2, 232 e 2. Magari ricorderai che 232 significa INX, ma cosa significa 2?

Premi #.

Prog. (ASM - Invalid)

The NAV ASM mode allows you see the program as it would be interpreted by the CPU. You can move the cursor using 2 (or up) and 8 (or down) to scroll the listing, but you cannot press 5 to edit it in place.

So, 2 means ??? for the CPU. Well, that was not very helpful. Let us start the VM (properly this time) to see what happens.

Press *.

INV.OP.

Here is what happened:

  1. The VM was powered on.
  2. The program was copied to the memory cells of the VM.
  3. The CPU read the cell 3:0 to get an operation to perform.
  4. Since 2 has no meaning for the CPU, the VM was halted with an error.

INV.OP. is the abbreviation of "invalid opcode". Opcode is the contraction of "operation code" and is a byte identifying what kind of operation to perform. Some opcodes (e.g. 232) make sense for the CPU, while some others (e.g. 2) do not.

Select End to return to the Editor and then press # to switch to the NAV MEM mode.

Prog. (2 232 2 NAV)

Place the cursor at 3:0, press 5 to switch to the EDT MEM mode and then press # to switch to the EDT ASM mode.

Prog. (EDT)

The EDT ASM mode allows you to lookup a valid opcode.

Press 5 (jkL), 3 (Def) and 2 (Abc).

Prog. (LDA #n)

Before going any further, let me rephrase the sentence:

232 means INX for the CPU.
Without using the misleading word "means" ("means" might suggest that the CPU understands something):
When the CPU reads the opcode 232 from a cell, it increments the X register.

The three-letter label INX is called mnemonic and its only purpose is to remind the programmer of what the CPU does.

Let us have a look at two new opcodes: 169 and 173.

169. When the CPU reads the opcode 169 from a cell, it replaces the content of the Accumulator with the content of the cell after the cell containing the opcode.
173. When the CPU reads the opcode 173 from a cell, it replaces the content of the Accumulator with the content of a specific cell. The address of that cell is computed using, as the offset, the content of the cell after the cell containing the opcode, and, as the page, the content of the cell after the cell providing the offset

The wording is a bit convoluted, but I hope it will become clear with the examples below. What is important right now is to see a similarity between the two opcodes: in both cases, the content of the Accumulator is replaced. The mnemonic for that is LDA (abbreviation of LoaD Accumulator).

Here is an example for the opcode 169:

169 65

Note that, unlike BRK and INX, one byte is not enough to specify the behaviour of the CPU. If we want the CPU to replace the content of the Accumulator, we must specify the new content (65 in this case). In other words: the operation beginning with the opcode 169 is two-bytes long and the second byte (a.k.a. the operand) specifies the new content of the Accumulator.

And here is an example for the opcode 173:

173 40 2

In this case the operation is three-bytes long, and the last two bytes (i.e. the operand) specify the address of a cell where the new value of the Accumulator can be found. In this case, that would be cell 2:40. Yes, the order is inverted and this might be confusing at first, but you will quickly get used to it.

If you look at the two sequences of bytes above, you see that it is not clear that they are doing something similar (i.e. replacing the content of the Accumulator). Furthermore, on a long program composed of several operations, it is difficult to spot where the operations begin and to check if you provided the right number of bytes as operands.

Consider this sequence:

169 40 2

Maybe you meant to load the Accumulator from the cell 2:40. But, of course, the CPU cannot guess what you meant; it would load the Accumulator with 40 and then halt the VM because 2 is not a valid opcode.

Assembly language is an effective method to present the bytes of a program. Every operation is clearly shown in its own line, not matter if it is 1, 2 or 3 bytes long. Its behaviour is unambiguously specified using its mnemonic and, if needed, its operand. The operand itself is formatted using a rigorous pattern. This pattern is a compact way to express the second part of the two sentences above, or, in 6502 jargon, the addressing mode.

Memory view Assembly view Explanation
169 65 LDA #65 LoaD the Accumulator [LDA] with the constant [#n] 65
173 40 2 LDA 2:40 LoaD the Accumulator [LDA] with the content of the cell [n:n] 2:40

The addressing modes here are #n and n:n, where n is the abbreviation of number.

The JBit-QS.pdf sheet contains the full list of the addressing modes of the CPU. You are not expected to understand all of them by the brief descriptions contained in that sheet, but, even if you do not understand them, you can still get some information from the way they look: the number of lower-case characters of an addressing mode is the number of extra bytes an operation needs. For example, the addressing mode n:n,X requires two extra bytes beside the opcode.

Assembly, like every programming language and unlike natural languages, is a formal language and every small detail matters. For example, in English, you might make a punctuation mistake, but you can still be understood. In Assembly, even punctuation is critical. The operations LDA #65 (i.e. 169 65) and LDA 65 (i.e. 165 65) are completely different (the second one, if we ignore the fact that is shorter and faster, is equivalent to LDA 0:65).

Select LDA #n from the list. 169 is inserted, the cursor is moved to the next cell and the mode is switched back to EDT MEM.

Prog. (169 65 EDT)

Press 6, 5 and * to insert the operand.

Press # to switch to the EDT ASM mode.

Press 7 (pqrS), 8 (Tuv) and 2 (Abc).

Prog. (STA n:n)

STA is the mnemonic of STore Accumulator and is in a way the opposite of LDA: it replaces the content of a cell with the content of the Accumulator.

The JBit-QS.pdf sheet contains the full list of the mnemonics of the CPU. Again, you are not expected to understand all of them by the brief descriptions contained in that sheet, but, even without looking at the list, you should already be able to guess what a few other valid mnemonics (LDX, STX, LDY, STY, INY, DEX and DEY) stand for.

Select STA n:n from the list. 141 is inserted, the cursor is moved to the next cell and the mode is switched back to EDT MEM.

Prog. (169 65 141 40 2)

Press 4, 0 and * to insert the first byte of the operand (i.e. the offset).

Press 2 and select OK to insert the second byte of the operand (i.e. the page).

Press # to switch to the NAV ASM mode.

Prog. (ASM - LDA/STA)

Here is the Assembly view of the complete program:

LDA #65
STA 2:40
BRK

To sum up:

  1. The first operation loads the Accumulator with the value 65.
  2. The second operation stores the Accumulator (i.e. 65) to the cell 2:40, causing the character A (see the table above) to appear at the top left corner of the display.
  3. The third operation halts the VM.

Select Debug to test the program.

Debug

Press 1 to advance one step. The Accumulator now contains 65 and the Program Counter 3:2.

Press 1 to advance another step. The Program Counter now contains 3:5. You can check that the character A is visible on the display of the VM by pressing # and then go back to the CPU view by pressing # again.

Select Abort to terminate the program and go back to the Editor.

Save

At the beginning, you are likely to write very short programs and saving your work should not be a priority. In fact, starting from scratch each time might help you to consolidate what you have learned. If in the future you begin writing larger programs, here is how you can save them:

Select Save, type Tutorial and select OK.

Main Menu (Store)

Select Back followed by Exit to terminate JBit, and then start JBit again.

JBit is a modular system and can be configured to include more or fewer tools, depending on the limitations of your phone. The main menu lists which tools have been included.

In this tutorial I am using JBit1M, a version of JBit targeting old phones that comes with only two tools: the Store and the Editor. We have already used the Editor and below we are going to use the Store, but before that, let me introduce a couple of tools that you probably have in your version of JBit:

Demos
This tool provides a few ready-made programs that you can study. In particular, the 6502 demos are especially designed for the beginning programmer. If you have problem installing a version of JBit including the Demos tool, you can type the 6502 demos manually using the JBit-E0.pdf sheet as a reference.
Paint
This tool allows you to create and edit simple images with JBit. It was designed to show how to write tools and it is not very advanced, but it might be useful nevertheless.

An important thing to understand is that the tools operate on the current program. Unlike most computer applications, JBit can only work on one "document" at a time; if you run a demo or load a program, the program you are working on will be silently replaced, even if it has not been saved.

You might wonder why there is a Paint tool, if the display of the VM cannot show images. The reason is that you can equip the VM with different versions of the IO chip:

MicroIO
The MicroIO version provides only the most basic facilities to write interactive programs.
MIDP1
The MIDP1 version adds various functionalities, but, most importantly, adds the ability to display images.
MIDP2
The MIDP2 version adds the ability to write 2D action games.

The MicroIO version should not be dismissed. You can learn it quickly and it so simple that you do not need to consult a reference to use it. Even if you have a better version available, targeting the MicroIO version when you write your programs is a very good idea.

Select Store.

Store

The Store tool gives you a container where you can keep your programs for future editing. You have already used the Store tool without realizing it, when you saved the program from within the Editor, but accessing it manually gives you more options. The list of the saved programs is presented to you and you can use a few commands to manage them.

Load&Edit (the default command) loads a program and starts the Editor. Load&Run loads a program and starts the VM. Load just loads a program.

Save asks for the name of the current program and saves it. You cannot overwrite an existing program using Save; for that you have to use Overwrite.

Info, Copy, Rename and Delete do pretty much what you expect them to do. They do not change the current program.

When you upgrade JBit to a new version, your phone should ask you if you want to keep its data and it is important to reply YES to keep your saved programs. The exact wording of the question varies from phone to phone.

Select Tutorial.

Prog. (162 88 142 40 2)

Here is a quick editing session, as a review:

  1. Press 5 to start editing.
  2. Press # to lookup the first opcode.
  3. Type 539 (for LDX).
  4. Select LDX #n from the list.
  5. Type 88* to enter the operator.
  6. Press # to lookup the second opcode.
  7. Type 789 (for STX).
  8. Select STX n:n from the list.
  9. Select OK to confirm the changes (the result should be: 162 88 142 40 2).
  10. Press * to run the program.
  11. Select Video to have a look at the display.
  12. Press any key (e.g. the soft key you have used for selecting Video, even if it does not have a label attached to it anymore) to go back to the HALTED screen.
  13. Select End to go back to the Editor.
  14. Select Save to save the new version of the program to the Store.

Select Back and then Exit to terminate JBit.