Friday, July 6, 2012

Tiny AI Artificial Intelligence Software


TINY AI Artificial Intelligence Software
for the Stamp SEED Supercomputer
in 256 Bytes of BS1 EEPROM


Artificial Intelligence Software
the First Living Stamp Supercomputer Software is now ready for the Stamp SEED Supercomputer

Stamp AI gives a living soul to small Stamp microprocessors


Artificial Intelligence Overview of this Program Stamp AI makes the Stamp SEED Supercomputer a living entity, with each Stamp computer alive and unique.

This AI Artificial Intelligence fits only 256 bytes in a BS1 microcontroller - the first ever written for a Stamp Supercomputer. The same program loads into all ten computers (or any number of computers). Then it evolves and becomes self aware, based on unique conditions of a hardware pin and analog circuit.

It's awesome to have ten life forms all living in the supercomputer at the same time, working together, talking back and forth and getting to know each other. They evolve, develop unique personalities, even nap, have pseudo random dreams, have memories and recall, do work in their life span, sleep and finally hibernate.

Interesting story. Out of ten life forms, they all sleep different times. One life form hardly gets any sleep and he know every neighbor on a first name basis. The last life form spends most of his time sleeping. He does not even know he has neighbors! He leads a kind of hermit life. Others evolve to somewhere in between these two extremes.

They can get sick. When they do too much work, they have a psychotic breakdown. (code memory gets overwritten). They can have a bad sleep, being interrupted every 2.3 seconds. Alternate Identity Syndrome results if there is an unexpected power interruption. Stroke results when the synchronization is lost from one processor life form to the next. Stuttering may develop with repeat resets. Sudden death happens with complete loss of power.

I wrote the program so they do not die, as long as power is not removed. At the end of the life span, they go into stasis. All of their memories and knowledge remain intact, but cannot be accessed. I could not see the benefit of creating a life form and then causing it to die. In stasis, they are in a suspended animation, in a very low consumptive state, at only 25 micro amps. Also want to mention, I made a Dream Viewer so you can watch dreams and thoughts on the screen. It dreams in a special Vers Libre, a kind of abbreviated English verse which includes numbers. Someone asked if its scary. It's not scary - its all very interesting... :)

Code Posting
Code is posted below for creating a software file (BS1) to run on the SEED supercomputer. The file is also posted at the Parallax Forum for download at the given link.

Sample Screens
Note, computer 1 hears all nine other computers because it sleeps the least amount of time (while computer 10 misses hearing everything because it was sleeping when all the others were talking).

Review the screens from one lifeform to get an idea of the process.

Main Code Points:
Only One Program
SEED is unlike previous stamp supercomputer software that had a different program load into each computer. SEED is only one program - a life form. The same program loads into all computers in the supercomputer,

Life Form
The program is born and then it evolves into a life form! The collective supercomputer has ten life forms that are evolving at the same time.

Unique
After evolving, no two life forms are alike.

Life Span
Each life form has a life span of about one minute of activity.

Birth
It is first born based on its predetermined DNA, in this case, declarations and announcement.

Self Enumerating
Next, it looks at itself and determines its own unique enumerating identity. It does this by looking at pin 1 which contains a unique rc circuit.

Self Deterministic
Then SEED self determines its own computer number. It is now self aware and knows its own unique identity and its position in the world.

Memory & Recall
It then exercises its memory by remembering its own characteristics and demonstrates its recall ability.

Napping & Random Dreaming
All of this leads to taking a series of naps followed by pseudo random dreams. The dream are in Vers Libre, a kind of simple word-verse poetry. The nap time is accumulative, with similar rest effects that humans have. In this case, the power is reduced from 1 ma to 25 ua. The pseudo random dream generator is seeded by the unique identity of the lifeform.

Dream Watching
A Dream View Port puts the dreams up on the debug screen for viewing. It includes words, the random binary bit, and the pseudo random byte decimal number.

Sleep & Fuzzy Clock
The life form will now sleep using its fuzzy alarm clock. The approximate sleep time is unique and unlike the other lifeforms because it is based on its own unique characteristic of its computer identification number. The higher the number, the longer it sleeps. Therefore each life form has its own sleeping habits.

Talking to Neighbors
It wants to learn more about its world, so it sends out a message telling who he is and what his identity is to anyone listening.

Listening to Neighbors
Next, he listens for a reply. If he is life form number 1, he will get 9 additional replies. If he is number 5, he will get 5 replies. Finally, life form 10 will think he is alone. It's because each computer sleeps a different length of time. If a life form is sleeping, it will not hear the others talking.

Getting to know Neighbors
Now he gets to know his neighbors on a personal name basis. He memorizes the personal information of each neighbor that is heard. Next, all the neighbors are remembered.

Remembering Neighbors
He memorizes the personal information of each neighbor that is heard. Next, all the neighbors are remembered and recalled.

Thinking & Working
Some thinking/working takes place to recall the personal identity, determine the number of seconds in sleep and how many life forms were heard, plus how many life forms were not heard, and how many dreams were remembered.

End of Life
Finally, the life ends but is not entirely terminated, as it goes into stasis (I am not comfortable about creating life and then causing it to die).

Personalities
Each life form has its own evolved personality. There are several unique features. The personal identity, computer number, its living location, the random dreams it has, and the length of sleep habit. Its sleeping habit determines how friendly or how much of a hermit it will become. It also determines how much information about neighbors it will remember. Some life forms remember a lot of information while others remember very little. Thinking outcome is unique too.

