DIFFERENT BITS
Listing 4
//wait for first button press
while (!input(button0));
//now grab timer1 value as random seed
seed=get_timer1();
//1. Create an initial population of candidate solutions
//randomly initialize pop
for (i=0;i<pop_size;i++){
for (j=0;j<dna_size;j++){
pop[i][j] = (rand()/1213)+95; //generate random number between 0 and 32,767
//we need to scale down to an interval of 95-122 —> 27 numbers so divide by 1213 and shift up 95
}
}
//put initial values out on screens
put_values();
delay_ms(500);
Listing 5
while (true){
//wait for a button press
in=0;
in= input_b();
while (in==0){
in= input_b();
}
pull-down resistor on every pin in the
port (B0– 7) to keep the pins at a low
value when the button is not depressed,
and to keep the pins without buttons
from accidentally straying to high
values. Finally, we hook up four other
pins as serial outputs, which CCS C
lets us do easily in software. Any four
extra pins should work, but avoid pin
A4 because it is an open drain output.
Refer to the included schematic for
any additional details.
The Code
The first thing to note is the header
file which contains the necessary
specifications for the four serial ports,
as well as standard fuses, clock speed,
BILL OF MATERIALS
• 16F877A PIC microcontroller
• 20 MHz crystal + capacitors or
ceramic resonator with internal
capacitors
• Nine 10K resistors (or similar value)
• Four pushbuttons
• Four serial LCD screens
Listing 6
//which button?
//chosen button reproduces with the
rest
if (in==2){
fputs(“ winner”,1);
breed_index=0;
}
else if (in==4){
fputs(“ winner”,2);
breed_index=1;
}
else if (in==8){
fputs(“ winner”,3);
breed_index=2;
}
else if (in==16){
fputs(“ winner”,4);
breed_index=3;
}
else {
fputc(254,1);
fputc(1,1);
fprintf(1,” error: %u”,in);
break;
}
breed(breed_index);
Listing 7
//make old population == new population
for (i=0;i<pop_size;i++){
for (j=0;j<dna_size;j++){
pop[i][j] = pop_new[i][j];
}
}
//DISPLAY
put_values();
}
quit();
}
Listing 8
void quit(void){
while (1){
;
}
}
Listing 9
void put_values(void){
int j;
//lcd 1
//clear screen
fputc(254,1);
fputc(1,1);
for (j=0;j<dna_size;j++){
fputc(pop[0][j],1);
}
//lcd 2
//clear screen
fputc(254,2);
fputc(1,2);
for (j=0;j<dna_size;j++){
fputc(pop[1][j],2);
}
//lcd 3
//clear screen
fputc(254,3);
fputc(1,3);
for (j=0;j<dna_size;j++){
fputc(pop[2][j],3);
}
//lcd 4
//clear screen
fputc(254,4);
fputc(1,4);
for (j=0;j<dna_size;j++){
fputc(pop[3][j],4);
}
}
SERVO 09.2008 71