Tuesday, 14 June 2016

The Torment of Alfred McSilvernuts: The "Game"

We now know how to control outputs and read input signals. Together with timers and interrupts that's all we need to build a simple controller and program something to control with it. No, let's top it up a notch and make a whole console! Let's start off with the connection diagram:

Circuit diagram of my very first "console".
Isn't it glorious? Powered by a single ATtiny85, it has a two button "controller" for one player and a mind-blowing three pixel monochrome LED "display". Yeah, those quotation marks are there for a reason.


So, my plan is to use the PB2..0 pins as output ports to light up some red LEDs and the PB3 and PB4 pins to read the button state. Clear as the fifth beer of the evening after passing through the system, no? Only noteworthy thing is that I have connected the buttons straight to the ground as I'm making my job easier by utilizing the internal pull-up resistors of the chip.

The circuit assembled on two breadboards.

Our "console" needs also a "game". With three LEDs and two buttons one doesn't make a new Megaman but how about this:  

A successful business man, Alfred McSilvernuts, woke up to evil laughter.

"Mwahaha, thy time was short but the list of thy sins is out of this world. However, as a nice guy that I am, I give thee one last chance to repent."

"NEVER,", yelled McSilvernuts "for my heart is black as my ass is wide! Those poor bastards deserve all the shit I managed to sell them and all their hard-earned money belongs rightfully to my bottomless bank account!"

"Very well. For now on, thou shall spend thy eternity trapped in this one-dimensional doom. No matter which direction thou travel, no matter how far and for how long, thou shall find thee circling around, always ending up in this very place thou now stand on."

Then there was a loud, low roar, like the heaven itself had emptied its bowels after a near-fatal combination of hard liquor and questionable fast food. The roar faded, ending up in complete silence and emptiness. Except for Alfred McSilvernuts and his prison.

Shitty backstory but so will be the "game" itself; the player moves Alfred (i.e. a lit LED) around his prison (a row of LEDs). There's no goal, no way to lose, no way to win. The quotation marks have found their place. However, "The Torment of Alfred McSilvernuts" is an important step as it will contain all the core principles (except for sound) that I'll be using in the future games and devices as well.

Let's start off with the topic of last post: timers and interrupts. To make games run smoothly, I want run them at a constant frame rate. To do this I'll use the Timer/Counter0 Overflow interrupt to tell the processor how often it should execute the frame worth of game logic, update the screen, read the controller input, and so on.

First, we'll add our preamble to the source code:
 #define F_CPU 1000000UL  
 #define L_BTN 0b10000  
 #define R_BTN 0b01000  
   
 #include <avr/interrupt.h>  
 #include <avr/io.h>  

In addition to the lines present in the last example, I defined two constants corresponding to the pins PB4 and PB3 to which the buttons are connected. Not necessary but makes the code more readable.
 volatile uint8_t player_position = 0;  
 volatile uint8_t old_state = 0;  

Here I initialise two variables. One holding the position of the player character and the other holding the state of the pins during the previous frame.
 void init_timer(){  
   
   //Init counter  
   TCNT0 = 0;  
     
   //set the clock, prescaler 64  
   TCCR0B |= (1 << CS01) | (1 << CS00);  
   
   //enable overflow interrupt  
   TIMSK |= 1 << TOIE0;  
   
 }  

For readability, I put the initialisation code of the Timer/Counter0 to a separate funtion. With 1 MHz clock signal and prescaler of 64, I'll get for the overflow frequency 1MHz/256/64 = 61.035...Hz, which is quite nice a frame rate. And now for the interesting part:
 ISR(TIM0_OVF_vect){  
   //Read the pin states  
   uint8_t pin_state = PINB;  
   
   //Move left if L_BTN down and the button state has changed  
   if (L_BTN & ~pin_state & old_state)  
     if (player_position == 0)  
       player_position = 2;  
     else  
       player_position--;  
   
   //Move left if R_BTN down and the button state has changed  
   if (R_BTN & ~pin_state & old_state)  
     if (player_position == 2)  
       player_position = 0;  
     else  
       player_position++;  
   
   //replace the old pin state with the current one  
   old_state = pin_state;  
     
   //Clear "screen"  
   PORTB &= ~0b00111;  
   
   //Put "player" on the "screen"  
   PORTB |= (1 << player_position);  
   
 }  