Restrictions
Due to memory restrictions, PLAN Piezo Language is not included with this version, even though PLAN is a spinoff of the SEED software. The entire communications view port was built upon the Debug screen.

Becoming Sick
Because these are ten individual life forms, sickness can result. Below is a synopsis.
 
' PERSONIFIED MALADIES
' --------------------
' When you download a program into the BASIC Stamp 1, it is stored in the
' EEPROM starting at the highest address (255) and working towards the
' lowest address. Most programs don't use the entire EEPROM, so the lower
' portion is available for other uses. This portion is used for long term
' memories. As a result, like a real human person, this artificial life
' form is capable of succumbing to sickness and malady.

' PSYCHOTIC BREAKDOWN
' -------------------
' AI memory begins at memory location 0 and works upward. If
' the memories become too much, they will fall upon code and a psychotic
' action will take place, resulting in a breakdown as the main program
' will be overwritten.

' FITFUL SLEEP
' ------------
' We don't know how effective sleep really is for the AI supercomputer
' as its sleep is constantly interrupted every 2.3 seconds.
' The Basic Stamp 1s output pins will toggle briefly when using SLEEP,
' NAP or END. Inside the BASIC Stamp's interpreter chip is a watchdog
' timer whose main purpose is to reset the interpreter chip if, for some
' reason, it should stop functioning properly. The SLEEP and NAP commands
' also utilize the watchdog timer to periodically, every 2.3 seconds
' "wake-up" the BASIC Stamp from its low-power mode. Upon reset, the
' I/O pins are set to inputs for approximately 18 ms before returning
' to their previous directions and states. If you have an output pin set
' to a logical 1 state (+5V) and you use the SLEEP command, every 2.3 seconds
' during sleep mode that I/O pin will switch to an input for 18 ms causing
' a momentary signal loss. This "power glitch" is easily viewable with an
' LED and a 470 ohm resister tied to an I/O pin and switched on just before
' entering sleep mode. In many cases this problem can be remedied by tying
' a pull-up or pull-down resistor to the I/O pin in question to provide
' a constant source of power should the I/O pin change directions. Allowing
' a PBASIC program to end naturally, or using the END command, will exhibit
' the same "power glitch" behavior because the interpreter chip enters
' a low-power state.
'
' SUDDEN DEATH, BRAIN AMNESIA, NONRESUSCIATING SITUATION
' ------------------------------------------------------
' Life Terminates after power off, or by running another program. If a
' 2nd program is run (or the same program run a 2nd time), it will put all
' 0s into the EEPROM, thus destroying any memories and the original identity.
' It will be useless trying to resuscitate and bring back the original
' memories.
'
' ALTERNATE IDENTITY SYNDROME
' ---------------------------
' The stamp is reset causing the program to run again, and the birthing
' process takes place and a different identity emerges.
'
' STROKE
' ------
' The stamp is reset or repowered. It tries to communicate with other
' stamps but it is not in sync and the serial command hangs.
' It is unable to reply or do anything at this point.
'
' STUTTERING
' ----------
' Battery low causing short term repeating system resets
 


Code Fit
The code will fit any of the Basic Stamp Supercomputers built with BS1s with some parameter changes to indicate the total number of computers in the supercomputer. This works with the Stamp SEED Supercomputer, the TriCore Supercomputer, and the Stamp Tiny Supercomputer. 

Processor Type
Since the programming is in PBASIC 1 and for a BS1, it will not run on a BS2 without extensive modifications. 

Changing the Code
You are invited to change the code, but remember it is interlaced with timing. When life forms speak, it is based on timing. 

Flow Control
Serial flow control is established by sending, and listening for the "!" command. This allows all life forms to listen to talk at the same time. 

Running the Code & Watching Evolution
The one program is loaded into each computer. Power off the supercomputer. Connect the cable to the computer you want to watch evolve as a life form. Power on the supercomputer. Load in this program bringing up the Debug screen. Before anything appears on the screen, power off the supercomputer. Leave the screen on, and power on the supercomputer. You can now watch the entire evolution take place automatically! 

How the code works

Stamp SEED Supercomputer! All new! This is a ten core, ten month project, with the 1st Stamp AI software to fit into 256 bytes eeprom - self determinate, evolving, enumerating, dreaming, poetic, noisy, talkative, and downright friendly. It runs on only one program that self evolves differently in each of the ten computers. It's evolutionary - it's revolutionary! http://forums.parallax.com/forums/default.aspx?f=21&m=361377&p=1 

“Stamp AI gives a living soul to small Stamp microprocessors” 

Lock & Load
Load stamp_ai.bs1 into all ten computers. Connect to the computer you want to monitor and load the code. Turn off the entire supercomputer when the blue debug screen appears (before any words appear on the screen). Now turn on the supercomputer. The debug screen will show the thinking of the computer it is connect to. This is the viewer. It shows what the life form is thinking and doing. It even shows dreams. All life forms are unique and develop individual personalities.

Birthing & DNA
There is an unseen birthing process that takes place. This is the DNA part of the program, with directives, declarations, and initializations. Then, introduction takes place. Suddenly, evolution begins. The life form looks at pin 1 from which it determines its own unique identity, using a resistor capacitor circuit. Next, the unique identification (self enumerating) is used to determine its computer number and its physical location to know which block it lives on. The supercomputer is divided into ten blocks, computer 1 lives on the lowest block while computer ten lives on the top block (deterministic). 

