VideoJuegoPIC - Funcionamiento VideoJuegoPIC - Operation

El diseño del hardware es absolutamente simple. The hardware design is quite simple. La fuente de alimentación es justamente un regulador estándar 7805 para conseguir el voltaje a 5v, y tiene un diodo y un casquillo en la entrada así que puede ser alimentada con CA y CC (el voltaje de entrada debe ser 8.15v ). The power supply is just a standard 7805 regulator to get the voltage to 5v, and has a diode and fittings at the entrance so it can be powered with AC and DC (the input voltage should be 8.15v).
Dos joysticks de C64/Amiga/Atari se utilizan como entrada para los juegos. C64/Amiga/Atari of two joysticks are used as input for games. Cada mando tiene cuatro interruptores de dirección (encima, abajo, de izquierdo, de derecho) y un interruptor de fuego. Each command has four switches of direction (above, below, from left to right) and a switch of fire.
El vídeo es generado por dos bits DA, usando solamente dos resistencias y la impedancia de entrada de la TV. The video is generated by two-bit DA, using only two resistors and the input impedance of the TV. Para poder conseguir una resolución más alta, el software utiliza PORTB como registro. In order to achieve a higher resolution, the software used as a PORTB register.
El audio tiene un solo bit  de tal modo que se limita a una señal de audio cuadrado. The audio has a single bit in a way that is limited to an audio signal square. El potenciometro de 1k y la resistencia de 2k7 forman un divisor del voltaje que hace un límite ajustable del voltaje de cero a 5*1/(1+2.7) =1,35v que asume que la resistencia de  carga es mucho más grande que 1k. The potentiometer of 1k and the resistance of 2k7 form a voltage divider that makes an adjustable threshold voltage from zero to 5 * 1 / (1 +2.7) = 1.35 v assumed that the resistance load is much larger than 1k . El audio puede solamente conducir una línea de entrada en una TV, un amplificador o algun similar, pero no auriculares o dispositivos similares con impedancia baja. The audio can only drive a line input on a TV, an amplifier or some similar, but not headphones or similar devices with low impedance. Como la salida de audio es solamente una onda cuadrada los sonidos del audio son terribles pero al menos el sistema tiene sonido aunque que suena malo. As the audio output is only a square wave audio sounds are terrible but at least the system is sound although it sounds bad.

Palancas de mando. Levers of command.

Img_01
Una palanca de mando clásica Tac2 A joystick classical Tac2
Los joysticks usados para este juego son viejas palancas de mando de C64/Amiga/Atari. The joysticks used for this game are old levers of command C64/Amiga/Atari.
Img_02
Diagrama esquemático para la palanca de mando compatible 64 de la CA Schematic diagram for the joystick compatible 64 of the CA
. .

Conectar el sistema con una TV. Connect the system with a TV.

Conectamos el sistema con una TV usando un cable scart. We connect the system with a TV using a scart cable.
Img_03
Diagrama esquemático para el sistema que conecta a una SCART-entrada. Schematic diagram for the system that connects to a SCART-entry.

Cómo generar las señales de video en software usando el PIC How to generate the video signals in software using the PIC

Señales video Video signals
Para entender un poco  sobre la generación de las señales video en tiempo real, se debe saber como trabajan las vídeo-señales detalladamente. To understand a little about the generation of video signals in real time, you should know how to work the video signals in detail.


Cómo funciona una TV estandar. How does a standard TV.
Un TV estándar se construye con un tubo de vacío, que tiene una pantalla de fósforo en la cual un cañón bombardea con electrones. A standard TV is built with a vacuum tube, which has a phosphor screen on which a cannon bombarded with electrons. Cuando los electrones del cañón golpean la pantalla, el fósforo emite luz mientras el cañón tire a electrones en él, y también tiene una posluminiscencia corta. When the electrons hit the screen of the canyon, the phosphor emits light when the electron gun to pull on it, and also has a short posluminiscencia. El haz electrónico del electrón se puede doblar usando los imanes así que tira en diversas partes de la pantalla. The electron beam of electron can be bent using magnets so it pulls in various parts of the screen. Si se controla esto así,  dibuja líneas horizontales por todas partes en la pantalla en varias pasadas, mientras que la intensidad de la línea es controlada, una imagen se puede dibujar en la pantalla. If we handle that well, draw horizontal lines all over the screen on several passes, while the intensity of the line is controlled, a picture can be drawn on the screen. La pantalla es redibujada 25 veces por segundo en un sistema PAL, pero al reducir oscilación la imagen se entrelaza, mostrando primero  todas las líneas impares uniformes, así que la imagen es parcialmente actualizada 50 veces por segundo. The screen redraw is 25 times per second in a PAL system, but to reduce the oscillation image is intertwined, showing the first all lines odd uniforms, so the image is partially updated 50 times per second. Hay que agradecer a la “persistencia del efecto de la visión” del cerebro humano que la imagen  parece ser constante en vez de oscilar a 50Hz. Thanks are due to the "persistence of the effect of the vision" of the human brain that the image appears to be steady rather than swing at 50Hz. Para conseguir a color cada punto de la pantalla se divide en tres colores: rojo, verde y azul, no obstante aquí discutiremos solamente la televisión en blanco y negro, porque eso es solamente lo que es posible generar tiempo real en software usando un PIC. To get to each point on the color screen is divided into three colors: red, green and blue, however, discuss here only television in black and white, because that is just what is possible to generate real-time software using a PIC.