The Interrupt Service Routine for the Timer0 Overflow is the heart of the program. Called every frame, it contains all the game logic and input/output code. In the beginning, we define a new local variable pin_state and assign the current state of the pins to it. The pins are accessed through PINB register and it contains the states of both the input and output pins.

Next comes the game logic; we check whether a button is pressed and move the player character accordingly. When a button is pressed, it connects the corresponding input pin to the ground or LOW signal. When not, the pin is set HIGH (why? keep reading..). To get the state of the left button, we take bitwise AND (&) between L_BTN and pin_state. This is true ONLY if the bit in pin_state corresponding to one defined in L_BTN is HIGH. But wait! That's not what we want. We want to know whether it is LOW. This is done simply taking the bitwise inverse (LOWs to HIGH and vice versa) of pin_state with the NOT (~) operator.

In addition, we take the bitwise AND with the old_state variable. This ensures that the expression is true only when the old_state of the pin was HIGH (i.e. the button was not pressed down) during the previous frame. Now the if clause reacts only when the button is pressed down and doesn't care whether the player holds it down or not.

If the following conditions apply, then the program moves the player. Since my high-tech display has three LEDs, the player has three possible positions marked with numbers 0, 1, and 2. When the left button is pressed, the program tries to move the player character left by subtracting one from the position. If the player is far left (position is 0), it jumps over the edge to the far right.

The same procedure is repeated for the right button and after that the old_state is replaced with the current one to be passed to the next frame. Then the display is cleared by setting all the output pins to zero. The NOT operator flips 0b00111, where I marked the output pins with ones, to 0b11000. Now when I take the bitwise AND with PORTB, it leaves the first two bits as they are and sets the last three to LOW.

The last step is to place the player on screen. This is done by shifting 1 or 0b001 the number of bits indicated by player_position and taking bitwise OR with PORTB to set the output and after the frame is completed and the program moves to wait for the next interrupt.

And here's the result! Bon Appétit!




Tuesday, 7 June 2016

Pull up my input

Erm, change of plans. Last time I referred to my plant watering machine but a couple of complications turned up. First, I still haven't gotten all the parts I need. Sometimes you can save a good deal of money by ordering components from China but as a downside it might take a while.

The second problem is with the power supply design. In brief, I need two different voltages: +5 volts for the controlling circuit (microcontroller and relays) and +12 volts for the solenoid valve that dispenses water from the reservoir to the plant. I have an AC adapter which produces +12 volts. At first I planned to use a couple of resistors as a voltage divider to drop it down to 5V but I soon realised it would be a stupid idea. My circuit doesn't require much energy but the voltage divider as a power supply would increase the power consumption manyfold - such a waste! For the sake of sanity (and my electricity bill), I now plan to use a voltage regulator instead. Unfortunately I don't have any which means that I'll have to visit the electronic parts store again..


It seems that my future in robotic agriculture has to wait. I did get some buttons via mail though (and a free disposable razor too!). Thus it's a good moment to go through how to use an AVR's I/O pins to read input.  

In C, the direction of the pins is once again set through the Data Direction Register DDRB. As a reminder, setting a bit to HIGH sets the corresponding pin as output and LOW as input. Say, if I want to use PB4 and PB3 as inputs and PB2..0 as outputs, I'll set DDRB to

 DDRB = 0b00111;  

..aand, that's it! To read the state of the pins into the variable x, for example, I simply read PINB register:

 x = PINB;  

Now x contains the states of all the pins as they were at the moment of reading. As PINB gives out both input and output pin states, we still need to pick out the right pin. To check the state of the pin PBn, one can do it for example followingly:

 x & (1 << n)  

1 << n shifts 1 to left n positions. For example if I want to read the state of PB3,
1 << 3 = 0b01000. Bitwise AND with x then results to 0 if the corresponding state is LOW and to a non-zero value if it is HIGH.

In principle this is sufficient to read the input but there's one more very beneficial trick, especially to be used with buttons. With PB4 and PB3 as inputs, I also set

 PORTB = 0b11000;  

This sets the output pins off and the input pins...on? In some sense, yes. Setting PORTB bits of input pins controls whether so called internal pull-up resistors are used or not.

The pull-up resistor raises the pin voltage when the switch is opened.