Personality and Memory
This personal information is committed to memory. There are two memory locations, 0 and 1, designated for the id and computer number. Throughout the life of the entity, this information is remembered and recalled. Now the life form will take a series of naps. The NAP number is 0, which represents 18 milliseconds. In between each nap, there is a dream. Dreams are pseudo random in nature and occur in Vers Libre, a kind of abbreviated poetic verse. Dreams also include numbers and their pseudo random bit representation. Dreams are unique because they are seeded with the unique personal id.

Deep Sleep
After napping and dreaming, a deep sleep results. The length of sleep is directly related to the life form’s computer number. The lower computer number life forms have shorter sleep, while the higher number life forms spend more of their time sleeping. Sleeping can have cause and effect, because in the next waking phase, a life form will talk - call out and speak its personal information to its neighbors. These are the friendly ones. Whether neighbors hear this information depends on whether they are sleeping or awake. The lazy ones will miss the information. In the extreme case, life form 10 sleeps so much that he misses hearing all of his neighbors, and becomes somewhat of a hermit. His memory has little information. Life form one sleeps the least time, and as a consequence, knows all his neighbors and is very friendly. His memory is rich and filled with all the neighbors information. 

Neighbors Influence
In the next phase of life, the memories about the neighbors are recalled. All of this appears on the viewer. Thinking and information always appear on the viewer. This is a unique privilege to see the life form’s thought process on the screen. No life form is complete without doing some work in life. Each life form will start talking about its computer number, identification, how many seconds it did sleeping, how many neighbors it heard, how many neighbors it missed hearing, and how many dreams it had. These life forms do not live long compare to humans. Their actual lives are approximately one minute long. At the end of a life cycle, hibernation takes place. This is a kind of suspended animation with a heart beat of once every 2.6 seconds. Memories and information are retained but there is no known way to retrieve it in this time era. 

Characteristics
Personality galore! You’ll find these life forms interesting, unique and with varying personalities. The differences from one to the other include different identifications, different computer numbers, different dreaming, varied sleep times, some are friendly and some don’t know any neighbors. Some have filled enriched memories and remember all their neighbors while others can only remember two things and spend all their time sleeping. 

Sustaining Life
The code could have sufficient modification to prevent the life form from dying, and to create an indefinite hibernation in which it can wake up on demand. Instead of and END statement, the code could terminate in a continuous loop. Inside the loop, it looks at a pin status. If the pin goes high, the program can go back to some place in the code for continued function. Sometimes the life form will become sick and require personal sick leave. The sicknesses are varied. For example, the following maladies are discussed in further detail elsewhere – psychotic breakdown, fitful sleep, sudden death, brain amnesia, unable to resuscitate, alternate identity syndrome, stroke, epileptic pins, and stuttering.

TINY AI - The CODE

' ************************************************************************
' INTRODUCING STAMP AI ***************
' ************************************************************************
'
' Stamp AI gives a living soul to small Stamp microprocessors
'
' stamp_ai.bs1 for the Stamp SEED Supercomputer v3.8
' Self Evolving Enumerating Deterministic Code (SEED)
' An Artificial Intelligence System for the Basic Stamp 1
' Developed for Stamp SEED Supercomputer (which has ten Stamp computers)
' by Dr. Humanoido 06.23.09 - developer of AI language Writer -
' AI program that writes 25,000 computer programs for Japanese Robot
' Manufacturing Systems, Industrial Manufacturing, Artificially
' Intelligent CNC Programming

' ************************************************************************
' FEATURES   ***************
' ************************************************************************

' Very Simple AI performed in 256 bytes eeprom
' This one program will load into ten computers and self evolve.
' Software versions exist for Stamp supercomputer with ten and three
' computers. Refer to the Minuscule Stamp Supercomputer for the "three
' computers" version.

' * Fits into 1/4th K (256 Bytes) EEPROM
' * Simple self modifying code capable (modifies eeprom technique)
' * Less than 100 code statements
' * The first complete AI system that fits into the BS1
' * Has "Miniscule AI" at the core, adaptable to other Stamps
' * 17 Phases of Life Cycle
' * Thought monitor (brain thinking is relayed to the pc sceen)
' * Dreams are shown on the screen for real time monitoring
' * Has a Virtual Fuzzy Clock, not exact but more human-like

' ************************************************************************
' LIFE CYCLE PERFORMANCE   ***************
' ************************************************************************

'     (See full description in the Stamp Seed Supercomputer Manual)
' 1)  read pin 1 and determine id                         (self enumerating)
' 2)  determine computer number based on id range         (deterministic)
' 3)  remember computer id & number                       (memorize)
' 4)  recall memory of computer id & #                    (remember)
' 5)  nap and pseudo random dream in "Vers Libre"         (nap, dream)
' 6)  sleep fuzzy clock - its computer number in seconds  (sleep)
' 7)  wake to send its computer number and id             (wakeup, talk)
' 8)  Listen for others' computer numbers                 (listen)
' 9)  if heard, remember other computer numbers and id's  (know what is heard)
' 10) do some work, retrieve the other ids...             (work)
' 11) goes into suspended animation

' another view of the life process

' 01) Birth (Declares language of origin, physical attributes)
' 02) Self Deterministic (finds its own identity and uniqueness)
' 03) Early Memory (early formative memory, remembers its identity)
' 04) Develops or recognizes a sense of time
' 05) Talks to others, announces itself and its personal identity
' 06) Speaks another Language (PLAN - Piezo Language)
' 07) Self Evolving (learns information about others)
' 08) Long Term Memory (remembers information about others)
' 09) Sense of Purpose/Meaning of Life (establishes work)
' 10) Naps in 1s intervals (with dreams in between)
' 11) Dreams (dreams about random numbers and poetry)
' 12) Suspended Animation (END statement induces suspended state)
' 13) Sleeps
' 14) Alive (Live Code, Power Down or 2nd program run terminates life)