1

1

El haz electrónico que dibuja la pantalla The electron beam that draws the screen

Las imágenes bipartitas se convierten en una imagen entera. The images are converted into a bipartite entire image.

Diversos estándares de la TV Various standards of TV
Hay tres TV-estándares importantes: NTSC, SECAM y PAL. There are three major TV-standards: NTSC, PAL and SECAM. El NTSC es el TV-estándar americano, tiene solamente 525 líneas, pero tiene una frecuencia de  actualización de 30Hz. The NTSC is the standard TV-American, has only 525 lines, but has a refresh rate of 30Hz. SECAM  es el TV-estándar francés, ha mejorado la resolución de la estabilidad de color y de intensidad más alta pero con menos resolución del color. SECAM is the standard TV-French, has improved the resolution of the color stability and high intensity but with less resolution color. El estándar europeo es PAL (líneas que se alternan de fase, tiene 625 líneas por marco, 25 marcos por segundo. Se basa en NTSC, pero la codificación de color ha sido mejorada usando un desplazamiento de fase en cada línea para quitar los errores del color que se daban con NTSC. The European standard is PAL (which alternate lines of phase, has 625 lines per frame, 25 frames per second. It is based on NTSC, but the color coding has been improved using a phase shift on each line to remove errors color that arose with NTSC.

La información en la señal video The information in the video signal
La imagen considerada en la pantalla tiene diversas intensidades. The image seen on screen has various intensities. Como los barridos del haz electrónico sobre la pantalla, la intensidad que debe estar en la posición de la línea, se envía como nivel voltaico en la señal video. As the electron beam sweeps on the screen, the intensity that should be in the position of the line, is sent as Voltaic level in the video signal. No hay información en esta señal de intensidad sobre la que está el haz electrónico en la pantalla. No information at this signal intensity on which the electron beam is on the screen. Para solucionar esto, un pulso de sincronización se envía  al principio de cada línea para decir que la línea actual de TV está acabada y para bajar el haz electrónico a la línea siguiente. To fix this, a sync pulse is sent at the beginning of each line to say that the current line of TV is finished and to lower the electron beam to the next line. (Como la llave del <Enter> en el teclado, al escribir un texto con una computadora) La TV debe también saber cuándo está viniendo una nueva imagen, esto se realiza haciendo un patrón especial de la sincronización. (As of <Enter> the key on the keyboard, writing a text with a computer) The TV must also know when a new image is coming, this is done by a special pattern of synchronization. (Como la función del “nuevo documento” al escribir un texto con una computadora) una imagen que es 25 veces actualizadas por segundo estaría oscilando absolutamente,  por consiguiente todas las líneas uniformes se dibuja primero y entonces todos los impares, muestreando de este modo 50  imágenes por  segundo, haciendo que el cuadro oscile menos. (Because the function of the "new document" to write a text with a computer) an image that is updated 25 times per second would be absolutely ranging, therefore all the standard lines are drawn first and then all odd, sampling thus 50 images per second, making the picture less swing. Las líneas o impares de la información se envían en el patrón de la sincronización vertical, como diversos patrones para las imágenes impares y uniformes. The odd lines or the information is sent in the pattern of vertical sync, as various patterns to the images and odd uniforms. La señal de video tiene una gama de voltaje de 0 a 1V, donde 0.3V representa negro, y 1.0V es blanco (las intensidades grises tienen voltajes entre estos valores). The video signal is a voltage range from 0 to 1V, which represents black 0.3V and 1.0V is white (the intensities have gray voltages between these values). Los niveles cerca de cero representan pulsos de sincronización. The levels near zero represent sync pulses.


1

Cuadro del “osciloscopio” - de una explorar-línea Table of the "scope" - a scan-line

Las líneas The lines
La imagen se divide en líneas, él es la parte más importante de la imagen puesto que contiene los datos de la imagen. The image is divided into lines, it is the most important part of the picture because it contains the image data. Las líneas son de 64us de largo. The lines are long 64us. Primero un pulso largo de sincronización de 4us es enviado, fijando la señal llana a 0V, para decir la TV que está viniendo un giro nuevo. First a long pulse synchronization 4US is sent, setting the signal flat to 0V, to say the TV is coming to a turning again. Las viejas TV eran más lentas, así que necesitaban 8us después del pulso para conseguir el haz electrónico en la posición. The old TV was slower, so I needed 8us after the pulse to get the electron beam in the position. Durante este tiempo la señal se guarda en el nivel negro. During this time the signal is stored in the standard black. El retraso de 8us es seguido por los datos de la imagen para 52us, dibujados en la pantalla de izquierda a derecha con las intensidades obtenidas de la señal video. The delay of 8us is followed by the image data to 52us, drawn on the screen from left to right with the intensities obtained from the video signal. El negro es representado por 0.3V y como el voltaje aumenta la intensidad, con la intensidad máxima se tiene 1.0v (blanco). The black is represented by 0.3V and as the voltage increases the intensity, with the maximum intensity is 1.0v (white).

Juntando las líneas como una imagen Gathering lines as a picture
Una imagen se construye de 625 líneas, pero una TV no muestra 625 líneas. An image is constructed of 625 lines, but not a TV show 625 lines. Algunas de las líneas se utilizan para los pulsos de sincronización, y algunas líneas son invisibles porque las viejas TV necesitaron un cierto tiempo para mover el haz electrónico desde el fondo de la pantalla. Some of the lines are used for sync pulses, and some lines are invisible because the old TV needed some time to move the electron beam from the bottom of the screen. (Esas líneas invisibles se utilizan hoy en día para otros propósitos, Texto-TV por ejemplo). (These invisible lines are used today for other purposes, Text-TV for example).


1

Cuadro del “osciloscopio” - de varias íneas en una señal video. Table of the "scope" - several INES in a video signal.

Los pulsos de sincronización vertical. The vertical sync pulses.
Para decirle a la TV que esté viniendo una nueva imagen, un patrón especial de pulsos de sincronización es enviado. To tell the TV that is coming a new image, a special pattern of sync pulses are sent. Puesto que el cuadro se construye a partir de dos medios cuadros, el patrón es diferente para las imágenes impares y uniformes. Since the table is constructed from two tables, the pattern is different for the odd images and uniforms. La sincronización vertical es la siguiente: The vertical synchronization is the following:


1

Este cuadro muestra los diversos pulsos de la sincronización vertical para las dos medias imágenes. This chart shows the various vertical sync pulses to the two half pictures. Los niveles son 0v y 0.3v. The levels are 0v and 0.3v.

Cómo  hacerlo en software How to do it in software
Esta es la parte sobre cómo crear la señal de video en el software, no será posible entenderlo si no se entiende la materia de la señal video descrita arriba. This is the part about creating the video signal into the software, we can not understand it if it means not the subject of the video signal described above.
Cuando se sabe como debe ser la señal de video que se quiere, es absolutamente fácil generarla en software, si tienes energía de proceso ilimitada. When one knows how it should be the video signal that we want, it is quite easy to generate in software, if you have unlimited processing power. El problema es que requiere mucha energía del procesador, pero si no tienes un procesador de gran potencia que pueda  hacerlo, de todos modos, se puede hacer pensando antes el código a escribir. The problem is that it requires a lot of energy processor, but if you do not have a high-powered processor that can do it, anyway, thinking you can do before the code to write.
En mis ejemplos del código en esta parte utilizaré las dos macros siguientes: In my code examples in this part will use the two macros follows:
DNOP - nop dual, una macro para esperar dos ciclos de reloj, en vez de dos nops DNOP - nop dual, a macro to wait two clock cycles, instead of two nops
DELAY – Un retraso de la macro que retrasa 3 veces el número de pulsos en el registro W. DELAY - A delay of the macro that delayed 3 times the number of pulses in the register W.


El hardware The hardware
Para poder generar una señal video, es necesario un mínimo hardware para poder generar niveles de señal entre 0 y 1V. To be able to generate a video signal, we need a minimum hardware for generating signal levels from 0 to 1V. Para conseguir un cuadro necesitaremos por lo menos 3 niveles. To get a table will need at least 3 levels. La TV necesita una sincronización y el nivel negro poder generar la señal video. TV needs a timing and level black power generating the video signal. Si deseas más que una imagen negra necesitarás un cierto nivel gris o blanco. For more than a black image will need a certain level gray or white. Una cierta clase de convertidor digital a analógico es necesaria, por lo menos de 2 bits para conseguir diferentes niveles. Some kind of digital to analog converter is necessary, at least 2 bits to achieve different levels. La impedancia de entrada en una TV estándar es de 75 ohmios, y usando dos resistores y un CDA de 2 bit se puede crear (como en las imágenes abajo) gracias a la división del voltaje. The input impedance in a TV standard is 75 ohms, and using two resistors and a 2-bit CDA can be created (as in the pictures below) thanks to the division of voltage.


1

Conectando ambos D0 y D1 con la tierra, el voltaje en la entrada de la TV será 0v (nivel de la sinc.) porque no se conecta nada con VDD. Both D0 and D1 connecting with the land, the voltage at the input of the TV will be 0v (level of sync.) Because it does not connect with anything VDD.

1

D1 que conecta a la tierra y D0 a 5v, pondrá el resistor 450ohm paralelamente a la impedancia de la entrada 75ohm de la TV, y con el resistor 900ohm conectado en serie, y lo agradece a la división del voltaje que éste genera 0.33v en la entrada de la TV, y ése es absolutamente negro. D1 connecting to the earth and D0 to 5v, will 450ohm resistor in parallel with the impedance of 75ohm input of the TV, and with the 900ohm resistor connected in series, and thanks to the division of voltage that it generates in 0.33v the entrance to the TV, and that is absolutely black. (el nivel negro verdadero es 0.3v) (the black level is true 0.3v)

1

D1 que conecta a la tierra y D0 a 5v, pondrá el resistor 900ohm paralelamente a la impedancia de la entrada 75ohm de la TV, y con el resistor 450ohm conectado en serie, y lo agradece a la división del voltaje que éste genera 0.67v en la entrada de la TV, y ése es gris. D1 connecting to the earth and D0 to 5v, will 900ohm resistor in parallel with the impedance of 75ohm input of the TV, and with the 450ohm resistor connected in series, and thanks to the division of voltage that it generates in 0.67v the entrance to the TV, and that is gray.

1

Conectar ambos D1 y D0 con 5v, pondrá el resistor 450ohm paralelamente al resistor de 900 ohmios, con la impedancia de la entrada 75ohm de la TV conectada en serie, y lo agradece a la división del voltaje que éste genera 1.0 en la entrada de la TV, y ése es nivel blanco. Connect both D1 and D0 with 5v, will 450ohm resistor in parallel with the resistor 900 ohms, the impedance of 75ohm input of the TV connected in series, and thanks to the division of voltage that it generates 1.0 at the entrance of the TV, and this level is white.

Con este circuito, cuatro niveles pueden ser creados. With this circuit, four levels can be created. La imagen arriba muestra los circuitos equivalentes para los cuatro diversos niveles y cómo se crean los voltajes. The picture above shows the equivalent circuit for the four different levels and how the voltages are created. Los valores del resistor no son críticos, se podrían utilizar los valores más estándares 470 y 1k en vez de 450 y de 900. The values of the resistor are not critical, the values could be used more standard 470 and 1k instead of 450 and 900.


Software contra señales video generado por componentes físicos. Software against video signals generated by physical components.
En un sistema video estándar como el de la tarjeta de un PC, la información gráfica sobre lo que se va a dibujar en la pantalla se toma de una memoria. In a system like that of standard video card for a PC, the graphic information about what is going to draw on the screen are making a memory. Esto se hace automáticamente en hardware. This is done automatically in hardware. Los pulsos de sincronización también se crean automáticamente en hardware. Sync pulses are also created automatically in hardware. En un PIC16F84 hay una memoria de 68 byte, y esa memoria se debe también utilizar para otros propósitos . In a PIC16F84 there is a 68-byte memory, and that memory is also used for other purposes. No es posible almacenar la imagen entera en memoria como en tarjetas gráficas, la imagen tiene que hacerse generado barridos de la señal video a través de la pantalla. You can not store the entire image in memory as graphics cards, the image has to be generated sweeps of the video signal through the screen. La generación de las señales video en software en un procesador tan simple es difícil, sólo las imágenes muy simples pueden ser creadas. The generation of video signals in software on a processor so simple is difficult, only very simple images can be created. La ventaja es que es absolutamente barata. The benefit is that it is absolutely cheap.

Una línea, haciendo una barra vertical. One line, making a vertical bar.
Creando línea con la información del color gris-negro-blanco-negro-gris, y repitiendo la  línea indefinidamente, una imagen se podía ver en una TV. Creating line with information from the gray-black-white-black-gray, and repeating the line indefinitely, an image could be seen on a TV. La señal contiene un pulso horizontal, seguido por el retraso y de la información del color, así que la TV podría trabar  la señal horizontalmente. The signal contains a horizontal pulse, followed by the delay and information of color, so it could lock the TV signal horizontally.

1

1

La señal de video generada por el código abajo aparecería esto en un osciloscopio. The video signal generated by the code below this would appear on an oscilloscope. Los niveles bajos son las barras negras, y el nivel grande en el centro es la barra blanca. The low levels are the black bars, and the standard big in the middle is the white bar.

La señal video generada por el código abajo parecería esto si estuvo entrada en una TV. The video signal generated by the code below it would seem if you were entering into a TV. Dos barras negras y una barra blanca. Two black bars and a white bar. (La frontera marrón se supone para ser la TV) (The brown border is supposed to be the TV)

El problema con la resolución pobre The problem with the resolution poor
En un PIC16F84 @ 12Mhz, se realizan 3 millones de instrucciones por segundo, durante exploración de línea de 64us, se realizan 192 instrucciones, y durante la parte visible de los 52us solamente 156 instrucciones pueden ser realizadas. In a PIC16F84 @ 12Mhz, there are 3 million instructions per second, during exploration of line 64us, there are 192 instructions, and during the visible part of 52us only 156 instructions can be executed. Si el valor del DA se fija para cada instrucción durante los 52us, conseguiríamos una resolución de 156 píxeles en el eje x, que es realmente malo. If the value of the DA was set for each instruction during the 52us, get a resolution of 156 pixels on the x-axis, which is really bad. Lo que es incluso peor es que los 156 píxeles no se pueden utilizar exactamente como deseas, apenas se pueden calcular el valor de un píxel en un ciclo de reloj a menos que sean siempre iguales así que puede ser generado por una instrucción de un bit del sistema. What is even worse is that the 156 pixels can not be used exactly as they wish, can hardly Estimating the value of a pixel in a clock cycle unless they are always the same so it can be generated by an instruction from a bit of system.


Obteniendo una resolución más alta cambiando los datos. Getting a higher resolution changing the data.
Si deseamos mostrar 8 píxeles en blanco y negro, almacenado en un bit de memoria se haría algo así: If you want to show 8 pixels in black and white, stored in a bit of memory would be something like this:


movlw 8 movlw 8

; el número de píxeles es 8 (1) The number of pixels is 8 (1)

contador del movwf meter of movwf

; fijar opuestamente al número de los píxeles (1) ; Set opposite the number of pixels (1)

shiftloop:

movlw COLOR_BLACK movlw COLOR_BLACK

; color determinado del defecto al negro (1) ; Specific color of the defect to black (1)

thedata del rrf, f thedata of the RRF, f

; rotar los datos a la derecha, pone el pedacito adentro llevan (1) ; Rotate to the right data, puts the chip inside bear (1)

skpnc

; comprobar si llevar, si no el píxel sigue siendo negro (1 o 2) ; See if lead, if not the pixel is black (1 or 2)

movlw COLOR_WITE movlw COLOR_WITE

; llevar fue fijado, fijan color al blanco (1) ; Lead was fixed, fix the color white (1)

movwf VIDEO_PORT movwf VIDEO_PORT

; fijar el color a DA (1) ; Set the color to DA (1)

contador del decfsz meter of decfsz

; disminuir al revés, comprobar para saber si hay cero (1 o 2) ; Decrease in reverse, check to see if there is zero (1 or 2)

shiftloop goto shiftloop goto

; si más píxeles, guardan el colocar (2) If more pixels, keep the place (2)


thedata del movfw thedata of movfw

; instalar el octeto que se cambiará de puesto hacia fuera (1) ; Install octet that will be changed to put out (1)

movwf PORTB, f movwf PORTB, f

; el primer pedacito llega a ser visible ahora (1) ; The first piece becomes visible now (1)

rrf PORTB, f RRF PORTB, f

; el segundo pedacito se cambia de puesto hacia fuera (1) , The second bit is changed from post out (1)

rrf PORTB, f RRF PORTB, f

; el tercer pedacito se cambia de puesto hacia fuera (1) , The third piece is changed to post out (1)

rrf PORTB, f RRF PORTB, f

; el cuarto pedacito se cambia de puesto hacia fuera (1) ; The fourth piece is changed to post out (1)

rrf PORTB, f RRF PORTB, f

; el quinto pedacito se cambia de puesto hacia fuera (1) , The fifth bit is changed from post out (1)

rrf PORTB, f RRF PORTB, f

; el sexto pedacito se cambia de puesto hacia fuera (1) ; The sixth bit of switching out because (1)

rrf PORTB, f RRF PORTB, f

; el séptimo pedacito se cambia de puesto hacia fuera (1) , The seventh bit is changed from post out (1)

rrf PORTB, f RRF PORTB, f

; el octavo pedacito se cambia de puesto hacia fuera (1) ; The eighth bit is changed from post out (1)

Este código hace salir los bit de un byte al puerto de video, como el ejemplo anterior, pero éste es mucho más rápido, aunque requiere cambiar los pins. This code does leave the bit of a byte to the port of video, like the example above, but it is much faster, although it requires changing the pins.


1

Los caracteres se dibujan solamente en cada segunda línea como se describe anteriormente. The characters are drawn only every second line as described above.

El ejemplo de arriba usa un pulso de reloj por bit, dando una resolución de 156 píxeles. The above example uses a pulse clock by bit, giving a resolution of 156 pixels. En el juego del pong que el tiempo de setup se puede ver cuando el texto se exhibe en la pantalla, se hace usando este método, Las secuencias son 8 caracteres  pero sería posible conseguir 10 caracteres en la pantalla. In the game of pong that the time of setup can be seen when the text is displayed on the screen, is done using this method, sequences are 8 characters but it would be possible to get to 10 characters on the screen. En pong, los bits que se cambiarán de puesto se toman de una posición de memoria que contiene  8*8 bits = 8 byte. In pong, the bits that will change because they are taken from a position of memory that contains 8 * 8-bit byte = 8. Para cada línea estos 8 bytes tienen que ser calculados leyendo los caracteres de la secuencia de los datos de la eeprom, donde se almacena, y después conseguir el mapa de bits correcto , y almacenar los datos de imagen en la memoria. For these 8 bytes each line must be calculated by reading the characters of the sequence data from the eeprom, which is stored, and then get the bitmap correct, and store the image data in memory. Hacer esto para 8 caracteres toma mucho tiempo, así que se hace durante un scanline entero. 8 characters to do this takes a long time, so it makes for a whole scanline. La razón por la que el texto solamente exhibe una línea cada segundo es que el procesador está calculando la línea siguiente para mostrar durante las líneas negras entre líneas exploradas de los gráficos. The reason that the text only displays one line each second is that the processor is calculating the next line to show during the black lines between the lines of the scanned image.
Así pues, este método permite mostrar gráficos con una resolución mucho más alta, pero ocupa el PORTB entero durante la operación. Thus, this method allows you to display graphics at a resolution much higher, but occupies the entire PORTB during the operation. Puede ser que parezca al principio imposible utilizar el PORTB para hacer otra cosa más, pero es posible. Might seem impossible to use the principle PORTB to do anything more, but it is possible. Puede ser utilizado fácilmente como salida si un pin, el PORTA, se utiliza para inhabilitar el hardware unido a PORTB cuando se utiliza como registro de cambio. It can be used easily as if an output pin, bearing, is used to disable the hardware attached to PORTB when used as a record of change. Es también posible utilizarlo como entrada cuando no está siendo utilizado para cambiar un registro. It is also possible to use it as input when not being used to change a record. En los juegos se necesitan muchos pins para conectar el joystick, pero conectar el joystick  directamente es peligroso, porque cuando se usa el joystick utilizado como salida podría quemarse el buffer del puerto. In games requires a lot of pins to connect the joystick, but directly connecting the joystick is dangerous, because when you use the joystick used as exit could burn the buffer port. Esto se soluciona usando resistencias pull-up de 100k, y las resistencias de protección de 1k. This is solved using pull-up resistors of 100k, and the resistance of the protection of 1k. Esto da un voltaje cerca de cero, cuando se pulsa el interruptor del joystick , cuando el joystick es leído por el puerto, pero para proteger el puerto contra cortocircuitos a tierra cuando es utilizado como salida cuando el puerto se utiliza como registro de cambio. This gives a voltage close to zero, when pressed the switch of the joystick, when the joystick is read by the port, but to protect the port against short circuits to ground when used as output when the port is used as a record of change.


La sincronización vertical. The vertical sync.
Para conseguir que la TV saque la señal video, deben ser generados los pulsos verticales. To get the TV out the video signal must be generated pulses vertical. Se puede hacer mediante el código siguiente: It can be done using the following code:


Shortsync:

; etiqueta “Shortsync”, entrada para el generador corto de la sinc. ; Label "Shortsync 'entry to the generator short of sync.

movwf counter1 movwf counter1

; fijar counter1 al número de shortsyncs ; Counter1 fix the number of shortsyncs

shortsync_l0:

; etiquetar “Shortsync_l0”, entrada corta del lazo de la cuenta de la sinc. ; Labeled "Shortsync_l0" entry short loop from the account of sync.

porta del bcf, 0 Carriers of the BCF, 0

fijar llano al synclevel (mordido 1) synclevel to fix flat (bitten 1)

portb del bcf, 0 portb of BCF, 0

; fijar llano al synclevel (mordido 0) ; To fix flat synclevel (bitten 0)

dnop DNOP

;

movlw 0x1d movlw 0x1d

;

movwf counter2 movwf counter2

; fijar counter2 a “30us” ; To fix counter2 "30us"

nop

;

bsf PORTA, 0 BSF PORTA, 0

; fijar llano al negro ; Fix the flat black

shortsync_l1

; etiquetar “Shortsync_l1”, sinc. ; Labeled "Shortsync_l1," sync. corta retrasa el lazo Short delays the loop

decfsz counter2 decfsz counter2

; retrasar el contar ; Delaying the count

shortsync_l1 goto shortsync_l1 goto

; el lazo si no acabó con retrasa ; If the tie ended with no delays

decfsz counter1 decfsz counter1

; número de la cuenta de shortsyncs ; Number of the account shortsyncs

shortsync_l0 goto shortsync_l0 goto

; si más shortsyncs, guardan el colocar If more shortsyncs, keep the place

retlw 5 retlw 5

; volver y fijar W al número de los longsyncs (5 longsyncs) ; Go back and fix the number of W longsyncs (5 longsyncs)

vertsync:

;

movlw 5 movlw 5

;

videostuff de los btfss, 0 videostuff of btfss, 0

;

movlw 6 movlw 6

;

shortsync de la llamada shortsync the call

;

videostuff del incf videostuff of incf

;

longsync:

;

movwf counter1 movwf counter1

; fijar el synccounter al número de los longsyncs (1) ; Synccounter to fix the number of longsyncs (1)

longsync:

; etiqueta “longsync” ; Label "longsync"

movlw 0x1d movlw 0x1d

; (1) (1)

movwf counter2 movwf counter2

; fijar opuestamente a 30us (1) ; Set opposite 30us (1)

porta del bcf, 0 Carriers of the BCF, 0

; fijar llano al pedacito 1 (1) de la sinc. ; Fix the flat bit 1 (1) of sync.

portb del bcf, 0 portb of BCF, 0

; fijar llano al pedacito 0 (1) de la sinc. ; Fix the flat bit 0 (1) of sync.

longsync_l1

; etiquetan “longsync_l1”, sinc. ; Labeled "longsync_l1," sync. larga retrasan el lazo Long delays the loop

decfsz counter2 decfsz counter2

; retrasar el contar (1) ; Delaying the count (1)

longsync_l1 goto longsync_l1 goto

; el lazo si no acabó con retrasa (3) ; If the tie ended with no delay (3)

nop

;(1) (1)

porta del bsf, 0 Carriers of the BSF, 0

; fijar llano al negro (1) ; Fix the flat black (1)

nop

;(1) (1)

decfsz counter1 decfsz counter1

; número de la cuenta de shortsyncs (1 o 2) ; Number of the account shortsyncs (1 or 2)

longsync_l0 goto longsync_l0 goto

; si más shortsyncs, guardan el colocar (3) If more shortsyncs, keep the place (3)

movlw 5 movlw 5

; fijar el número de shortsyncs a 5 (1) ; Fix the number of shortsyncs to 5 (1)

videostuff de los btfss, 0 videostuff of btfss, 0

; comprobar si segundo campo (1 o 2) ; See if second field (1 or 2)

movlw 4 movlw 4

; sí, hacer 4 shortsyncs en lugar de otro (1) Yes, make 4 shortsyncs instead of another (1)

shortsync goto shortsync goto

; hacer esos syncs cortos ; Make these shorts syncs

Este código genera la sincronización de pulsos necesarios., según lo descrito anteriormente. This code generates synchronization pulses required., As described above.

Los juegos Games

1



Pong. Pong.


La lógica del juego es sobre todo guardar la bola dentro de la pantalla. The logic of the game is all about saving the ball inside the screen. Las primeras líneas son apenas blancas, y es en las líneas superiores donde la lógica del juego está realizada. The first lines are just white, and is in the lines above where the logic of the game is done. Para todas las líneas en el campo de juego verdadero hay dos clases de líneas, las que está con una bola y las que están sin ella. For all the lines in the field of game there are two classes of lines, which is a ball and those without it. Primero muestra al que no tiene la bola, y si es necesario al jugador izquierdo, entonces la línea es negra hasta que el jugador adecuado debe ser mostrado (o no). First shown to not have the ball, and if necessary the player left, then the line is black until the appropriate player must be shown (or not). Las líneas con una bola encendida son similares, con la diferencia de que la bola se debe demostrar en el área negra. The lines are lit with a ball like, with the difference that the ball must be shown in the black. Haciendo dos retardos en el PIC antes y después hace que se muestre la bola, donde los retardos dependen de la posición x de la bola. Making two delays in the PIC before and after makes it appear the ball, where delays are dependent on the x position of the ball. Desde que el reloj cuenta tres pulsos de reloj, la bola se mueve en pasos  grandes en el eje de las x. Since the clock account of three pulses clock, the ball is moving in big steps in the axis of x.
En la parte inferior de la pantalla, se muestra el marcador. At the bottom of the screen, it displays the marker. Se saca con el método descrito anteriormente. It was taken out with the method described above. En la mayoría de las líneas la rutina  comprueba si el sonido está activo. In most lines routine checks to see if the sound is active.
Todos los menús de texto tienen su texto almacenado en la eeprom en strings de tipo long char de 8bits.El texto se muestra solamente cada segunda línea porque en la primera línea el texto se extrae de la eeprom y los datos de memoria de imagen se almacenan en un área del buffer. All the menus of text are stored in text strings in the eeprom type of char long 8bits.El text is displayed only every second line in the first line because the text is drawn from the eeprom and data memory image is stored in an area of the buffer. En la segunda línea se muestra el resultado. On the second line shows the result.


1



Tetris. Tetris.


La lógica del juego The logic of the game Tetris primero se hizo con Borland C en el DOS en un PC, apenas para conseguir la lógica correcta antes de que fuera hecha para el ensamblador de PIC. Tetris was first made with Borland C in the DOS on a PC, just to get the correct logic before it was made for the assembly of PIC. Los bloques se almacenan en memoria en un formato comprimido, y después se descomprimen según el ángulo actual de un área de buffer donde se almacena como coordenadas relativas. The blocks are stored in memory in a compressed format, and then decompressed according to the current angle of a buffer area where it is stored as coordinates on. Tres diferentes rutinas pueden utilizar el bloque en el área del buffer para operar en la pantalla. Three different routines can use the block in the area of the buffer to operate on the screen. Estas rutinas son las que hacen posible que un bloque sea desplazado de un lado a otro y que pueda ser depositado cualquier bloque en la parte de abajo. These are the routines that make it possible for a block is moved from side to side and that any block can be deposited on the bottom. La rutina de la salida es absolutamente similar a la que saca los caracteres a la pantalla, a excepción de que esta no tiene que estar rápidamente poniendo los píxeles negros entre los bloques, así que los cambios que hace para mostrar el campo de juego en la pantalla, es bastante fácil. The routine of the output is absolutely similar to that which brings the characters to the screen, except that this need not be quickly put the black pixels between the blocks, so that changes made to show the playing field in the screen is fairly easy.
En la mayoría de las líneas se llama una rutina de música cambiando el canal de audio por intervalos con diversas frecuencias, está hecho en todas las líneas excepto las primeras. In most of the lines is called a routine of changing the music channel audio on and off with different frequencies, is done on all lines except the first. Debido a esto la música se distorsiona bastante. Because of this music is quite distorted. La música está en un formato comprimido en la eeprom, con un tono y una longitud almacenados en un byte. The music is in a compressed format in the eeprom, with a tone and a length stored in a byte. Todas las frecuencias tienen que ser un múltiplo de la frecuencia de líneas exploradas, así que las frecuencias no son exactamente correctas, y ésta hace que el sonido de la música sea incluso peor. All frequencies must be a multiple of the frequency of lines scanned, so that the frequencies are not exactly correct, and it makes the sound of the music is even worse. Aunque el sonido es muy malo, al menos tiene sonido. Although the sound is very bad, at least has sound.
La puntuación se muestra con el método shift-out, sacar a la pantalla,  No hay menús en Tetris porque no había mas sitio en memoria. The score is displayed with the shift-out method, remove the display, no menus in Tetris because there was no more place in memory.

Programación PIC PIC Programming

Que necesitamos: We need:
-Programador T-20 Programmer-T-20
-ICprog (Puedes descargarlo en la seccion descargas o aqui ) -ICprog (You can download it in the downloads section or here)
-Parche XP ICprog (Puedes descargarlo en la seccion descargas o aqui ) Patch-ICprog XP (you can download it in the downloads section or here)
-Ficheros de los juego Tetris y Pong -Files of the game Tetris and Pong

Primerdo descargamos el ICprog y el parche y metemos los dos archivos en el mismo directorio, seguidamente ejecutamos el archivo icprog.exe. Primerdo downloaded the patch and ICprog and get the two files into the same directory, then run the file icprog.exe. En la parte derecha superior seleccionamos el pic que vamos a utilizar (en este caso el pic 16f84A). In the upper right select the pic we are going to use (in this case the 16f84A pic).


ahora conectamos el programador al ordenador mediante un cable rs-232 estandarizado y instalamos el pic como aparece en la imagen siguiente. Now connect the programmer to your computer via a cable rs-232 standard and installed the pic as it appears in the picture below.

Seguidamente presionamos sobre -archivo>abrir datos>y seleccionamos el juego a cargar. He then pressed on file-> open data> and select the game to load. Despues vamos a la pestaña comando y seleccionamos borrar todo (para asegurarnos de tener el pic en blanco). Then we will select the tab command and erase everything (to make sure you have the pic blank). Una vez esto nos queda seleccionar comando y programar todo. Once we select this command and to schedule everything.

ya tenemos listo el pic para jugar. we already have the pic ready to play.


Inicio | Funcionamiento | Materiales Home | Administration | Materials | Descargas | Fotos y Videos | Fotolitos | Links | Acerca de | Downloads | Photos and Videos | Fotolitos | Links | About
©VideoJuegoPIC © VideoJuegoPIC Freelance web designer