A pull-up resistor has a large resistance and it is connected between the input pin and the HIGH voltage. If the pin is disconnected, a tiny current goes through this resistor and sets the state of the pin HIGH. However, if pin is connected to the ground, the large resistance eats away all the voltage allowing the pin to go LOW.

Unless the pin is connected to a logic LOW or HIGH at all times, it is necessary to use pull-up resistors. Otherwise some electrons might be left to hang around on the pin when they shouldn't be. This potentially makes the state of the pin go nuts, which can mess up with the behaviour of the circuit.

AVR are quite handy that they have internal pull-ups, otherwise one would have to connect extra resistors to the pins to take care of those pesky, free-loading charge carriers. These internal pull-ups make using buttons on AVR very simple; all you have to do is to connect a button between ground and the pin. Then set the corresponding PORTB bit to one to enable the pull-up and your microcontroller is all ready to read some button states!

Monday, 23 May 2016

Timers and Interrupts

In the future my posts will be roughly divided into two categories. The first one will be more technical containing the posts where I go through how to do this and program that in a detailed manner. The second one contains all the rest that doesn't make the brain (whether yours or mine) wanting to escape through the ear. The post you're reading right now belongs (unfortunately) to the first category.

Interrupts and timers are important topics what comes to programming of microcontrollers. An interrupt is a signal to the microcontroller that makes it put on hold whatever it is doing at the moment and do something else instead. After the interrupt is handled, the controller continues where it left off. Interrupts can be internal (e.g. a timer reaching a specific value) or external (e.g. a button connected to a pin is pressed).

Timers are simply counters that are synchronized with a clock signal. The clock can be the same that controls the CPU or it can be separate. For example, if I'd like to keep track on seconds, I can just wire an old digital watch to the chip instead of building a circuit of my own.

In ATtiny25/45/85, there are two innovatively named 8-bit timers/counters: Timer/Counter0 and Timer/Counter1. Both can be set to count clock pulses increasing their value from 0 to 255. When 255 is reached, the next pulse causes an overflow and the counting starts from the beginning. A prescaler can be assigned to the clock signal that lowers its frequency dividing it by a factor of 8, 64, 256, or 1024.

The timers can be set to cause interrupts. There are two types of interrupts: timer/counter overflow and compare match. The first one is caused when the timer value jumps from 255 to 0 and the second one when the timer value matches with the one in so called Output Compare Register. There are two Output Compare Registers, A and B, for both timer/counters.


For an example, let's rewrite the blinking LED code using a timer and interrupts. Let's say I want to toggle on-off state of the LED every 250 ms using the timer/counter overflow interrupt. If the clock frequency is 1 Mhz and I set the timer prescaler to 64, the timer ticks every 64/1000000 second or 0.064 milliseconds.  Thus an 8-bit counter overflows every 0.064*256 = 16.384 milliseconds.

For 250 ms I need thus 250/16.384 = 15.258... overflows, so I can't time exactly 250 ms with this approach. There are couple of ways to go around this limitation but I think simply rounding this down to 15 overflows (245.76 ms) is sufficient for my purpose. 250 ms was arbitrarily chosen anyway. I'll return to the other ways in another post.

Once again we start with begin the programming with preprocessing lines:

 #define F_CPU 1000000UL  
 #include <avr/interrupt.h>  
 #include <avr/io.h>  

The first line sets the clock frequency to 1 Mhz and the rest import the necessary declarations and functions for interrupts and pin I/O. Next we need a variable to store the number of overflows:

 volatile uint8_t ovf_count = 0;   

Note the use of the keyword volatile. It tells to the compiler that the value of ovf_count can change 'due to external factors' and thus has to be load every time even if the main program hasn't changed it. In this case the 'external factor' means interrupts, as they stop the execution of the main program while doing their own thing. (I don't use ovf_count outside the interrupt function so I could skip the use of volatile here but I wanted to brought it up, as it is certain to fuck up the code if omitted where needed.) 

Before getting to the main function, we define our Interrupt Service Routine (ISR) that is executed when the interrupt is fired. From the AVR libc reference we see that the so called vector corresponding to the timer0 overflow interrupt is TIM0_OVF_vect. Thus the ISR corresponding this interrupt is:

 ISR(TIM0_OVF_vect){  
   if (ovf_count < 15){  
     //increase the counter by 1  
     ovf_count++;   
   }  
   else {  
     //reset the counter and toggle pin PB0  
     ovf_count = 0;  
     PORTB ^= 1;  
   }  
 }  