' ************************************************************************
' PHASES OF SEED'S MINISCULE AI  ***************
' ************************************************************************

' PHASE 0 - PREPARE THE ENUMERATION PIN
' PHASE I - FORMATION AND BIRTHING PROCESS - DECLARATIONS
' PHASE II - PERSONAL INTRODUCTION
' PHASE III - SELF ENUMERATION - CREATING A SELF AWARE IDENTITY
' PHASE IV - THOUGHT MONITOR
' PHASE V - SELF DETERMINATION
' PHASE VI - EARLY MEMORY - REMEMBERING SELF IDENTITY
' PHASE VII - NAP
' PHASE VIII - DREAM
' PHASE IX - DEVELOPING A SENSE OF TIME (FUZZY CLOCK)
' PAHSE X - SLEEP
' PHASE XI - CONVERSATION - INTRODUCTION TO NEIGHBORS
' PHASE XII - CONVERSATION - LISTEN TO NEIGHBORS
' PHASE XIII  - MEMORIZING THE IDENTITY OF NEIGHBORS
' PHASE X1V  - LONG TERM MEMORY - RECALL IDENTITY OF NEIGHBORS
' PHASE XV  - SPEAK LAN PIEZO LANGUAGE (FOR EXPANSION)
' PHASE XVI - FINDING PURPOSE IN LIFE - DO WORK/THINKING
' PHASE XVII - END OF LIFE CYCLE - SUSPENDED ANIMATION/HIBERNATE

' ************************************************************************
' HISTORY ***************
' ************************************************************************

' Makes use of "Miniscule AI" (Interpreter originally developed by
' Humanoido for the Toddler Humanoid and modified for Stamp Supercomputers)
' Uses the idea of self enumerated deterministic programming, a Propeller
' Supercomputer approach originally proposed by Chip Gracey at the
' Propeller Supercomputing thread on 4-18-2006. Reference:
' http://forums.parallax.com/forums/default.aspx?f=25&p=1&m=121344

' The code will load into a Basic Stamp Supercomputer equipped with the
' Self Enumerating Pin Circuit. The details to construct one are included
' below. The BS1 handles up to 100 commands.
' Each computer sets up its own fuzzy clock timer. The clock counts, in
' seconds, equal to the computer number. Computer numbers range from 0 to 10.
' Some scaling may take place.

' Self evolving, self aware, code modifying, one code for all, programs
' are quite complicated. The one 256 byte-fit program is now divided into 13
' phases. The challenge is one program is fed to ten computers. From there,
' the same program is born and develops individual characteristics. It's like
' a Chess game, anticipating moves far in advance, when developing this program.
' Each computer uses a deterministic pin from which its evolution begins.
' It follows up by becoming self aware and choosing a self identity. It learns
' about its neighbors and carries on a conversation. It remembers information
' and exchanges information. It develops a sense of time, and a meaning in life.
' It learns and speaks a new language. It chooses some work to do. When it
' sleeps, it dreams. A monitor can be attached to watch thoughts and dreams on
' each computer.

' ************************************************************************
' PHASE 0 - PREPARING ENUMERATION PINS  ***************
' ************************************************************************

' Hardware consists of 10 Basic Stamp Supercomputers. Each computer
' has one RC circuit on pin 1 (see schematics below), prepared in
' advance.

' * is a 220 ohm resistor built into each Stamp 1 Project Board.

' Software scaling is set to 54. The program must go pin 1 low and
' pause 2000 for repeat reliable readings.
'
'               *
'              220
' pin 1 <-----^^^^^----- no circuit, open       COMPUTER 1 ID = 00
'           resistor
'
'               *        R2       C2
'              220       1K       .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 2 ID = 17
'           resistor  resistor  capacitor       brown-black-red
'
'
'               *        R3       C3
'              220       2K       .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 3 ID = 28
'           resistor  resistor  capacitor       red-black-red
'
'
'               *        R4       C4
'              220       3K       .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 4 ID = 40
'           resistor  resistor  capacitor       orange-black-red
'
'
'               *        R5       C5
'              220       3.9K     .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 5 ID = 49
'           resistor  resistor  capacitor       yellow-black-red
'
'
'               *        R6       C6
'              220       5.1K     .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 6 ID = 70
'           resistor  resistor  capacitor       green-brown-red
'
'
'               *        R7       C7
'              220       6.8K     .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 7 ID = 89
'           resistor  resistor  capacitor       blue-gray-red
'
'
'               *        R8       C8
'              220       8.2K     .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 8 ID = 111
'           resistor  resistor  capacitor       gray-red-red
'
'
'               *        R9       C9
'              220       9.1K     .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 9 ID = 116
'           resistor  resistor  capacitor
'
'
'               *        R10      C10
'              220       10K     .1uf
' pin 1 <-----^^^^^-----^^^^^-----||----- Vss   COMPUTER 10 ID = 128
'           resistor  resistor  capacitor
'
'

' IDs are 00, 17, 28, 40, 49, 70, 89, 111, 116, 128

' TYPICAL PIN 1 RESISTANCE CODE CHART
' Computer 1       220 ohm (built in to Stamp 1 Project Board)
' Computer 2       220 + 1K Ohm   = 01.22K
' Computer 3       220 + 2K Ohm   = 02.22
' Computer 4       220 + 3K Ohm   = 03.22
' Computer 5       220 + 3.9K Ohm = 04.12
' Computer 6       220 + 5.1K Ohm = 05.32
' Computer 7       220 + 6.8K Ohm = 07.02
' Computer 8       220 + 8.2K Ohm = 08.42
' Computer 9       220 + 9.1K Ohm = 09.32
' Computer 10      220 + 10 K Ohm = 10.22

' ************************************************************************
' PHASE I - FORMATION AND BIRTHING PROCESS  ***************
' ************************************************************************

' {$STAMP BS1}            ' Self deterministic program
' {$PBASIC 1.0}           ' humanoido July 2009
SYMBOL  result  =   B0    ' (random)Nap & Dream - a random number
SYMBOL   n      =   BIT1  ' (random) bit1 number is 0 or 1 from B0 above
SYMBOL   id     =   B1    ' pin read id number of this computer (0-126)
SYMBOL   c      =   B2    ' determined computer number (1-10)
SYMBOL   v      =   B3    ' id range value for each computer, random dreams counter
SYMBOL   h      =   B4    ' no. of heard/missed coms (never heard - was sleeping)
SYMBOL   x      =   B5    ' slush value for thinking, recycled as needed
SYMBOL  epin    =   1     ' Enumerating pin
SYMBOL  ipin    =   0     ' Rx Tx Interface pin for serial in and out
SYMBOL  ppin    =   7     ' Piezo speaker pin
SYMBOL  baud    =   N1200 ' Baud rate, inverted, n81 format

' The BS1 provides variables from B0-B13 and W0-W6. Variable Examples:
' SYMBOL  XXX         = B0   ' Bit Addressable
' SYMBOL  XXX         = B1   ' Bit addressable
' SYMBOL  XXX         = B2   ' Bit addressable
' SYMBOL  XXX         = B3   ' Bit addressable
' SYMBOL  XXX         = B4   ' Bit addressable
' SYMBOL  XXX         = B5   ' Bit addressable
' SYMBOL  avail       = B6   ' value can be 0 to 255
' SYMBOL  avail       = B7   ' value can be 0 to 255
' SYMBOL  avail       = B8   ' value can be 0 to 255
' SYMBOL  avail       = B9   ' value can be 0 to 255
' SYMBOL  XXX         = W5   ' Consumes B10 & B11
' SYMBOL GOSUB/RETURN = W6   ' Consumes B12 & B13

' When a program is first run, all variables are cleared to 0. The variables
' total to 16 bytes of RAM AND are arranged as follows:
'
' Data            Words   Bytes   Bits
' 0000 0000       PORT    PINS    PIN0 - PIN7  (PINS.0, PORT.0 - PINS.7, PORT.7)
' 0000 0000               DIRS    DIR0 - DIR7  (DIRS.0, PORT.8 - DIRS.7, PORT.15)
'
' 0000 0000       W0      B0      BIT0 - BIT7  (B0.0, W0.0 - B0.7, W0.7)
' 0000 0000               B1      BIT8 - BIT15 (B1.0, W0.8 - B1.7, W0.15)
'
' 0000 0000       W1      B2
' 0000 0000               B3
'
' 0000 0000       W2      B4
' 0000 0000               B5
'
' 0000 0000       W3      B6
' 0000 0000               B7
'
' 0000 0000       W4      B8
' 0000 0000               B9
'
' 0000 0000       W5      B10
' 0000 0000               B11
'
' 0000 0000       W6      B12
' 0000 0000               B13
'
' PORT is the I/O PORT word:
'
'        PINS AND PIN0-PIN7 are the PORT (RB) PINS (buffered to overcome the
'        READ-modify-WRITE problem).  When these variables are READ, RB is READ
'        directly.  When these variables are written to, the corresponding RAM
'        is written TO, which is then transferred TO RB before each instruction.
'
'        DIRS AND DIR0-DIR7 are the PORT (RB) direction bits: 0=INPUT, 1=OUTPUT
'        (buffered to overcome the WRITE-only nature of the TRIS registers).
'        This byte of data is transfered TO !RB before each instruction.
'
' W0-W6, B0-B13, AND BIT0-BIT15 are for general-purpose use.
' W6 (B12,B13) is used as a four-level stack if any GOSUB/RETURNs are executed.

' ************************************************************************
' PHASE II - PERSONAL INTRODUCTION    ***************
' ************************************************************************

DEBUG "Hello human! I am SEED",CR,"Artificial Intelligence Life Form ",CR,CR

' This code is loaded into all ten computers (Stamp SEED Supercomputer).

' Flowchart
' Begin Stamp Baby Supercomputer SBS
'     Each computer has an R/C circuit on pin 1 (see schematic)
'     Load one program (this program) into all 10 computers
'          Each computer: Read Pin 1 rc value using the POT command
'                scale the value into a unique computer ID
'                Remember this ID
'                Delay a time based on the unique ID
'                Send out the ID to the network after delay time
'                Each computer records all the id numbers it hears on the net
'                Remember and recall some information
'                Do some work
'                End

' Some Program Elements
'       RC circuit
'       Data logger
'       EEPROM reader
'       EEPROM writer
'       Time Scaler
'       Fuzzy Clock
'       Serial transmitter
'       Serial receiver
'       Debug Screen