Nothing complicated here. The if clause counts the number of overflows and when it reaches 15, it resets the counter and toggles the output of the LED pin. ^= is bitwise XOR that takes the bits of PORTB defined on the right hand side and flips them. The right hand side value 1 = 0b0001 picks the PB0 pin.

The main program looks like this:

 void main(){  
   
   //Init counter  
   TCNT0 = 0;  
     
   //set the clock, prescaler 64  
   TCCR0B |= (1 << CS01) | (1 << CS00);  
   
   //enable overflow interrupt  
   TIMSK |= 1 << TOIE0;  
   
   //Global interrupt enable  
   sei();  
   
   //Set PB0 as output  
   DDRB = 1;  
   
   //Enter the endless loop  
   while(1);  
   
 }  

So, mainly a bunch of acronyms picked up from the datasheet. TCNT0 (Timer/Counter Register) is the counter itself that is initialized to 0 in the beginning.

TCCR0B (Timer/Counter Control Register B) has two bits (0 and 1) that has to be set one to select prescaling factor of 64. I could do it like this:

 TCCR0B |= 0b00000011;  

Bitwise OR |= sets the last two bits 1 but leaves all the rest as they are. However, it is customary to use names of the bits (CS01 and CS00, from the datasheet) and use the bitshift operator << that moves 1 (or 0b00000001) as many bits to the left as CS01 and CS00 say. In this case 1 << CS01 = 0b10 and 1 << CS00 = 0b01. These are combined with bitwise OR so that  0b10 |  0b01 =  0b11. It might need a little practice to get used to this kind of notation (at least for me it did) but it makes the code easier to read.

TIMSK (Timer/Counter Interrupt Mask Register) is used to set which interrupts are active. In this case we are interested only in Timer0 overflow so we set the TOIE0 bit (Timer/Counter Overflow Interrupt Enable).

Thus Timer/Counter0 is all set. All we need now is to enable the interrupts globally with sei() (to disable use cli() ) and set the PB0 pin as output. After that the program enters to an endless loop that is paused only to handle the timer0 overflow interrupts. And tadah, The blinking LED v2 is finished!

But enough with the LEDs. Next time we'll do something that is actually useful. We are going to grow some flowers learn how to use buttons to control the microcontroller.

References:

http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf

Thursday, 19 May 2016

Microcontrollers part IV: The First Taste of Programming

As far as I know, there are two programming languages to program AVR: assembly and C. Assembly is a very low-level language that gets you as close to the machine level as possible. It allows to use the computing resources as efficiently as it can get but takes an ass-load more work to write and debug.

Even very simple operations like summing up three numbers from the memory can take like five lines of code to perform in assembly whereas in C one line does the job. Also C is somewhat tedious in modern standards but certainly less than assembly, making it my choice for microcontroller programming.

Finally, it's time to get cooking! Let's start with something simple: a blinking LED. What follows is a compilation from the AVR Libc Reference Manual, the ATtiny85 datasheet and my previous knowledge on the AVR programming (which is not very deep).

Let's use the pin PB0 to control the LED (see the ATtiny85 pinout here). Usually one should use a resistor to limit the amount of current passing through the LED. However, since I don't have any right now the I/O pin can output max. 40 mA of current, I can connect it directly between the PB0 and GND pins. (Note that this shortens the lifespan of both the LED and chip, though.)

Next we need the program. As usual, I open my text editor and start off by writing down definitions and includes:

 #define F_CPU 1000000UL  
 #include "avr/io.h"  
 #include "util/delay.h"  

The first line defines the clock frequency which I chose to be 1 MHz. The header file "avr/io.h" contains the definitions for I/O operations and "util/delay.h" contains the function declaration for _delay_ms() that I'll use to slow down the blinking. The rest of the program is written in the main function which is very short:

 void main(){ 
 
   DDRB = 0b0001; 
 
   while (1){  
     PORTB = 0b0001;  
     _delay_ms(250);  

     PORTB = 0b0000;  
     _delay_ms(250);  
   }  
 }  