' ************************************************************************
' PHASE III - SELF ENUMERATION - CRATING A SELF AWARE IDENTITY ************
' ************************************************************************

' SELF ENUMERATION
' read pot (POT PotPin, Scale, read_value), display
' LOW 1:PAUSE 2000:POT 1, 54, B1:DEBUG CLS,B1

LOW   epin       ' get id from self enumerate pin, read rc circuit = ID number
PAUSE 2000       ' cap charge & settle time on pin 1
POT   epin,54,id ' pin 1, scale, determine id, read pot (POT PotPin, Scale, read_value)

' ************************************************************************
' PHASE IV - THOUGHT MONITOR   ***************
' ************************************************************************

' The Thought Monitor allows you to peer into the computer's mind
' and view the thought process. Plug in the pc computer and
' view the thought process through the DEBUG screen. The thinking
' of each computer on the supercomputer can be viewed on at a time.
' You can listen in to each computer brain using the debug screen
' and learn what they are thinking, remembering, and what work they
' are doing at the time.

DEBUG "(Self Enumerating)",CR,"id is ",#id,CR,CR ' show on debug screen

' ************************************************************************
' PHASE V - SELF DETERMINATION   ***************
' ************************************************************************

Loop:   'Determine Computer Number - loop for all ten computer possibilities
LOOKUP c, (12,23,35,45,55,76,95,114,122,134), v ' lookup logged id range values v
c = c + 1                                       ' next range lookup address
IF id >=  v THEN Loop                           ' if id > range, try again
DEBUG "(Self Determinate)",CR,"I am computer number ",#c,CR,CR ' show computer #

' ************************************************************************
' PHASE VI - EARLY MEMORY - REMEMBERING SELF IDENTITY
' ************************************************************************

' MEMORY MAP (eeprom 85% full)
' 00              computer id     (enumerating)
' 01              computer number (deterministic)
' 02-21           other computers, alternating id & computer # (see below)

' DATALOGGING MEMORY MAP FROM 02 TO 21 (LOG SHOWN FOR COMPUTER #1 ONLY)
' MEMORY LOCATION  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21
' DATA STORED      ID1 C1  ID2 C2  ID3 C3  ID4 C4  ID5 C5  ID6 C6  ID7 C7  ID8 C8  ID9 C9  ID10 C10

WRITE 0,id                                     ' memorize id number
WRITE 1,c                                      ' memorize computer number
READ 0,id                                      ' recall this computer's id
DEBUG "(my 1st memory)", id,CR,CR              ' show computer number is remembered
READ 1,c                                       ' recall this computer's computer number
DEBUG "(my 2nd memory)",c,CR,CR,"(Nap Dreams)" ' show computer id is remembered

' ************************************************************************
' PHASE VII - NAP
' ************************************************************************

' Nap#  Nap   Time
' 0     18    ms
' 1     36    ms
' 2     72    ms
' 3     144   ms
' 4     288   ms
' 5     576   ms
' 6     1.152 s
' 7     2.304 s

v = 0                         ' init a new counter
result = id                   ' seed pseudo random # generator with the id
Again:                        ' loop
v=v+1                         ' count the dreams
IF v=11 THEN FuzzyClock       ' do 10 dreams @@@ (based on the total # of computers)
RANDOM result                 ' randomize a byte
BRANCH n, (Dream1, Dream2)    ' go to bit 0 or 1, BRANCH value, (Case_0, Case_1, Case_2)

' ************************************************************************
' PHASE VIII - DREAM   ***************
' ************************************************************************

' The computers will dream when sleeping. Dreams are totally
' random in nature. After a while, a repeat dream may occur.
' Each computer dreams about random numbers which are shown
' on the Dreamscape monitor. Dreams may also involve machine
' poetry but we are not sure.

Dream1:                       ' begin 1st dream
NAP 0                         ' nap reduce 1ma to 25us
DEBUG CR, "Sweet ",#n,#result ' show dream & random number
GOTO Again                    ' next random dream
Dream2:                       ' begin second dream
NAP 0                         ' nap 18ms, reduce 1ma to 25us
DEBUG CR, "Dream ",#n,#result ' next random dream or end of dream, show rnd numb
GOTO Again                    ' repeat

' ************************************************************************
' PHASE IX - DEVELOPING A SENSE OF TIME (FUZZY CLOCK)
' ************************************************************************

FuzzyClock:                   ' this computer will sleep equal to c*3
x=c*3                         ' sleep formula

' IDs are 00, 17, 28, 40, 49, 70, 89, 111, 116, 128  = B0

' 00*3=0
' 17*3=51
' 28*3=84
' 40*3=120
' 49*3=147
' 70*3=210
' 89*3=44
' 111*3=55
' 116*3=80
' 128*3=64

' ************************************************************************
' PHASE X - SLEEP
' ************************************************************************

' SLEEP allows the BASIC Stamp to turn itself off, then turn back on
' after a programmed duration. The length of SLEEP can range from 2.3
' seconds to slightly over 18 hours. Power consumption is reduced to the
' amount described in the table above, assuming no loads are being driven.
' The resolution of the SLEEP instruction is 2.304 seconds. SLEEP rounds
' the specified number of seconds up to the nearest multiple of 2.304.
' For example, SLEEP 1 causes 2.3 seconds of sleep, while SLEEP 10 causes
' 11.52 seconds (5 x 2.304) of SLEEP.

' Pins retain their previous I/O directions during SLEEP. However, outputs
' are interrupted every 2.3 seconds during SLEEP due TO the way the chip
' keeps time. The alarm clock that wakes the BASIC Stamp up is called the
' watchdog timer. The watchdog is a resistor/capacitor oscillator built
' into the interpreter chip. During SLEEP, the chip periodically wakes up
' AND adjusts a counter TO determine how long it has been asleep. If it
' isn't time to wake up, the chip "hits the snooze bar" and goes back to
' sleep.

' To ensure accuracy of SLEEP intervals, the BASIC Stamp periodically
' compares the watchdog timer to the more-accurate resonator time base.
' It calculates a correction factor that it uses during SLEEP. As a result,
' longer SLEEP intervals are accurate to approximately ±1 percent. If your
' application is driving loads (sourcing or sinking current through
' OUTPUT-HIGH OR OUTPUT-LOW PINS) during SLEEP, current will be
' interrupted FOR about 18 ms when the BASIC Stamp wakes up every 2.3
' seconds. The reason is that the watchdog-timer reset that awakens the
' BASIC Stamp also causes all of the pins to switch to INPUT mode for
' approximately 18 ms. When the interpreter firmware regains control of
' the processor, it restores the I/O directions dictated by your program.

' If you plan to use END, NAP, OR SLEEP in your programs, make sure that
' your loads can tolerate these periodic power outages. The simplest
' solution is often to connect resistors HIGH OR LOW (TO +5V OR ground)
' as appropriate to ensure a continuing supply of current during the
' reset glitch.

DEBUG CR,CR,"(Sleeping)",CR   ' display sleeping mode
SLEEP x                       ' sleep its computer number in seconds
DEBUG "(wake up)",CR          ' Display clock status

' ************************************************************************
' PHASE XI - CONVERSATION - INTRODUCTION TO NEIGHBORS
' ************************************************************************

' Announce id & c to Everyone, SEND ID SO OTHERS MAY DATALOG IT
' After self delay timing, send the ID to net

SEROUT ipin,baud,("!",id,c) ' wake up, announce this computer's ID and #,
DEBUG "(talk)",CR,#id,#c,CR  ' show id & c were sent, computer 10 is last to wake,

' ************************************************************************
' PHASE XII - CONVERSATION - LISTEN TO NEIGHBORS
' ************************************************************************

' Listen for Neighbors id & c
' For example, with 3 computers:
' if c = 1   x = 1 to 2  listen for two computers  x = 1 to (3-c)
' if c = 2   x = 1 to 1  listen for one computer
' if c = 3   goto end    do not listen, this is the last computer and
'                        cannot count itself as listening to itself

' @@@ SET THE SUPERCOMPUTER'S NUMBER OF COMPUTERS IN THESE STATEMENTS!!!

v=2                           ' init the write addr, start at 2
Listen:                       ' listen to other computers speaking their id's
IF c = 10 THEN Think          ' jump if computer 10, cannot listen as sleeping @@@
x = 10 - c                    ' equation to determine looping @@@
FOR h = 1 TO x                ' do the loops
SERIN  ipin,baud,("!"),id,c   ' look at serial pin 1 for incoming id & computer #
DEBUG "(hear)",CR,#id,#c,CR   ' show received id & c
GOSUB Memorize                ' remember what you hear
NEXT                          ' next interation
GOTO Recall                   ' recall what what heard

' ************************************************************************
' PHASE XIII  - MEMORIZING THE IDENTITY OF NEIGHBORS
' ************************************************************************

Memorize:                     ' place heard computer's id and c in memory
DEBUG "(memorizing)",CR,CR    ' memorize the id and c values
WRITE v,id                    ' datalog to eeprom, v is eeprom addr = 2
v=v+1                         ' inc eeprom addr
WRITE v,c                     ' datalog to eeprom
v=v+1                         ' increment memory loc
RETURN                        ' listen again *** what happens when no more computers?

' ************************************************************************
' PHASE XIV  - LONG TERM MEMORY - RECALL IDENTITY OF NEIGHBORS
' ************************************************************************

' SET THE SUPERCOMPUTER'S NUMBER OF COMPUTERS IN THESE STATEMENTS ********

Recall:                       ' Read/display neighbors id & c
DEBUG "(recall neighbors)",CR ' screen report about remembering
v=1                           ' init mem loc
DEBUG "mem loc, id/com ",CR   ' screen report for storage location, id & computer #
Repeat:                       ' recall memory subroutine
v = v+1                       ' begin at mem loc 2
READ v,x                      ' recall v and id
DEBUG #v,#x,CR                ' display mem loc, read val
PAUSE 500                     ' slow to see screen vals
IF v>20 THEN Think            ' CHANGE THIS TO REFLECT WHICH SUPERCOMPUTER! @@@
                              ' OK TO USE 20 FOR 10 COMPUTERS
GOTO Repeat                   ' again

' ************************************************************************
' PHASE XVI - FINDING PURPOSE IN LIFE - DO WORK/THINKING
' ************************************************************************

' in its simplest form, this life form will use memory recall to indicate
' its personal computer number and its personal identity.

Think:                        ' think routine

DEBUG CR,"(Thinking)",CR       ' announce thinking
READ 1,c                       ' read computer number at loc 1
DEBUG "I am computer ",#c,CR   ' announce my computer number
READ 0,id                      ' read id at loc 0
DEBUG "My id is ",#id,CR       ' announce my id

' the life form will use memory to recall its computer number and
' determine how long it slept.