This is the actual program that the chip starts to executed immediately after the power is connected. The first line sets the direction of the I/O pins through DDRB (Data Direction Register B). This is done by a binary number 0b0001. The prefix 0b stands for the binary number and the bits after that correspond to the pins PB3, PB2, PB1 and PB0. Since we want PB0 to be an output we set that to 1. All the other bits can be whatever, in this case 0:s or inputs.

After setting data directions, the program enters into an eternal loop that blinks the LED. The first line in the loop sets the LED on through PORTB. Here the pin-bit correspondence is the same as in the former case but the action depends how the pins are configured. If the pin set as an output, then 1 bit sets the output to HIGH and 0 to LOW. On the other hand, if the pin is configured to an input, then setting the bit controls whether the pull-up resistor is on or not. I'll talk more about this later.

After setting PORTB, the program waits for 250 milliseconds. After that it sets PORTB again but now putting the last bit to 0 i.e. PB0 to LOW state turning off the LED. The program again waits for 250 ms and then moves in the beginning of the while loop. The loop is repeated until the power source is detached from the microcontroller.

The finished program needs to be compiled and written to the chip. I saved my file as main.c and typed the following lines into the terminal:

avr-gcc -mmcu=attiny85 -Os -c main.c  
avr-gcc -mmcu=attiny85 -o main.elf main.o  
avr-objcopy -j .text -j .data -O ihex main.elf main.hex  

The first line compiles main.c, the second one links it to the libraries, and the last one produces an Intel hex file that can be uploaded to the microcontroller. Once again, if the model of the chip is different, the first two lines have to be changed accordingly.

The last step is to write the program to the chip. Plug the following into the terminal:

 sudo avrdude -p attiny85 -C ~/avrdude_gpio.conf -c pi_1 -e -U flash:w:main.hex  

If the connections and the alignment of the celestial bodies are as they should, the microcontroller should now be programmed! And here's what the result looks like:


Works like a charm! Even though I forgot to connect the operating voltage to the RESET pin.. Apparently the circuit works without it for the demo purpose but it is very unstable. Now just touching the pin with a finger causes the chip to reset which surely is unwanted behavior. Always remember to wire the RESET pin as well!

--

This concludes the Microcontrollers series that I intended as a tutorial to DIY microcontroller electronics. From the basics to setting up tools, we've now have acquired the equipment and knowledge to pursue for more complicated applications, being a small but important step closer to a working retro-style gaming system. The quest continues!
Original: https://en.wikipedia.org/wiki/File:It's_dangerous_to_go_alone!_Take_this..png

Tuesday, 17 May 2016

Microcontrollers part III: Setting up the programmer

To be functional, the microprocessor needs a program. But how can we get one inside as there's no place to stick in a USB drive?

Let's take another look at the pinout of ATtiny85:
On the right side, we see that pins PB0, PB1, and PB2 have alternative labels MOSI, MISO, and SCK. These pins are used for Serial Peripheral Interface (SPI) which is a popular protocol to make embedded devices communicate with each other. When the RESET pin is pulled to ground (as opposite to the normal case), the SPI bus can be used to program the microcontroller.

To get started with programming, we first need to install and setup some essential software to the Raspberry Pi. The easiest way to do this is to paste the following line to the terminal:

 sudo apt-get install gcc-avr binutils-avr gdb-avr avr-libc avrdude  

This installs all the necessary stuff to e.g. compile and debug the programs (gcc-avr, binutils-avr, gbd-avr, avr-libc) and write them to the chip (avrdude). If you use the Pi like a normal computer with a display, mouse and keyboard, that's probably sufficient. I have only one display and I don't want to switch between my PC and Pi all the time, so I connected my Pi to the router with an Ethernet cable and access it remotely from my PC to spice up the nerd factor. However, working over the SSH connection can be tedious sometimes, so I installed the same package on my PC to develop bigger codes on it, leaving the Pi as the chip programmer.

The next step is to edit avrdude's configuration file to list the GPIO bus as a programming device. I did this following a tutorial on adafruit.com and as I'm not planning to steal any credit, I won't copy it on my post but advice you to look up the same tutorial here. Unlike the tutorial, I chose Pi's pin #8 for RESET, #9 for MISO, #10 for MOSI, and #11 for CLK as I wanted them closer to each other. It's a matter of taste what pins you choose.

Pi's GPIO pins. Source and more info: https://www.raspberrypi.org/documentation/usage/gpio-plus-and-raspi2/