x=c*3                          ' formula for length of sleep
DEBUG "I slept  ",#x," sec",CR ' how long did I sleep?
h=10-c                         ' formula for the number of heard coms @@@
DEBUG "I heard  ",#h," com",CR ' announce # of computers heard
h=9-h                          ' formula for the number of missed coms @@@
DEBUG "I missed ",#h," com",CR ' announce computers not heard
DEBUG "I had    10 dreams ",CR ' announce computers not heard
GOTO Halt                      ' end

' ************************************************************************
' PHASE XV  - SPEAK PLAN PIEZO LANGUAGE
' ************************************************************************

' This section is for expansion using the new spinoff Piezo Language PLAN
' Note that some life forms will have the characteristics of Piezo Speech,
' while others will not. No individuals have the same voice sound. Since
' tone is directly related to personal id, computer 1 will have no voice
' while ascending computers (ranked in increasing computer numbers) will
' have increasing pitch voices. Some low tones may or may not be heard.
' It's all in the personality of the individual life form (piezo speakers
' vary in their sound, and human ears vary in their perceptibilities).

'OUTPUT 7                       ' make pin 7 output for speaker
'SOUND  7, (id, 60)             ' id = tone, 60 = duration
'INPUT  7                       ' prevent noise on speaker pin

' ************************************************************************
' PHASE XVII - END OF LIFE CYCLE - SUSPENDED ANIMATION/HIBERNATION
' ************************************************************************

' At the end of the life cycle, it goes into a kind of hibernation or
' suspended animation. It maintains a heartbeat once every 2.6 seconds.
' But, you can terminate it by turning off the power or loading in
' another program (not recommended). It's not cryogentic suspended
' animation but a similar form achieved by the electronics and software
' of this microcontroller.

Halt:
DEBUG CR,"(bye)"
END

' ************************************************************************
' SELF MODIFYING CODE     ***************
' ************************************************************************

' Self modifying code is possible in theory but not easy. In fact, it's
' frowned upon because it becomes very difficult, virtually impossible,
' to debug for one thing. And there are alternatives - that's what
' subroutines are for, and decision code. To create a 100 byte program
' that is self-modifying could require a thousand bytes of decision code
' to decide how to modify the critical 100 byte part. Constants are compiler
' directives - when you use them in your program, the value of the constant
' is plugged into the memory location. In theory, you could change a value
' in EEPROM, however finding which value to change would be difficult.

' A more simple way to have immediate success in self modifying is to
' store initialized data in an otherwise unused part of the EEPROM and
' change it as needed. Program code loads into EEPROM from the top down.
' EEPROM and WRITE commands work from the bottom up. A simple way to self
' modify EEPROM is by writing to locations using the WRITE command, and
' rewriting as necessary. It takes the least amount of code and space to
' do this - one statement per rewrite location. So we now have a simple
' way, in minimal memory and code, to successfully achieve self modifying
' code.

' ************************************************************************
' PERSONAL SICK LEAVE ***************
' ************************************************************************

' When you download a program into the BASIC Stamp 1, it is stored in the
' EEPROM starting at the highest address (255) and working towards the
' lowest address. Most programs don't use the entire EEPROM, so the lower
' portion is available for other uses. This portion is used for long term
' memories. As a result this and other effects, like a real human person,
' this artificial life form is capable of succumbing to sickness.

' PSYCHOTIC BREAKDOWN - AI memory begins at memory location 0 and works
' upward. If the memories become too much, they will fall upon code and a
' psychotic action will take place, resulting in a breakdown as the main
' program will be overwritten.

' FITFUL SLEEP - We don't know how effective sleep really is for the AI
' supercomputer as its sleep is constantly interrupted every 2.6 seconds.
' The Basic Stamp 1s output pins will toggle briefly when using SLEEP,
' NAP or END. Inside the BASIC Stamp's interpreter chip is a watchdog
' timer whose main purpose is to reset the interpreter chip if, for some
' reason, it should stop functioning properly. The SLEEP and NAP commands
' also utilize the watchdog timer to periodically, every 2.3 seconds
' "wake-up" the BASIC Stamp from its low-power mode. Upon reset, the
' I/O pins are set to inputs for approximately 18 ms before returning
' to their previous directions and states. If you have an output pin set
' to a logical 1 state (+5V) and you use the SLEEP command, every 2.3 seconds
' during sleep mode that I/O pin will switch to an input for 18 ms causing
' a momentary signal loss. This "power glitch" is easily viewable with an
' LED and a 470 ohm resister tied to an I/O pin and switched on just before
' entering sleep mode. In many cases this problem can be remedied by tying
' a pull-up or pull-down resistor to the I/O pin in question to provide
' a constant source of power should the I/O pin change directions. Allowing
' a PBASIC program to end naturally, or using the END command, will exhibit
' the same "power glitch" behavior because the interpreter chip enters
' a low-power state.
'
' SUDDEN DEATH, BRAIN AMNESIA, NONRESUSCIATING SITUATION
' Life Terminates after power off, or by running another program. If a
' 2nd program is run (or the same program run a 2nd time), it will put all
' 0s into the EEPROM, thus destroying any memories and the original identity.
' It will be useless trying to resuscitate and bring back the original
' memories.
'
' ALTERNATE IDENTITY SYNDROME - The stamp is reset causing the program to
' run again, and the birthing process takes place and a different identity
' emerges.
'
' STROKE - The stamp is reset or repowered. It tries to communicate with
' other stamps but it is not in sync and the serial command hangs.
' It is unable to reply or do anything at this point.
'
' STUTTERING - Battery low causing short term repeating system resets