All right, time to test out whether we talk with the microcontroller. To connect the chip to Pi, I used a solderless breadboard to which one can just stick all the components and wires in. The most annoying part is to connect all the pins with individual wire. One day I'll build a neat cable for this but for now I have deal with a bunch of 60 cm (2 ft.) long spaghetti. It's a mess.

Pi's GPIO connected to the chip. The red wire is the operating voltage (+3.3 V), grey is SCK (or CLK), violet MISO, orange MOSI, white RESET, and the black is ground.
Be extra careful when making these connections. You don't want to short any pins as it might break the GPIO pins or in the worst case the whole Raspberry Pi! I accidentally did short two pins once and it jammed the whole Pi. I already thought I've done goofed but fortunately turning it off and on again brought it alive again.

After connecting the chip it is ready to be tested. Assuming you followed the adafruit tutorial, the configuration file should be in the home folder and the GPIO programmer should be named 'pi_1'. To test reading the chip type the following command to the terminal replacing 'attiny85' with the model you are using:

 sudo avrdude -p attiny85 -C ~/avrdude_gpio.conf -c pi_1 -v  

avrdude then outputs a wall of text and numbers on the screen. If everything went as expected, there should be this line somewhere near the end:

 avrdude: AVR device initialized and ready to accept instructions  

Congratulations, your microcontroller is working, connected properly and ready to be programmed and you're ready to move to the next level post! However, if it isn't, you might get something like this as I did at the first try:

 avrdude: AVR device not responding  
 avrdude: initialization failed, rc=-1  
      Double check connections and try again, or use -F to override  
      this check.  

It can mean that your chip is broken, but most likely some wires are not connected as they should be. In my case none of them were; it turned out that I can't count pins up to eight properly.

Saturday, 14 May 2016

Microcontrollers part II: Have a byte of ATtiny85

Microcontrollers come in a wide variety of models and packages. For my projects I'll use ones from Atmel's AVR family. After a long pondering, it turned out that AVR offers the best possible...erm, no. The true reason to pick AVR was that I've had one course in digital electronics that involved a project work using AVR chips. Thus I have a vague idea how to work with AVR controllers which makes my task a tad easier.

The model I'll start working with is ATtiny85. As the AVR family itself, the model was chosen after a comprehensive thought process i.e. I picked it randomly from the catalog while queuing at the local electronics store. I usually don't think too much beforehand; I tend to start with the first idea that comes to my mind and rethink if it fails.

ATtiny85 in DIP8 package
And here's the badass. To run this beast we need operating voltage of at least 2.7 volts but to get out the most of it we should crank it up to 5.5 V. With sufficient amount of volts, it can be run at the maximum clock frequency of 20 Mhz. It has 6 input/output pins, although usually one of them is reserved for other purpose. It has 8 KiB of flash memory to store the programs, and 512 bytes of RAM and EEPROM memory each to hold the run-time data and to store long term data, respectively. Such wow!

As bits and bytes are essential in digital electronics, I want to say a few words about them. A bit is the smallest unit of information in digital computing. It has two possible values: HIGH (ON, 1) or LOW (OFF, 0). In electronics these are practically implemented with voltage; either there is some or there is not. When we want to present numbers in binary, we put together multiple bits. For example with two bits we can present numbers from 0 to 3 with 0 = 00, 1 = 01, 2 = 10, and 3 = 11.

In 8-bit microprocessors the data is handled in the groups of 8 bits, which are also known as bytes. Each byte holds a value in the range of 0 to 255. Depending on the situation, bytes can represent other types of data as well, like characters or instructions for the processor. In ATtiny85, there is 8 KiB of memory for the program. KiB is often called kilobytes but the technically correct term would be kibibyte. One kibibyte is 1024 bytes, so 8 KiB would be 8192 bytes.

To put things into perspective, this is what it would approximately look like as an 8-bit grayscale bitmap (here I was forced to use PNG format which compresses it down). The picture contains 90 x 90 pixels. The "greyness" of each pixel is presented by one byte with the value in the range of 0 (black) to 255 (white). 512 bytes would be 16x32 sized rectangle to which Mario barely fits in. It is less than it would take to store this paragraph if every character was presented with a single byte! "Much" memory but sufficient for now.

Next we have to figure out how to connect the microcontroller to the rest of our chip. For this we need to get our hands on its datasheet. Datasheets are the source of all the necessary information regarding electronic components. Each component has a datasheet that tabulates its characteristics, like temperature behaviour or typical variation in parameter values, and most importantly for complicated components, how to use them. So in its datasheet, the pinout for ATtiny85 in DIP8 package looks like this:

ATtiny85 pinout from the datasheet
Holy fuck. Apparently this bastard is capable of doing way more stuff I knew. Honestly I have no idea what most of these acronymic abominations mean. Fortunately I don't have to. The essential thing for now is to know that VCC stands for positive operating voltage, GND for ground (i.e. negative end of the battery) and PB0 to PB4 are the input and output pins where we will eventually connect some buttons and displays and whatever our console needs.

According to the datasheet, PB5 is a special case. It behaves normally as the RESET pin, or technically its inverse. This means that if LOW signal is put to the RESET pin, it resets the chip and we get nowhere in our program. To prevent this we have to wire it to HIGH signal which is easiest to get from the operating voltage. Thus all I have to do is to connect the wires to the chip like this:


and voilà, it works! ...Or it would work, if it had a program in it. Now it does pretty much nothing but waste electricity. At this point we'll need to get out the Raspberry Pi but that'll be the topic of the next post.


References:

ATtiny25/45/85 datasheet

Original screenshot from the Super Mario Bros. from https://en.wikipedia.org/wiki/Super_Mario_Bros.

Thursday, 12 May 2016

Microcontrollers part I: Basic structure

Last time I wrote about the Raspberry Pi, a beer can sized computer. Now it's time to go even smaller. The following couple of posts are about microcontrollers which shall be the brain and soul of my future game console.

The microcontroller, or MCU, is simply put a very small computer crammed into a single chip. Unlike personal computers, MCUs have typically a rather humble amount of computing power but they are low cost and don't require much electricity. Therefore they are perfect to solve relatively simple tasks in embedded systems. If a desktop computer is a car and the Pi is a motorcycle, then the microcontroller would be a lawnmower: not very fast but good for its intended purpose.
Basic building blocks of a microcontroller.
The core of the MCU consists of a control unit and at least one arithmetic and logic unit (ALU). The control unit is responsible that all the action happens where it should; it translates the instructions to actual operations, temporarily stores small bits of data in registers and moves the data around the chip. It is the manager that follows the programmer's instructions telling the ALU what to do. The arithmetic and logic unit is the part that does all the number crunching and logical operations. Together the control unit and the ALU are called central processing unit, or CPU, just like the processor in the desktop computer.

In addition to the CPU, a microcontroller contains memory, input and output peripherals and quite often an internal clock. Memory comes in two flavours: volatile and non-volatile memories. Here volatile memory is synonymous with random access memory (RAM) which is fast but requires power hold information. RAM is therefore used for run-time storage of data, such as the position of the player or the number of lives left.

Non-volatile memory on the other hand retains its data even without power. However, depending on the type of the memory it is either non-writeable or slow. Non-volatile memory is thus most suitable for storing the program itself or data that needs to be preserved even when the system is down, like save states.

Input and output peripherals connect the chip to the surrounding world. Input can be, for example, signals from a controller to move the player around. Output signals can control the graphics on the screen or play funky music out of the speaker.

The last but not the least is the clock, an oscillator that produces a periodic signal that rapidly switches between ON and OFF states. The clock makes the microcontroller tick controlling the pace at which the instructions are executed.

Schema of a clock signal
Whenever you see MHz (million oscillations per second) or GHz (billion oscillations per second) mentioned in the context of computers, it most likely refers to the frequency of the clock signal. Higher the frequency, the more ticks per second. This, however, doesn't necessarily mean that a microcontroller with higher clock frequency has faster computation speed as the number of clock cycles to execute instructions depends on how they are implemented in a particular processor. Many MCUs have an internal clock but their frequency can be unstable. One uses an external crystal like in electronic watches when precise timing is required.

Well, that was a good bunch of theory. In the next post I'll make it more concrete through an example chip that I'll be using in applications once I get there. Until then, stay tuned.  


References:

James J. Brophy, Basic Electronics For Scientists, 1983, McGraw-Hill International Book Company

https://en.wikipedia.org/wiki/Microcontroller