hamstack microcontroller project platform
TRANSCRIPT
HamStack
Microcontroller Project Platform
Sierra Radio Systems
Getting Started With The
Welcome
Getting Started With the HamStack Microcontroller Project Platform
Revision 3.2 - April 2013
See appendix for document revision history.
© 2011-2013 George Zafiropoulos, KJ6VU and John Best, KJ6K
Special thank you to Robert Ralston, KJ6HFR, who contributed many edits and
improvements to this manual. Your contributions will be appreciated by all who
use it.
This guide provides a broad introduction to the HamStack microcontroller platform,
DEV-1 development board, software development tools and project examples.
For more in-depth information, we recommend the following resources.
Sierra Radio Systems' HamStack web page – www.hamstack.com
The HamStack community support web site is hosted on Yahoo Groups with a group
name of hamstack – http://tech.groups.yahoo.com/group/hamstack/
Microchip's web site for more info on the CPU chips, MPLAB, C18 compiler and
incircuit programming software – www.microchip.com
Swordfish Basic compiler website for basic language and compiler information and
general support forum – www.sfcompiler.co.uk
If you are interested in purchasing HamStack hardware, software or accessories, visit
our web store at www.hamstack.com and click on the “store” link.
We believe all material in this document is correct and up to date. There is always a
chance that something was omitted or incorrect. If you find any errors or have
ideas of how to make the document better, please email us at
- 3 -
Table of Contents
Introduction
1. CPU board hardware reference
2. DEV-1 Development Board hardware reference
3. Assembly Instructions
4. Software development tools
5. Putting it all together: Your first sample
6. Basic circuits and program examplesDigital outputDigital inputControlling relaysAnalog inputRS-232 serial outputLCD displayTemperature probe
7. Mini-ProjectsTemperature controlled fanCW beacon controller
8. Accessory and expansion boardsPrototyping backpack boardProject boardLCD display and interfaceDual 8A relay boardUSB interface
Appendix
- 4 -
Introduction
Over the last several years, we have built some very sophisticated, multi-CPU ham
radio projects using PIC microcontrollers. The power and flexibility of these
devices can be applied to many applications including repeater controllers,
beacon transmitters, keyers, antenna switches, battery monitors, etc. We had
several people ask us how to get started designing and building their own
microcontroller-based ham projects. As we thought about it, we asked
ourselves “what would the perfect platform look like?” We came up with the
following criteria…
Powerful enough to build REAL applications
Simple enough that anyone can start to learn from scratch
Open enough so you are not tied down to only one chip or language
Focus on higher level languages including C and Basic
Low cost to encourage everyone to give it a try
Small hardware that can be embedded into projects
Expandable enough to handle large projects
Examples that are relevant to the ham radio operator
As we looked around, it became obvious that nothing really met our requirements.
So, in typical ham radio fashion, we decided to build a platform that met our
criteria. We looked at various hardware devices, board form factors, language
compilers, etc. The result of that effort is a platform we call the HamStack.
The “ham” part of the name refers to the desire to target the platform to the
needs of the ham radio operator. The “stack” is a play on words that refers to
the physical design of the platform with its ability to stack multiple boards
together. Stack also refers to the “software stack” of libraries that are available
to make programming easier.
The HamStack is designed for the beginner and the experienced designer
If you are new to the world of microcontrollers or programming, don’t be afraid to
jump in. The process of designing circuits and writing programs for the
HamStack is very simple. Following the examples in this book you will be
building hardware and writing programs in no time. The HamStack supports
program development in Basic and C. You can choose the language you want
to learn or are more comfortable with.
For the more advanced user, the HamStack is a powerful hardware platform with a
high performance CPU, lots of IO and a variety of packaging options. You can
easily incorporate a HamStack CPU board into your own projects. Lots of
solder pads are provided giving you easy access to all signals.
- 5 -
People new to programming may prefer the easy to read Swordfish Basic language. Advanced programmers can take advantage of the free Microchip C18 C-language compiler for developing sophisticated programs. The HamStack library provides added functionality to build really amazing applications without developing all of the low level code from scratch.
The HamStack is openAs an open platform, we make all circuit schematics and source code for examples available to the user. Our PCB layout and stacking connector approach is designed to be as hardware compatible with the Arduino shield boards as possible. There are dozens of software tool sets that are intended for the Microchip 18F microcontrollers and should work. We specifically develop examples and software applications using the Microchip C18 and Swordfish Basic compilers and we recommend you use those tools. Thousands of professional and amateur designers and developers use these tools every day so there is a very large and diverse community of users.
The HamStack is modularA variety of boards are available including the main CPU board, add on “backpack” boards that stack on top of the CPU and “project boards” that the CPU stack can plug into. These project boards, provide additional circuitry that make a complete project. You have the option to add your own hardware functionality by customizing the prototype backpack board or design your own board to plug in.
Some assembly requiredHamStack boards are available as hardware kits to encourage ham radio operators to build their own gear. By building your own equipment, you gain a deeper understanding of how the hardware works and you are more likely to tweek and experiment. The HamStack documentation provides step by step assembly instructions. You will only need simple hand tools including a soldering iron, solder, sponge (use a medium temperature iron with a fine tip), small diagonal wire cutters to trim the leads from the bottom of the board. Our boards use all “through hole” components, not surface mount parts to make assembly easier. No particular test equipment is required but an inexpensive volt-ohm-multimeter is very handy.
How does the HamStack compare to the other hardware and software out there?There will be the inevitable comparison between the HamStack and the Arduino, Basic Stamp, PIC-EL or any of a dozen other platforms out there. There are many fine products on the market and they all have their pros and cons. Some are proprietary, some are very slow or very limited in memory space, some lock you into specific software tools or languages and most have little or no design examples or software tailored to the ham radio operator. Our goal is to make the HamStack a powerful, yet easy to use platform, ideal for learning about and deploying microcontrollers in ham radio projects.
We hope you enjoy using the HamStack as much as we enjoyed designing it.
’73 John, KJ6KGeorge, KJ6VU
- 6 -
Section 1
CPU Board Hardware Reference
- 7 -
Hardware Reference
Architecture OverviewThe HamStack is built on the 8 bit PIC 18F series of flash based microcontrollers from Microchip. These powerful “computers on a chip” are some of the most popular devices in use today. As a result there is a very large and growing community of professional and hobbyist designers and programmers that you can draw on for ideas and information. The heart of a project is the CPU board. The HamStack CPU board contains the CPU chip, crystal, voltage regulator, RS-232 interface chip and connectors. When building your own project, the CPU board can be embedded into your project. For experimentation and extending the functionality of the CPU board, you can add the prototype “backpack” board. This board stacks on top of the CPU board and provides either solder pads or a reusable solderless breadboard block. Pass through connectors allow multiple backpack boards to be stacked. The backpack board is pin compatible with the Arduino shield boards. The CPU and backpack boards can be stacked on top of the project board. This board provides several convenient peripheral devices, connectors and sub-circuits. Many projects can be built completely from the CPU and project boards alone.Since the CPU is the heart of the HamStack, it is helpful to understand a bit more about the chip itself and its IO pins.
The CPU ChipThe HamStack CPU board is designed to support the 18F series of microcontrollers that come in a 40 pin DIP (Dual In-line Package). All of our testing and application development is done with the 18F4620 and the faster 18F46K22. The HamStack CPU kits are shipped with either the 18F4620 or 18F46K22 chips. Many other 40 pin microcontrollers from Microchip will work in the CPU board but we can not guarantee that all the software compilers or examples will work.* Note that each pin may be configured to serve multiple functions but only one at a time. There are a maximum of 30 physical IO pins which can be assigned from the pool of pins on this chart.
Specification PIC 18F4620 18F46K22
Max CPU Speed 40 MHz 64 MHz
Program flash memory 64k bytes 64k bytes
RAM 4k bytes 4k bytes
Data EEPROM 1k bytes 1k bytes
Number of physical IO pins 30 30
Max analog input pins * 25 25
Max SPI serial IO ports * 1 2
Max I2C serial IO ports * 1 2
Max serial UART ports * 1 2
Max PWM ports * 5 5
- 8 -
The CPU Pins
You will want to become familiar with the physical pin names and functions they perform. One of the powerful aspects of the PIC architecture is that all of the IO pins can perform multiple functions. IO pins are not simply digital inputs or digital output but may include serial interfaces (UART, I2C, SPI), analog to digital converter inputs, pulse width modulator outputs, etc. Each of these pins has a name. The IO pins are grouped into “ports” or “registers”. The groups are named PORTA, PORTB, PORTC, etc. Each port group can have a few pins or as many as 8. On the 18F4620 and
18F46K22 CPU chips, there are 30 IO pins. They are grouped as follows…
PORT A – 6 pins – Digital IO and analog voltage inputsPORT B – 5 pins – Digital IOPORT C – 8 pins – Digital IO and serial interfacesPORT D – 8 pins – Digital IO PORT E – 3 pins – Digital IO
The individual pins are referred to by their port or register name (A, B, C, etc.) and their logical number in that group (0, 1, 2, etc.). So the first IO pin of port B (register B) is called RB0, meaning “register B, pin 0). You will become very familiar with the names of the pins and what they can be used for. You may wonder why didn’t they just call the pin “input 1”?, Since each pin can be configured to perform various functions (analog, digital, serial, etc) we use the general name to refer to the pin is “RA0”. When you look at the datasheet for the part, you can see that RA0 is also known as AN0 because it can be configured as an analog to digital converter input. These names are shortened on the PCB layout to save space so pin RD1 for example is labeled “D1”. For now all you need to become familiar with is the common pin name like RB0 (“B0”), or RC7 (“C7”).
RS232 Tx
RS232 Rx
Ground
MCLR
V+
Ground
PGD
PGC
Programming
jack
RS232 Port
Voltage
Regulators
Power+5.0v
CPU
User Programmable IO
Reset
Mode (A4)
J1-5 RE2J1-6 RA4J1-7 RC1J1-8 RC2J2-4 RB4J2-5 RB3J2-6 RB2J2-7 RB1J2-8 RB0J4-3 RC3J4-4 RC5J4-5 RC4J4-6 RA5J4-7 RD7J4-8 RD6J5-1 AN0J5-2 AN1J5-3 AN2J5-4 AN3J5-5 RE0J5-6 RE1J6-1 RD5J6-2 RD4J6-3 RD3J6-4 RD2J6-5 RD1J6-6 RD0
- 9 -
Stacking interconnect bus and Arduino compatiblity
The HamStack establishes a standard physical PCB layout and electrical signal assignments to the interboard connectors. This ensures hardware compatibility and makes the re-use of modules very easy. Each pin in the stack has a specific purpose. The hardware reference sections specify the exact pin assignment and what they are used for. There are 7 interboard connectors. Four of them match the interboard connectors of the Arduino Uno and similar boards. This means that you can take an Arduino shield, like a relay board or a Zigbee RF module and plug it on top of a HamStack CPU board and there is a good chance it will work. There are hundreds of 3rd party Arduino shield boards on the market and the HamStack will not be completely compatible with all of them. The Arduino uses an Atmel CPU while we use a PIC so there will be some differences on some boards. Having said that, we have mapped the HamStack’s CPU IO pins as closely as possible to the Arduino pins so many functions will be “plug and play”. Digital inputs, digital outputs, analog inputs, serial tx and rx, I2C, and SPI pins should work on most boards. Of course, the Arduino software is not compatible with the HamStack. However, many, if not all, Arduino IO functions are available in either the Microchip C18 or Swordfish Basic compilers.In addition to the 4 Arduino compatible connectors, there are two additional 8 pin interboard connectors providing more IO. The seventh interboard connector is the HamStack (PicKit compatible) in-circuit programming socket.
You will notice that there are two sets of solder pads for each interboard connector on the CPU board. Each pin is duplicated on the board. This is done for two reasons. First, the inner row of solder pads, those closest to the center of the PCB are used for the vertical stacking of PCBs using the stacking interboard connectors. The outer row of solder pads can be customized by the user. One use of these solder pads is to put a set of female sockets on the bottom of the board to allow the CPU board to plug into a larger “motherboard” that we call a project board” The project board spec uses male header connectors to mate with the female sockets on the bottom of the CPU board.
The other use of the solder pads is to provide a place to solder wires directly to the CPU board if you are embedding the CPU into your own project. You can choose to solder wires to any IO pin, power and ground.
CPU clock frequency and crystal selection
The HamStack comes with a 10 or 16 MHz crystal. The 18F4620 comes with a 10 MHz crystal and the 18F46K22 comes with a 16 MHz crystal. In both cases, the on-board phase lock loop oscillator circuit (PLL) will multiply the crystal frequency by 4x. This means that a 10 MHz crystal will clock your CPU at 40 MHz and the 16 MHz crystal will clock the CPU at 64 MHz. You can also choose to clock the CPU at the native (1x) crystal frequency but you might as well use the higher speed modes. When you write your programs, you have the choice of what oscillator to use to clock the CPU chip.
Most, if not all, of the examples in this book use the 18F4620 with a 10 MHz crystal with the oscillator set to the native (1x) crystal frequency of 10 MHz. This is done to keep the examples simple. We will explore how to use the 4x PLL mode in app notes.
- 10 -
Embedding the HamStack CPU into your own projects
The HamStack CPU can become the brain in your next ham radio project. When you assemble the CPU board for embedding into your own project, you can use the IO stacking connector sockets or make direct wire connections to the solder pads provided. Installing the 6 pin programming jack will ensure that you can upgrade your firmware in the future. Be careful not to exceed the current capability of the on-board regulator.
The 78L05 5v voltage regulator on the HamStack CPU board can supply a maximum of 100ma. The CPU board itself should consume less than half of that. Depending on the input voltage, you can power one or two additional chips but that is about it. If your input voltage to the CPU board is 13.8v and you are powering other devices with the 5v out of the CPU’s regulator, the device will get too hot. You can either reduce the input voltage, to 6 or 7 volts or provide an external DC power source to the other circuits.
RS-232 serial port
The CPU board has a built in voltage converter chip that will match the (0/5v) level of the CPU chip to the RS-232 voltage standard (+12v/-12v). The RS-232 signals are present on J9, the 3 pin male connector and are also passed to two of the interboard connector pins. The pins on the CPU board are Tx, Rx, ground when looking at the connector from the edge of the board. To connect to a PC or other serial device, make the following connections.
HamStack J9 pin 1 (Tx) to DB9 Female connector pin 2HamStack J9 pin 2 (Rx) to DB9 Female connector pin 3HamStack J9 pin 3 (Ground) to DB9 Female connector pin 5
This configuration will plug into a male DB9 RS232 port on a computer or straight through extension cable.
The reason we choose to put RS232 on the HamStack, rather than USB is that most devices in the ham shack you would want to control use RS-232. It is also easier for those new to programming microcontrollers to program a RS232 serial interface rather than the more complex USB interface. If you want to add a USB interface to the HamStack, that can be done as well but a different CPU chip will be required. For the majority of ham applications, the RS232 interface is more useful.
What about USB ?If you want to directly control the HamStack CPU from a PC, you can use a commonly available USB to RS232 dongle. We have tried many different brands and all adapters tested worked fine.A USB to TTL serial adapter board is also available.
!Read Me
Warning – Do not exceed the current capacity of the on-board regulator.
- 11 -
CPU Board Pin Assignments
J1J3
J5
J2J4
J6
Program
RS232
Status
Power
Mode
Reset
Power
J1-1 User pin A
J1-2 User pin B
J1-3 RS232 Rx
J1-4 RS232 Tx
J1-5 E2
J1-6 A4
J1-7 C1 (PWM2)
J1-8 C2 (PWM1)
J3-1 Reset
J3-2 3.3v
J3-3 5.0v
J3-4 Ground
J3-5 Ground
J3-6 Voltage In
J5-1 AN0
J5-2 AN1
J5-3 AN2
J5-4 AN3
J5-5 RE0
J5-6 RE1
J2-1 C0 (LED)
J2-2 PGD (Programming)
J2-3 PGC (Programming)
J2-4 B4
J2-5 B3
J2-6 B2
J2-7 B1
J2-8 B0
J4-1 Bias
J4-2 Ground
J4-3 C3
J4-4 C5
J4-5 C4
J4-6 A5
J4-7 D7
J4-8 D6
J6-1 D5
J6-2 D4
J6-3 D3
J6-4 D2
J6-5 D1
J6-6 D0
J6-7 C6 (Tx serial)
J6-8 C7 (Rx serial)
Tx
Rx
Gn
d
NoteIn PCB version 1.0, J3-5 is not connected to ground. The pin is isolated.
All later versions are correct.
- 12 -
CP
U v
ers
ion
4b
CPU BoardPin Assignments & Parts Placement Diagram
Remove jumper JP1 when using the CPU board plugged into the DEV-1 board.
The CPU board is powered by the DEV-1 board so there is no need to plug a power supply into the DC power jack
Plug PICKit2 compatible programmer into J9 or into J5 on the DEV-1 board.
RC0 / Status LEDProgramming pin PDataProgramming pin PClkRB4 - RelayRB3 – LED 4RB2 – LED 3RB1 – LED 2RB0 – LED 1
Bias – not usedGroundRC3 – I2C Clk not usedRC5 – I2C Data not usedRC4 – Not usedRA5 – PS2 keyboard clkRD7 – OneWire busRD6 – Not used
RD5 – LCD E pinRD4 – LCD RW pinRD3 – LCD D7RD2 – LCD D6RD1 – LCD D5RD0 – LCD D4RC6 – UART Serial TxRC7 – UART Serial Rx
RA0 – Analog inputRA1 – Button 1RA2 – Button 2RA3 – Button 3
RE0 – Encoder ARE1 – Encoder B
Reset3.3v - Not used
5.0v from DEV-1GroundGround
External voltage in
User A - not usedUser B - not used
RS232 RxRS232 Tx
RE2 – Encoder buttonRA4 – Button 4
RC1–PS2 keyboard dataRC2 – PWM Tone out
J7 RS232Pin 1 – TxPin 2 – RxPin 3 - Ground
Some CPU pins are not used with the DEV-1 board including RC3, RC4, RC5, and RD6. They are not pre-wired to any devices on the DEV-1 board. These pins are available for the user to use for custom applications. Adding a stacking board on top of the CPU board provides easy access these and all other pins. RC3 and RC5 are the I2C bus which is very convenient for connection to all kinds of devices including memories, sensors, IO expanders, etc.
Reset ButtonThis button will causethe CPU to reset.
Mode ButtonConnected to RA4, the mode button is used by some applications and is wired to Button 4 on the DEV-1 board.
Pwr LED Indicates power is present on the CPU board.
Status LEDConnected to CPU pin C0 and is typically used to indicate program status. User programmable.
- 14 -
J1-1 A User definable pin
J1-2 B User definable pin
J1-3 R2 RS232 UART1 Rx (Same as J9 pin 2)
J1-4 T2 RS232 UART1 Tx (Same as J9 pin 1)
J1-5 E2 CPU pin RE2, digital IO pin, or RS485 network control pin
J1-6 A4 CPU pin RA4, digital IO, and “Mode” button w/10k pull up
J1-7 C1/PWM2 CPU pin RC1, digital IO pin or PWM #2
J1-8 C2/PWM1 CPU pin RC2, digital IO pin or PWM #1
J2-1 C0/LED CPU pin C0, general IO pin and status LED, logic 1 = LED on
J2-2 PD CPU pin PGD. In-circuit programming pin
J2-3 PC CPU pin PGC. In-circuit programming pin w/ 10k pullup
J2-4 B4 CPU pin RB4, digital IO pin
J2-5 B3 CPU pin RB3, digital IO pin
J2-6 B2 CPU pin RB2, digital IO pin
J2-7 B1 CPU pin RB1, digital IO pin
J2-8 B0 CPU pin RB0, digital IO pin
J3-1 RST Pull this pin to ground to reset CPU. CPU MCLR pin #1 w/10k pullup
J3-2 3v3 3.3v DC supply rail output
J3-3 5v 5.0v DC supply rail output
J3-4 GND Ground
J3-5 GND Ground (Isolated on v1.0 PCB layout)
J3-6 Vin Input voltage. This is the external voltage input, typically 7.5 to 13.8 VDC.
J4-1 Bias Not used on the CPU board. Reserved for 2.5v DC supply rail
J4-2 GND Ground
J4-3 C3/SCK CPU pin RC3, digital IO pin, or SPI clock or I2C clock
J4-4 C5/SDO CPU pin RC5, digital IO pin or SPI data out pin
J4-5 C4/SDI CPU pin RC4, digital IO pin or SPI data in pin
J4-6 A5/SS CPU pin RA5, digital IO pin, or SPI select
J4-7 D7/Rx2CPU pin RD7, digital IO pin, or serial UART2 Rx pin (TTL level)
J4-8 D6/Tx2 CPU pin RD6, digital IO pin, or serial UART2 Tx pin (TTL level)
J5-1 AN0 CPU pin RA0, digital IO pin or analog input AN0
J5-2 AN1 CPU pin RA1, digital IO pin or analog input AN1
J5-3 AN2 CPU pin RA2, digital IO pin or analog input AN2
J5-4 AN3 CPU pin RA3, digital IO pin or analog input AN3
J5-5 RE0 CPU pin RE0, digital IO pin or analog input AN4
J5-6 RE1 CPU pin RE1, digital IO pin or analog input AN5
J6-1 D5 CPU pin RD5, digital IO pin
J6-2 D4 CPU pin RD4, digital IO pin
J6-3 D3 CPU pin RD3, digital IO pin
J6-4 D2 CPU pin RD2, digital IO pin
J6-5 D1 CPU pin RD1, digital IO pin
J6-6 D0 CPU pin RD0, digital IO pin
J6-7 C6/Tx CPU pin RC6, digital IO pin, or serial UART1 Tx pin (TTL level)
J6-8 C7/Rx CPU pin RC7, digital IO pin, or serial UART1 Rx pin (TTL level)
- 15 -
CPU Board
Mechanical Dimensions
Board length 3.1”
Board
width
2.3”
Hole spacing
2.9”
Hole
spacing
2.1”
2x O=0.125”
Inner pin
spacing
for
Arduino
shields
1.9”
- 16 -
Section 2
DEV-1 Development BoardHardware Reference
DEV-1 Development Board Features
DC power in7-14VDC
RS232
OneWireTemperatureProbe jack
RelayContacts
PS2 computer keyboard Audio
output jack
Optional DS temperature sensor (not supplied)
Speaker
Volume pot
Audio amp
LCD contrast pot
IO Jumpers
External A/D converter input
Rotary encoder and pushbutton
Status LED
Built-in AN0Potentiometer
4x LEDs and push buttonsOptional external connectionsolder pads
CPU reset button
LCD Display
CPU chip or CPU board
Optional EEPROM for data storage
Programming jack
Power LED
CPU pin assignment reference table
HELLO WORLD
DEV-1 Development BoardCPU Options
The DEV board can be used 2 ways. One option is to use the built-in solder pad location for a 40 pin CPU chip. The other option is to leave the socket empty and plug in a HamStack CPU board. The functionality is essentially the same. The DEV board is supplied with a CPU chip (18F4620), a 40 pin socket and associated components that will be installed next to the CPU chip. You should install all these parts AND the CPU 40 pin socket.
If you are not planning on using a HamStack CPU board with your DEV board, at least, not initially, you should assemble the whole board and plug the CPU chip into the socket.
If you plan to use a HamStack CPU board that plugs into the HamStack interconnect header pins, then you should install all parts EXCEPT the CPU chip and then plug the CPU board on top.
Option 1 Option 2 Use the built-in CPU chip. Use a HamStack CPU board
HamStack CPU board
CPU Chip
DEV-1 Development BoardConfiguration Jumpers
Jumper block JU2 – Select A0 Input (Analog voltage input)Jumper between pins 1 & 2 selects the built-in potentiometerJumper between pins 2 & 3 selects the external voltage input terminal block P5This 3 pin jumper block selects which voltage input will be routed to the CPU pin AN0 analog to digital converter 0.
Jumper block JU3Enc_A Connects rotary encoder to CPU pin RE0Enc_B Connects rotary encoder to CPU pin RE1Button Connects rotary encoder push button to CPU pin RE2Pot Connects analog voltage input to CPU pin AN0 A/D converter
Jumper block JU4LED4 Connects LED 4 to CPU pin RB3LED3 Connects LED 3 to CPU pin RB2LED2 Connects LED 2 to CPU pin RB1LED1 Connects LED 1 to CPU pin RB0
These jumper blocks allow you disconnect some of the peripheral parts from the CPU. This is a convenient way to free up extra CPU pins for use in your own custom projects by simply removing the jumper shunts. The default configuration is to install all jumper shunts for JU3 and JU4 and insert the JU2 jumper between pins 1 and 2.
PWM output from CPU
CPU pin RC2
+5V
RC2
Audio Amplifier
The audio amplifier takes the output of the CPU’s pin RC2, which has a hardware Pulse Width Modulator output, and will shape the wave into a sine wave using the RC filter R8, R9, C11, C13. The raw filtered signal is available at the 3.5mm jack J5. The audio then passes into an LM386 audio amplifier and to the local speaker. The pot R21 is used to set the audio level. If fixed levels are needed, the user resistors R11 and R12 can be installed instead of the pot.Note: components in the feedback loop, R13 and C10, are optional depending on the gain desired. The default configuration includes C10 installed with a 10uf capacitor and a jumper wire in the R13 position.
R4
Analog Input
OneWire – Temperature Probe
GND
RA0
+5v
+5v
+5vOneWire
Ground
Pot
Exte
rnal
Use jumper JU1 to select the analog input. “Pot” connects the built in potentiometer. “External” allows an external voltage input. The analog to digital converter (ADC) input can measure from 0 to 5 VDC. This value is reported as a number between 0 and 1023.
When using the external voltage input on connector P6, the input voltage goes through a simple voltage divider using a 10k series resistor and a 2.2k resistor to ground. This provides a usable range of 0-27.5 VDC.
The in this case, each unit from 0 to 1023 represents a resolution of 0.026 volts.
RD7
CPU pin RD7 is used as the data pin for OneWire sensor devices. Typically used for sensors like digital temperature devices, the OneWire interface connector J3 provides +5v, data and ground. There is also a TO-92 footprint on the PCB that can be used to install an optional DS18B20 temperature chip.
JU3 is a 3 pin connector to provide a connection to an external OneWire sensor.
Jumper JU3Pins 1 & 2
RA1RA2RA3RA4
+5V
Digital Inputs and Buttons
+5v
RE0RE1RE2
RE0 Encoder ARE1 Encoder BRE2 Encoder push button
The rotary encoder has two outputs which creates wave forms 90 degrees out of phase. These signals are decoded to produce a count up pulse or a count down pulse. For example, if the last value was 00 and the current value is 01, the device has moved one half step in the clockwise direction.
GND
A B
+5V
LCD and LED Displays
+5V
This LCD display uses the industry standard 4 bit Hitachi interface. The CPU uses 6 wires, 4 for data and 2 for control. Pot R17 is used to set the contrast on the display. An extra connector, J6 is wired in parallel with the built-in LCD display if an external display is going to be used. Normally J6 is not used.
RB3RB2RB1RB0
RB0.. RB3 are wired up to 4 LEDs. When the CPU pin is set high, +5v, the LED will be turned on.
Jumper block JU4 is provided to allow the user to disconnect any of the CPU pins RB0..RB3 from the LEDs and free up the CPU pins to be used for another purpose.
RD5RD4RD3RD2RD1RD0
JU4
PS2 Computer KeyboardThis connection provides a convenient way to take user input into an application running on the HamStack CPU.The PS2 keyboard requires the hs_keyboard.bas library to be included in your source code.
RA5
External Connections
RC1
RS232 Serial PortThe CPU chips’s main serial UART is connected to a TTL to RS232 level shifter chip (MAX232) located on the CPU board. Those RS232 signals are routed through the inter-board header connectors to the DEV-1 board then to J2, a female DB9 serial data connector.
Pin 2 – Transmit data out of the board.Pin 3 – Receive data input to the board.Pin 5 – Ground
SPDT RelayThe board includes a single pole double throw (SPDT) relay. The relay control signal comes from CPU pin RB4.When pin RB4 is high, +5v, it will turn on Q1 pulling the collector of the transistor to ground. This will complete the circuit allowing current to flow through the relay coil and actuating the relay.LED D8 will indicate when the relay is turned on.Diode D5 is used to eliminate “counter EMF”. It’s the voltage produced by the interaction of current in the coil of the electromagnet its magnetic field, when one, or both, is changing.
RB4
RC6RC7
Power Supply
- 26 -
Section 3
Assembly Instructions
- 27 -
Assembling the DEV-1 Board
These assembly instructions are specifically for building the HamStack DEV-1 development board but the general principals apply to any of the HamStack boards. For detailed assembly instructions of additional HamStack boards, refer to the hardware manual for those boards.
Too many partsYou may find extra parts in your kit. This happens because some components are easy to loose or install incorrectly. So just in case, we may include a few extras.
Too few partsWhile we are very careful to make sure you get what you are supposed to get, we may have accidently omitted a component. If this happens, drop us an email at [email protected] and we will send you a replacement part right away.
General assembly instructionsAssembly is very straight forward but requires some basic soldering skills. If you are an experienced builder, you can use the parts placement diagram as your guide and start assembling the board. If you have never built an electronic circuit board, we suggest you practice on another PCB to get the hang of it. There are many good resources on the web to show you how to solder
Hardware Overview
The DEV-1 board provides several common hardware peripherals that are connected to a HamStack CPU board plugged on top of the DEV-1 board. The connectors on the bottom of the CPU board provide a path to the DEV-1 boards peripherals. This system is a handy platform for software development and system prototyping.
Assembly
The DEV-1 board comes as a kit and can be easily assembled in an evening. While there is no special s no special order of assembly we would recommend the following order.
Install all IC sockets, header connectors.
Install the pushbuttons, LEDs, resistors, capacitors, diodes and transistors.
Install the LCD display.
Install the larger components including the connectors, speaker, encoder and knob.
This order is recommended because it allows you to put the lowest parts on first and ultimately the heaviest components last.
Special notes…
LCD – The connection between the LCD and the circuit board is accomplished using wires between the boards. Your kit includes 12” of buss wire that is cut into short pieces long enough to connect a solder pad on the LCD board to the main PCB.
Encoder knob – Be careful when putting the knob on the rotary encoder to make sure you don’t but the knob too low. The encoder includes a “button press” action and if you install the knob too low, it will prevent the encoder “push button” from moving.
The input voltage to the board can be any DC voltage from 7-13.8 VDC.
- 29 -
Reference Designators Not On The Silkscreen
Some components on the board are not labeled with a reference designator. This diagrams shows the proper placement of those parts.
J7 J8 J9
J10
J11
J13 J14
J15
J7, J8, J9
J10, J13, J14
J15, J11
Male header pins
Male header pins
Install 6 male headerconnectors here
- 30 -
Assembling the LCD Display Module
Install the two female SIP header sockets on the bottom of the LCD board. The connectors will be pointing down.
Install two screws and standoffs on the bottom of the LCD PCB in the lower two holes.
J7 J8 J9
J10
J11
J13 J14
J15
HELLO WORLD
Female header sockets mounted to the bottom of the LCD display PCB.
J16 - 6 pin J17 - 8 pin
7/16” Standoff
Nut
HELLO WORLD
LCD PCB
7/16” Standoff
Header connectorside view
NutDEV-1 PCB
LCD PCB
DEV-1 PCB
Side View
Builders Alerts
The builders alerts are important modifications that should be made to your DEV-1 board for proper operation.
Rev 3 Beta Boards
There is a missing trace on the bottom of the board that connects the voltage regulator ground pin to the DB9 ground pads. This is a view of the bottom of the PCB. Install a piece of wire as shown below. The mod is done on the bottom
Rev 3 PRODUCTION Boards
This missing trace was corrected in the production boards. No jumper is required.
Bottom of DB9
connector
Bottom of 7805 regulator
Added jumper wire
This is a view of the bottom of the PCB
This mod is on the bottom of the board in this location
- 32 -
DEV-1 Development Board Parts ChecklistCheck Type Part Reference Designator
□ Capacitor 0.047uf C1□ Capacitor 10 uf electrolytic C11, C14□ Capacitor 22 pf C12, C13□ Capacitor 1 uf electrolytic C16, C17, C18, C19□ Capacitor 0.022uf C2□ Capacitor 0.1 C3, C4, C6, C9, C15, C20□ Capacitor 330 uf electrolytic C5, C10□ Connector 3.5mm stereo jack J1□ Connector 8 pin female SIP connector J13□ Connector 6 pin mini-DIN connector J2□ Connector DB9-F J34□ Connector 2.1mm DC coaxial power connector J4□ Connector 1x6 pin female SIP connector J5, J16□ Connector 1x8 pin female SIP connector J17□ Connector 3 pin header right angle w/ ramp J6□ Connector 1x8 pin male header J7, J8, J9, J10, J11□ Connector 1x6 pin male header J13, J14, J15□ Connector 1x2 pin male header JU1□ Connector 1x3 pin male header JU2□ Connector 2x4 pin male header JU3, JU4□ Connector 2 pin pluggable terminal block P5□ Connector 3 pin pluggable terminal block P6□ Diode LED T1-3/4 RED D1, D2, D3□ Diode LED T1-3/4 GREEN D4, D6, D7, D8□ Diode 1N4148 D5□ IC LM386 audio amplifier U1□ IC 7805 +5v voltage regulator U2□ IC PIC 18F4620 U5□ IC MAX232 U7□ IC Socket 8 pin DIP IC socket 0.3" U1-SOC, U4-SOC□ IC Socket 40 pin DIP IC socket 0.6" U5-SOC□ IC Socket 16 pin DIP IC socket 0.3" U7-SOC□ Misc Rotary encoder with pushbutton ENC1□ Misc Crystal insulator INS1□ Misc Knob for rotary encoder KNOB1□ Misc 2x16 LCD display LCD1□ Misc 4-40 x 1/4" screw M1, M2, M3, M4, M5□ Misc 4-40 nut M6, M7, M8□ Misc Standoff, long M9, M10□ Misc Jumper shunts QTY 10□ Misc Speaker SPEAKER1□ Misc Pushbutton SW1, SW2, SW3, SW4, S5□ Relay SPDT 5v relay RY1□ Resistor 10k Pot R1, R5, R19□ Resistor 10 ohms R12, R20□ Resistor 270 R14, R15□ Resistor 270 resistor pack (5 resistors bussed) R17□ Resistor 2.7k R18□ Resistor 10k R2□ Resistor 2.2k R3□ Resistor 10k SIP resitor pack R4, R11, R13□ Resistor 2k R8□ Resistor 1k R9, R16□ Resistor 10 MHz Crystal Y1□ Transistor PN2222 Q1
- 33 -
Assembling the CPU Board
These assembly instructions are specifically for building the HamStack CPU board but the general principals apply to any of the HamStack boards. For detailed assembly instructions of additional HamStack boards, refer to the hardware manual for those boards.
Too many partsYou may find extra parts in your kit. We do this because some components are easy to loose or install incorrectly. So just in case, we may include a few extras.
Too few partsWhile we are very careful to make sure you get what you are supposed to get, we may have accidently omitted a component. If this happens, drop us an email at [email protected] and we will send you a replacement part right away.
Before you assemble the CPU board, take a minute to review these important options.
Making the right decision now will save you potential headaches down the line.
All components are mounted to the top of the board. That is the side with the white silkscreen lettering.
#1 DC Power ConnectionsThe CPU kit includes both a 2.1mm coaxial DC power jack, the kind found on small AC adapters. The kit also includes a two pin screw terminal block. You have the option to install either of these connectors or solder wires directly to the PCB. As a general rule, when embedding the CPU in your own projects, you would use the terminal block or solder wires to the pads. If you are using the CPU board stand alone or with a backpack board and want quick connect / disconnect of power, then you should use the 2.1mm DC power jack.
#2 Stacking Connector OptionsThe stacking connectors allow your board to connect with other HamStack boards. You should install the inner connectors on J1 – J6 plus J7. You have the option of installing additional connectors on the bottom of the CPU board. These connectors are required when using the HamStack project board.
#3 Generally SpeakingAssembly is very straight forward but requires some basic soldering skills. If you are an experienced builder, you can use the parts placement diagram as your guide and start assembling the board. If you have never built an electronic circuit board, we suggest you practice on another PCB to get the hang of it. There are many good resources on the web to show you how to solder
To identify components, refer to the component identification guide in the appendix..
!ReadMe
- 34 -
CPU Board V4b - Parts Placement
Parts List – Required Components
C1 10uf electrolytic capacitor
C2, C3 0.1 uf capacitor (104)
C4, C5 22pf capacitor (22)
C6 0.1 uf capacitor (104)
C7, C8, C9, C10
1 uf electrolytic capacitor
R1, R2 270 Ohm ¼ w resistor (270)
RP1 10k resistor pack (103)
D1, D2 Red T1 LEDs
S1, S2 Pushbutton switch
Y1 10 MHz crystal
INS1 Crystal insulator
U1 78L05 5v voltage regulator
U2 CPU chip
U3 MAX232 RS232 level shifter IC
J1, J2, J4, J6 Inner connector row 8 pin
female sockets
J3, J5 Inner connector row 6 pin
female sockets
J7 3 pin male connector with tab
J8 2.1mm coaxial DC connector
J9 6 pin female programming jack
- 35 -
CPU Board
Step by Step Assembly Instructions
Step 1 - Install the IC sockets
To start off, lets install the IC sockets. There is a 40 pin socket
for the CPU chip and a 16 pin socket for the RS232 interface
chip. Put the 40 pin socket in place first. The end of the socket
that has pin 1 will be indicated by an indent. Flip the board over
and solder pin 1 first. Then solder pin 21. You now have one
pin at each corner soldered. Pinch the socket against the
board with your fingers and touch the solder pad for pin 1 with
the soldering iron tip. If there is any space between the socket
and the board, the socket will snap tight against the PCB.
Repeat this for pin 21. Now the socket is snug against the
PCB. Solder all remaining pins.
Insert the 16 pin socket for U2, the RS232 interface chip.
Follow the same procedure you did for the 40 pin socket.
Using the 2.1mm DC coaxial jackThese three highlighted solder pads are
where the pins of the jack are inserted
and soldered.
Using the terminal blockThese three highlighted solder pads are
where the pins of the terminal block pins
are inserted and soldered. Note that the
silkscreen indicates which pin is GND and
which is the +V input.
Step 2 – J8, the Input power connector
Now, you have a choice of they type of input power connector
you use. The kit comes with both the 2.1mm coaxial DC
connector and a two position screw terminal block. If you plan
to package the CPU board into a chassis, you should use the
screw terminals. If you will use the CPU board by itself, maybe
with a backpack board, you could use the coaxial connector for
quick connections. The coaxial connector will clash slightly with
a backpack board but work OK. The screw terminal will sit
flush with the backpack board.
You could also solder wires directly to the PCB for an
embedded application
Make sure you have
pin 1 on each socket
in the correct
position.
Pin
1 Pin
1
- 36 -
CPU Board Assembly – Continued
Step 3 - Install the crystal, insulator and
capacitorsFind the thin crystal insulator and slide it on to the
leads of the crystal. The insulator may be clear or
white.
Then install the crystal and insulator on the PCB.
Also install the two small 22pf capacitors next to the
crystal case. These caps are marked “22”.
Parts
Y1 – 10 or 16 MHz
crystal
INS1 – Crystal insulator
C4, C5 – 22pf mono cap
Note: These capacitors
look very similar to the
0.1 uf capacitors. Do
not confuse them and
install the wrong part.
Make sure you install
the capacitors labeled
“22” in these two
positions.
Step 4 - Install the 78L05 5 volt regulatorThis voltage regulator is in a small plastic TO-92
case. It looks like a common transistor. Make sure
you look closely at the markings to see that you have
the 78L05 voltage regulator and not another part.
You can see the solder pads say I, G and O. These
are the Input, Ground and Output pins.
Parts
U2 – 78L05 voltage
regulator
Step 5 - Install capacitor C1This filter capacitor is installed near pin 1 of the CPU
chip socket. The silkscreen says 47uf but this
capacitor can be anywhere between 10uf to 47uf.
Note that the silkscreen for all polarized electrolytic
capacitors show a “+” sign on the board and the
positive hole is “pin 1” of the capacitor indicated by a
square solder pad. You can quickly tell which pin is
the “+” pin on the capacitor because the “+” lead is
always the longer of the two. Also the markings on
the can typically indicate the “-” lead.
Parts
C1 – 10uf to 47uf
electrolytic capacitor
Note: The silkscreen on
the board says 47uf.
The kit will be supplied
with a 10uf capacitor
instead. Install the
supplied 10 uf capacitor.
Step 6 - Install resistors R1 and R2Install the two 270 Ohm resistors R1 and R2 next to
the CPU socket. The silkscreen on the board shows
“270” inside the pattern for the resistor to indicate the
value of the component.
270 Ohms 5% is Red Violet Brown Gold.
These resistors limit the current through the LEDs.
Parts
R1 – 270 Ohms ¼ watt
R2 – 270 Ohms ¼ watt
Make sure you don’t confuse these
capacitors with the 0.1uf capacitor
marked “104”. The 0.1uf caps go next
to the CPU socket. That step comes
later.
+ -
- 37 -
Step 7 - Install bypass capacitors C2 & C3Install the two small 0.1uf capacitors, C2 and C3 next
to the CPU chip. These little capacitors are marked
“104” indicating the value of 100000 pf or 0.1uf.
Be careful not to confuse these with the 22pf
capacitors that go next to the crystal. The may look
exactly the same except for the tiny writing.
Parts
C2 – 0.1uf
C3 – 0.1uf
Step 8 - Install the 10k resistor pack
When installing the resistor pack, make sure to install
pin 1 in the proper location. When reading the value
of the component on the side, pin 1 is always the left
most pin of the package. That pin will go into the
square pin 1 solder pad on the PCB.
You can read the value of the resistor pack by
looking at the part number. Most manufacturers will
indicate the value of the resistors by a three digit
number. Make sure the 3 digit number on the
component you install into the CPU board is “103”
which means 10k Ohms.
Parts
RP1 – 10k resistor pack.
5 resistors, common
bus.
Step 9 - Install the programming socketNow it's time to install the last few components: the
SIP sockets. SIP stands for “Single In-line Package”
The programming socket is a 6 pin SIP female
socket.
Place the socket into the holes on the PCB. Flip the
board over being careful that the socket does not fall
out. Now, solder one pin. Flip the board back over
and see if the socket is flush with the PCB and if it is
perpendicular to the board. The socket MUST be
flush and straight. Take you time. It is very
important to get these SIP sockets installed properly.
The properly installed SIP socket will look like this.
Parts
6 pin female SIP socket
CPU Board Assembly – Continued
- 38 -
Step 10 - Install 6 top mounted SIP socket
connectors
The six SIP sockets are used to provide
interconnection between the CPU board and the
backpack or other boards plugged on top of the CPU
board.
Parts
2x 6 pin SIP sockets
4x 8 pin SIP sockets
As with the programming socket, set each socket in place by soldering
only one pin. Then make sure it is snug against the PCB and is
vertical.
These six connectors are mounted on top of the PCB just like all the
other components so far.
When you look at the PCB, you will see two rows of solder pads for
every connector position J1 through J6. The inner solder pads are
used for these six sockets.
PartsJ9 – 3 pin male
connector
C6 – 0.1uf capacitor
C7, C8, C9 C10
1uf electrolytic
capacitor
D1, D2 – Red LEDs
B1, B2 – Pushbuttons
Step 11 - Install the remaining components
along the front edge of the board
Now its time to install the last few components, the
serial jack, the 4 electrolytic caps for the serial interface,
the 2 LEDs, and the two pushbuttons.
From top to bottom as shown in the picture to the left...
11.1 Install one of the 1 uf electrolytic capacitors, C10
11.2 Install the RS232 3 pin locking male connector
11.3 Install the remaining three 1uf electrolytic
capacitors that are used for the RS232 interface. Be
sure to put the longer “+” lead into the square solder
pad.
11.4 Install the 2 RED LEDs.
The longer leads of the LEDs go into the square
solder pads.
11.5 Install the 2 push buttons.
11.6 Install C6, the 0.1uf capacitorNote if you build a project that runs on battery power and you want to reduce power
consumption to the absolute minimum, you can choose to not install the LEDs. If
you already installed the LEDs, you can always cut a trace that powers the LEDS
On the bottom of the PCB, the traces that go to the two LEDs can be cut with a
knife. The little traces are next to the <LED> label on the bottom.
CPU Board Assembly – Continued
- 39 -
CPU Board Final Assembly
Congratulations !
After you insert your CPU and RS232 chips, you
have completed the heart of the CPU board.
Note that the rev 1 boards included a 3.3v
voltage regulator which was removed from the
rev 2 and later boards.
Now you have one last decision to make. Do
you want to install the inter-board connectors on
the bottom of the CPU board? Those 6
connectors are used to plug the CPU board on
top of the IO extender board.
If you are embedding your CPU board into a
project then you most likely will not want to
install the bottom connectors. If you are
plugging into a IO extender board then you must
install them as follows…
Step 12 – OPTIONAL
Install 6 BOTTOM mounted SIP socket
connectors
Remember, when you installed the 7 SIP connectors
on the top of the board? They were installed on the
inner solder pads of J1-J6 and J7.
Now when installing the bottom SIP socket
connectors, they will be installed into the outer solder
pads of J1-J6. Use the same procedure to insert
each connector, solder one pad, make sure its flush
to the PCB and vertical. Then, solder all the
remaining pins.
Parts
6 pin female SIP sockets
Note
If you are going to install
the bottom SIP sockets,
you may want to install
the sockets before you
plug the chips into the
board.
Now, your completed
board looks like
this…
Bottom view
Place the bottom connectors on the outer row of
solder pads on J1-J6
- 40 -
Section 3
Software Development Tools
- 41 -
Programming Software
As an open computing platform, the HamStack can support any development tool set that is designed to support the 40 pin 18F series of Microchip CPU chips. Having said that, we recommend the Microchip C18 C language compiler or the Swordfish Basic compiler. To help those people new to programming with microcontrollers, we have focused all the examples illustrated in this book on Swordfish Basic compiler. In addition to the compiler tools, you will also need an incircuit programmer. The HamStack USB programmer uses the Microchip PicKit2 programming software. A dumb terminal program also helps debugging by providing an easy way to send data back and forth between the CPU board and the PC.
We will focus in this book on the Swordfish Basic compiler because it is simple and easy to start writing code and see results immediately. If you want to start learning C for the HamStack, there are other documents on the HamStack website that will show you how to get started.
Which language: C or Basic?The biggest question you want to consider is which language, and ultimately, which compiler should you use? There is no simple answer to this question that covers all users. We choose the C18 and Swordfish Basic compilers because they are very good and there are free versions available. There are also commercial versions of these compilers and others that cost about $150. While there are some limitations to the free versions, they are very capable and all the examples in this book are developed with the free versions. Ultimately your choice of compiler depends on many factors but if you really need some advice, here goes…
Microchip C18 compiler- Very powerful compiler with no code restrictions- The MPLAB IDE has a lot of features and lets you manage large projects with many files- The complexity of MPLAB also means there is more to learn about the environment- The upgrade to the commercial version is an optimizing compiler that generates smaller code
Swordfish Basic- Also a very powerful programming environment- Simple, easy to use environment. You will be coding in just a few minutes- The SE (Special Edition) version limits the maximum RAM variables to 256 bytes- The upgrade to the commercial version has no restrictions
Ultimately, if you are scared off by the terse, obtuse C language syntax and all the curly braces, then start with Basic. If you are comfortable with C and are willing to spend a few evenings learning MPLAB then start with the C18 compiler. Either way, you have great tools to use.
C18
basic
- 42 -
Introduction to Swordfish Basic
Swordfish is a highly structured, modular PIC® BASIC compiler for the PIC18 family of
PIC® microcontrollers. Swordfish is a true compiler that generates optimised, stand alone code which can be programmed directly into the HamStack CPU board. Extensive library support is provided with full source code, some of which include LCD, GLCD, EEPROM, ADC, software and hardware SPI, software and hardware I2C, software UART, USART, string manipulation, USB and math libraries. Support for strings, arrays, structures, boolean, bit, unsigned and signed 8, 16 and 32 bit ordinal types and 32 bit floating point is also provided. Swordfish is supplied with a powerful and flexible Integrated Development Environment (IDE) which includes an advanced code explorer, full syntax highlighting, third party programmer integration, serial communicator and integrated boot loader application. Just a single mouse click, or key press, will compile your program.
The HamStack comes with the free version of the compiler called Swordfish Special Edition or Swordfish SE for short. The Special Edition has all the same features of the full commercial version except that it can compile a program with a maximum of 256 bytes of RAM. Even with this limitation, you can develop significant applications. All the examples in this book can be compiled with the SE version. If you need the full RAM capacity of the commercial version, you can visit the HamStack web site to purchase a copy.
Swordfish enables you to structure a program using subroutines and functions. Each subroutine or function can have its own local declarations consisting of constants, structures and variables. Procedural programming is a better choice than simple sequential or unstructured programming, especially in situations which involve moderate complexity or require significant ease of maintainability.
In large and complex programs, modularity is essential. Swordfish enables you to group commonly used subroutines, functions, constants, structures and variables into a single entity called a module. Scoping is an essential part in keeping a program modular and Swordfish allows all module declarations to be defined as either private or public. The separation of private and public parts of a module is often referred to as encapsulation, or information hiding, and enables you to create modules that are both reusable and robust.
- 43 -
Typical screen shapshot of the Swordfish Integrated Development Environment (IDE)
The following lists some of the key compiler features.
Signed and unsigned ordinal, floating point, string and array constantsBoolean, bit, 8, 16 and 32 bit signed and unsigned, floating point, char and stringsArrays and structures, including arrays of strings and structuresAlias and modifiersAddressable EEPROM data constantsConditional statements including if...then..elseif...else...endif and select...caseRepetitive statements including while...wend, repeat...until and for...next, breakSubroutines and Functions, support for local constants, structures and variables.Inline subroutines and functionsFull support for passing by value and passing by reference. Powerful frame recycling algorithm ensures optimal RAM usageAll constants and declaration types can be declared as private or publicSupport for embedded assemblerPowerful hardware based interrupt supportRich set of compiler directives including #ifdef, #constant, #variable, #define, etc.Predfined subroutines and functions, including AddressOf, BitOf, Bound, Dec, DelayMS, DelayUS, High, Inc, Input, Low, Output, Terminate and ToggleExtensive library support is provided with full source code, some of which include LCD, GLCD, EEPROM, ADC, software and hardware SPI, software and hardware I2C, software UART, USART, Secure Digital (SD), string manipulation, math, interrupt based RX and interrupt based timer libraries. Specific peripheral libraries are also included with full source. Some examples include the DS18B20, DS18S20 and DS2405.Comprehensive set of relational, mathematical and logical operators
- 44 -
Step by Step Instructions for Using the Swordfish Basic IDE
After launching the Swordfish Basic compiler IDE for the first time, you are presented with an empty text editor file. The IDE assumes you will be using an 18F452 CPU chip.
We need to make a few quick adjustments.
In the editor box, erase the contents and enter the following...
' This is my first program
Device = 18F4620
Clock = 10
Any text after the single quote is a comment and ignored by the compiler.
As soon as you enter the device type, in this example, 18F4620, the compiler loads the proper CPU parameters and updates the navigation bar on the left side.
Entering “clock = 10” tells the compiler that we are clocking the CPU at 10 MHz and to adjust any timing specific behaviors accordingly. The 18F4620 can be clocked up to 40 MHz with the supplied 10 MHz crystal using the 4x clock mode called HSPLL (High Speed Phase Locked Loop). However, all the examples use the native 10 MHz clock to keep the examples simple
At this point you can compile your first program. Click on the “Build” button in the tool bar. The compiler will generate the .hex file to be down loaded into the CPU chip. This program won't actually do anything but you can see how the process works.
After compiling, the screen looks like this...After compiling the program, the Results window will tell you how much code you generated and how much RAM will be used.
In this example, the program generated is only 19 bytes long and uses 0.3% of the CPU's program memory. It will also use 25 bytes of RAM. This is a little misleading because the compiler allocates at least 25 bytes to every program, even if it uses less RAM.
- 45 -
Swordfish Basic Compiler Commands
Swordfish Basic is a powerful structured programming language. Here are some of the types of constructs available.
Variables and data typesConstants, array constants, variables, Boolean types, strings, char types, arrays, structures, unions, user types
EEPROM Data
Conditional StatementsThe If…Then Statement The Select…Case StatementConditional Jump
Repetitive StatementsThe While…Wend Loop The Repeat…Until Loop The For…Next Loop Short Circuit Boolean ExpressionsBreakContinue
Subroutines
Functions
Subroutine Declarations
Embedded Assembler
With StatementInterrupts EventsContext Saving
Compiler Directives#constant #variable #define #undefine #ifdef…#else…#endif #ifndef…#else…#endif #if…#elseif…#else…#endif. #error #warning #option
Predefined Subroutines & FunctionsAddressOf BitOfBound ClearDecDelayMSDelayUSHighIncInputLowOutput TerminateToggle
Library of ModulesAnalog to digital converterData type conversion (string, float)EEPROMGraphic LCDI2CISRRXISRTimerKeypadLCDManchester encodingMath library (abs, trunk, round, cell,
floor, fmod, modf, sqrt, cos, sin, tan, acos, asin, atan, exp, log, log10, pow, atan2, cosh, sinh, tanh, fexp, idexp)
DS One Wire devicesShift registerSoftware I2CSoftware SPISoftware UARTHardware SPIString library (length, copy, upper,
lower, position, mid, left, right, delete, insert, trim, compare)
Hardware USARTUSB and HIDUSB CDCUtils
- 46 -
Typical Swordfish Basic Program
In this example we will have the CPU do the following tasks...- Send a “Hello World” message to the serial port- Blink the LED once a second- Every 10 blinks, send another message to the serial port- Loop forever blinking the LED
Source code
' HamStack_blinky.bas
' Send a "Hello World" message and blink the status LED
Device = 18F4620 ' Set the CPU type to an 18F4620
Clock = 10 ' Set CPU clock frequency to 10 MHz
Include "usart.bas" ' Include the RS232 UART subroutines
'----- VARIABLE DEFINITIONS ---------------------------------
Dim x As Byte ' Loop counter variable
'----- DEFINE PIN DIRECTIONS --------------------------------
' 0 = output
' 1 = input
TRISC.0 = 0 ' Status LED defined as an output
'----- INITIALIZE VARIABLES AND SERIAL PORT -----------------
x = 0 ' Initialize loop counter to zero
SetBaudrate(br9600) ' Set serial baud rate to 9600
'----- START MAIN PROGRAM CODE ------------------------------
USART.Write("Hello world from HamStack", 13, 10) ' Send hello
'----- START MASTER CONTROL LOOP ----------------------------
master_loop:
For x = 1 To 10 ' Set up a count from 1 to 10
High (PORTC.0) ' Turn on status LED
DelayMS (500) ' Wait 500 ms.
Low (PORTC.0) ' Turn off status LED
DelayMS (500) ' Wait 500 ms.
Next ' Loop
USART.Write("Another 10 loops completed", 13, 10)
GoTo master_loop ' Loop forever
- 47 -
Now lets look at what each command in this example does
Device = 18F4620
This command tells the compiler to generate code for a Microchip 18F4620. If you are using another CPU chip, change the part number to match the CPU you are using.
Clock = 10
This command tells the compiler that the crystal oscillator is running at 10 MHz.
Include "usart.bas"
Swordfish Basic allows you to put commonly used program code into separate files that can be inserted automatically at compile time. This makes your source code easier to read and keeps you from accidently making changes to your library of good working subroutines. To user the serial IO commands, you must include the “usart.bas” source code file.
Dim x As Byte
Next, the variables used in the program are defined. Variables can be byte (8 bits), word (16 bits), strings, etc. The command means “dimension variable named x as a byte”
TRISC.0 = 0
Next we need to define the behavior of the IO pins we are using. In this case, we are using the pin PORTC pin 0, or “RC0” as we refer to it. The “TRIS” control register inside the CPU controls the behavior and direction. If TRISC.0=1 then the pin is a digital input, if TRISC.0=0 then its an output pin. Note that 0 is a zero.
X = 0
Here we initialize the variable to a value of zero. Although not necessary in our program, its good programming practice to initialize all variables to avoid unexpected behavior.
SetBaudrate(br9600)Sets the serial port baud rate to 9600.
USART.Write("Hello world from HamStack", 13, 10)
This command sents the string “Hello world from HamStack” out the serial port followed by a return and a line feed character. The return character is a decimal value of 13 and the line feed is a value of 10.
Now that the setup is all done, we can get down to work. Most programs have a primary control loop. The control loop typically reads a set of inputs, makes a set of decisions and sets various outputs, then loops forever. In our case the control loop starts at a label called“master_loop”
Inside master_loop, there is a For / Next block and a serial output command. The
basic control structure is simply a label, followed by some commands, then a jump back to the master_loop starting point. This will cause the loop to execute forever.
- 48 -
Inside the master_loop is a for/next statement. This control structure is convenient for doing something a certain amount of times. In our case, we want to blink the LED 10 times then send a serial port message.
Here is how the for loop works...
For x = 1 To 10
High (PORTC.0)
DelayMS (500)
Low (PORTC.0)
DelayMS (500)
Next
For x = 1 to 10
This says that x starts out with a value of 1 and that all commands between this line and the “Next” command will be executed 10 times.
High (PORTC.0)
Turns on output pin RC0, which is hooked to the anode of our status led that we want to blink. When we say High, we mean put +5 volts on the output pin.
DelayMS (500)
Do nothing for 500 milliseconds.
Low (PORTC.0)
Turns off output pin RC0. This puts a value of 0 volts (ground) on the output pin thus shutting off the status LED.
DelayMS (500)
Do nothing for 500 ms again.
NextGo back to the last “For” command and start executing the code. If the value of x as defined in the For statement is greater than 10, exit the for loop and execute the next sequential command.
USART.Write("Another 10 loops completed", 13, 10)This is the next command after the loop executes 10 times. This command will send a message to the serial port.
- 49 -
In-Circuit Programming
Now that your program is compiled and you have generated the .hex file, its time to download the program into the CPU board. This is done using the HamStack USB programmer and the Microchip PicKit2 programming software.
The idea is really simple. Once the software is installed, you plug the programmer into the programming jack on the CPU or backpack board and go through these steps...
1. Make sure the HamStack is powered up2. Make sure the programmer is communicating with the CPU board3. Erase the flash memory that stores the program in the CPU chip4. Load the new .hex file from disk5. Write the new firmware into the CPU chip
InstallationDownload the latest version of the PicKit2 software from the Microchip web site or use the version on the HamStack CD. Follow the simple instructions in the setup program. When the software is installed, lets try downloading our firmware into the CPU.
Plug the HamStack USB programmer into your PC and launch the PicKit2 program.
The window should look like this...
The program should automaticallyrecognize the programmer anddetect the CPU chip in the HamStack CPU board. You can tellbecause the “Device:” field will sayPIC18F4620” or whatever CPUchip is installed.
The message window will also say “PicKit2 found and connectedPIC device found”
If you get this message...
The programmer is not plugged inproperly or there is no power on the HamStack CPU board.
- 50 -
Next, click on the “Erase” button to erase the contents of the program flash memory in the CPU chip.
Now, open the .hex file. Select File / Import Hex then navigate to the file. In our example the file is called HamStack_blinky.hex
Successfulimport of the.hex file
You can seethe hex file isnow ready to be downloadedinto the CPU chip
Now its time to download the firmware into the CPU chip. Click on the “Write” button to download.
After successful programming, you will see this message
- 51 -
HamStack In-Circuit Programmer
Make sure you plug the programmer into the CPU board with the red stripe of the ribbon cable plugged into pin 1 of the programming jack. Pin 1 is the pin closest to J2 on the CPU board. Put the programmer into 5v mode with the slide switch. When in 5v mode, the green LED will be off.
The connector on the end of the programmer's cable is a 6 pin female SIP connector. The HamStack CPU board and backpack boards also have a 6 pin female SIP connector. To connect the programmer to the CPU board or backpack, you will need a 6 pin male to male header adapter. This is included with the HamStack USB programmer.
Ribbon cable from USB programmer
CPU or backpackboard with programmingconnector
6 pin male / male header
USB plug and play
No external power required
Uses Microchip's PICkit 2 software and MPLAB IDE
120mA current output
Over-current protection
Compatible with C18 and Swordfish basic compilers
Read / write serial EEPROM 24LCXX, etc.
Runs on Windows XP ,Windows Vista and Windows 7 (32 and 64 bit)
Support for 3.3V and 5.0V devices
- 52 -
HamStack In-Circuit Programmer
Pin 1 of the ribbon cable is indicated by the RED stripe
Pin 1 of the ribbon cable plugs into pin 1 of the programming jack labled “M”.M is the MCLR or reset signal for the CPU.
Power – Please Read...The HamStack programmer provides +5v DC power to the CPU board. This is very convenient when developing your software and testing it on a HamStack CPU. However, when the HamStack CPU is embedded into a project, you will want to provide power directly to the CPU board, not through the programmer. In this case you must disable the +5V DC from the programmer. To do this, you must cut or remove pin 2 from the programmer's in-circuit programmer connector as illustrated below.
Programming connector1 M MCLR (reset)2 V +5v DC from programmer3 G Ground4 D Programming serial data5 C Programming serial clock6 A Aux (not used)
Remove or cut pin 2, the +5v DC power from the 6 pin programmer adapter header when powering the CPU board directly and not from the programmer.
!Read Me
- 53 -
Section 4
Putting It All Together:
Your First Project
- 54 -
Putting It All Together
Now lets walk through the process from start to finish. We will take the simple example that illustrates the concepts of the control loop to blink the status LED and send a message to the serial port. We will show the following steps in detail.
1. Enter the source code in the Swordfish editor window.2. Compile the program, generating the .hex output file.3. Downloading your program into the CPU board.4. Watch the LED blink monitor activity on the serial port.
Step 1. Enter the source code.
Launch the Swordfish Basic compiler program.These screen snapshots were taken on a Windows 7 system. If you are using XP or another OS your windows may look slightly different. When the program starts, you will see a screen like this.
The Swordfish environment automatically inserts a default header of text at the top of the file. You can edit this banner to include any text you want by going to View / Editor Options / Program Header. You may want to go there now to enter your name and any other info you want included in the very beginning of your programs.
- 55 -
To keep the comments to a minimum, we will delete the header comment block and enter the following program.
Source code
' My first program
Device = 18f4620
Clock = 10
Include "usart.bas"
Include "convert.bas"
Dim status_led As PORTC.0
Dim x As Word
TRISC.0 = 0 'Sets pin PORTC.0 to be an
output
x=0
SetBaudrate(br9600)
While true
x = x + 1
High (status_led)
USART.Write("Hello from HamStack #", DecToStr(x), 10,13)
DelayMS (500)
Low (status_led)
DelayMS (500)
Wend
Note:This program assumes you have an assembled HamStack CPU board with the serial RS-232 cable plugged in and connected to your PC. If your PC does not have a RS-232 port you can use a USB to serial RS-232 dongle adapter.
- 56 -
Step 2 – Compile the Program
Click the “Build” button to compile the program. This step will generate a .hex file that will be downloaded into the CPU board.
At the bottom of the screen, the Results window will either list problems with the program or show the “Compilation Success” window.
You must configure your “build” option before you compile any programs.
Select the little downward pointing triangle next to the “Build” button at the top of the screen.
Select Option / Compile Only
This tells the compiler to generate the .hex code but not to automatically download it into your HamStack board. Then use the Microchip PicKit2 programming software to do the firmware download into the CPU board.You can always change this later if you use another programmer.
!Read Me
- 57 -
Step 3 – Downloading your program into the CPU chip
Make sure your HamStack USB programmer is plugged into your PC.
Then plug the programming ribbon cable into the HamStack board. Note the location of the red wire on the ribbon cable. The pin on the red striped wire goes to the “M” pin of the programming connector on the CPU board.
Red stripe
- 58 -
Launch the Microchip PicKit2 programming software.Your screen should look like this...
Click the [Erase] button to erase the program from the CPU chip.
Now do File / Import Hex ...
If everything is working properly, the PicKit software should detect the CPU board and report the type of CPU chip it found.
It should detect an 18F4620 CPU chip.
The status window should say “PIC Device Found.”
You are now ready to read in the .hex file you just compiled.
- 59 -
Now you should see the status window say “Hex file successfully imported.”
You can tell the file was imported because you can see the code displayed in the “Program Memory” window.
All you have to do now is press the [Write] button and the program will be downloaded into the CPU chipIf all goes well, you will see the message: “Programming Successful.”
- 60 -
4. Watch the LED blink monitor activity on the serial port.
Now, lets launch Termite, the terminal program to watch the serial data coming from the CPU board.
Now click the Settings button to set the COM port.
Make sure the baud rate is set for 9600. Every computer is different so you will have to figure out the right COM port. If you click the Port pull down menu, you will see the available COM ports on your computer.Then click [OK].
- 61 -
If everything is working properly, you should see the status LED blinking and text like this in the Termite terminal window.
Now that you can see it all working together, this is a great time to experiment. Go back to the source code and modify the program. Change the timing on the LED delays, change the text in the serial output line, etc.
Take your new source code and run it through the whole process of compiling and downloading a few times to get the hang of it.
The next step is to try some of the other examples in this book.
- 62 -
Section 5
Program Examples
- 63 -
Program Examples
These program examples are written for the standard HamStack CPU board and DEV-1 development board. They are helpful to understand the basic hardware and software development process using the HamStack and they can be combined to build your own projects.
These examples use the native 10 MHz crystal frequency and not high speed PLL mode. When making more complex projects, the PLL can be enabled to run the CPU up to 40 MHz.
The HamStack CPU board also supports the 18F46K22 and newer CPU chips. The standard HamStack CPU boards with these chips use a 16 Mhz crystal and can run at 64 MHz in 4x PLL clock mode. When using these faster chips, replace the first few lines of each sample program in this section with the following code...
Device = 18F46K22 ' Assign CPU device type
Clock = 16 ' Set effective clock frequency
If you want to use the higher speed 4x PLL mode that can clock the chip at 64 MHz, use this header...
Device = 18F46K22 ' Assign CPU device type
Clock = 64 ' Set effective clock frequency
Config fosc = HSHP ' Set clock mode to 4x PLL (16 x 4 = 64 MHz)
Config PLLCFG = on ' Turn on 4x PLL mode
#option usart_brgh = TRUE ' Configure serial UART for 4x PLL mode
#option usart_brg16 = TRUE ' Configure serial UART for 4x PLL mode
- 64 -
Schematic
Digital Output
DescriptionThe simplest example of digital output is blinking an LED. When a CPU output pin goes high, logic state 1, the pin's voltage is +5v. When the pin goes low, logic state 0, the voltage at the output pin is 0 volts. In this example output RBC toggles between high and low logic states blinking the LED. Note: The CPU board already has the status LED wired up to RC0. You can just compile and load this program to see it blink or add your own LED in parallel witht the status LED and watch both blink.
Swordfish Basic Code Swordfish Basic Code Using the “goto” statement Using the “while” statement
Notes
Device = 18F4620
Clock = 10
TRISC.0 = 0
while true
High (PORTC.0) 'LED on
DelayMS (500) 'Wait
Low (PORTC.0) 'LED off
DelayMS (500) 'Wait
wend
In the example above, the goto statement sends the program back up to the top to create the loop. In the second example, the while statement performs the same task.
The Status LED on the HamStack CPU board is already connected to CPU pin C0. This example will work with the HamStack CPU board by itself plugged into the DEV-1 board.
Device = 18F4620
Clock = 10
TRISC.0 = 0
master_loop:
High (PORTC.0) 'LED on
DelayMS (500) 'Wait
Low (PORTC.0) 'LED off
DelayMS (500) 'Wait
GoTo master_loop
- 65 -
Digital Input
Description
A digital input is used to register a push button, switch closure of any kind of digital signal transition. In this case, we will sense the state of a pushbutton and turn an LED on and off. The digital input is pulled up to +5v through a 10k resistor. When the switch is pressed, the circuit is closed and the input is pulled to ground.
Hardware Swordfish Basic Code
Notes
Device = 18F4620
Clock = 10
Dim button As Byte
TRISB.0 = 0 ' LED output pin
TRISA.1 = 1 ' Push button pin
master_loop:
button = (PORTA.1)'Read button
If button = 1 Then
High (PORTB.0) 'LED on
Else
Low (PORTB.0) 'LED off
EndIf
GoTo master_loop
RA1
+5V+5v
GND
CPU pin
Schematic
LEDRB0
SwitchRA1
LEDRB1
SwitchRA2
LEDRB2
SwitchRA3
LEDRB3
SwitchRA4
- 66 -
Relay Control
Description
Relays are used to control real world signals. Microcontroller output pins can not directly drive most relays so an additional buffer device is required. You can use a transistor or an array of transistors such as the ULN2803 chip.This example shows how to use a common 2N2222 NPN transistor as the buffer. The circuit illustrated uses a 5 v DC relay. When the relay is on, the status LED on port RC0 is also on.
Schematic
Notes
Device = 18F4620
Clock = 10
Dim relay As PORTB.4
Dim led As PORTC.0
TRISC.0 = 0 ' LED output pin
TRISB.4 = 0 ' Relay control
While true ' Do forever
High (relay) ' relay on
High (LED) ' LED on
DelayMS (500) ' Wait 500 ms.
Low (relay) ' relay off
Low (LED) ' LED off
DelayMS (500) ' Wait 500 ms.
Wend
RB4
Components
Swordfish Basic Code
When RB4 is set high, putting +5v on the pin, the transistor will turn on pulling the collector close to ground. This causes current to flow through the relay’s coil actuating the relay contacts. So a logic “1” will turn on this relay. In this example we will also turn on the status LED to track the state of the relay.
- 67 -
Analog Input
Description
An analog input pin can measure a DC voltage between 0 and 5 volts. In this program, every 250 ms. we sample the input pin AN0 which has been configured as an analog input. Using the 10 bit A/D converter in the CPU, the raw value of the sample is between 0 and 1023 In this example, sampled value is converted to the voltage and sent to the serial port.
Swordfish Basic Code
Circuit
Device = 18F4620
Clock = 10
Include "usart.bas"
Include "ADC.bas"
Include "convert.bas"
Function ADInAsVolt() As Word
' Read analog input AN0 and scale for 0 - 5 volts...
result = (ADC.Read(0) + 1) * 500 / 1024
End Function
Dim ADVal As Word ' This is the sampled analog value
TRISA.0 = 1 ' Set AN0 direction as an input
ADCON1 = %00001110 ' Set AN0 pin type as an analog input
SetBaudrate(br9600) ' Set baud rate to 9600
DelayMS (500)
'--- Main Program Loop ---
While true
ADVal = ADInAsVolt
USART.Write("DC Volts = ", DecToStr(ADVal / 100))
USART.Write(".", DecToStr(ADVal, 2), " ", 13, 10)
DelayMS(500)
Wend
GND
RA0
+5v
Pot
Ext
Jumper JU3Pins 1 & 2
- 68 -
RS-232 Output example_serial_out.bas
Description
The serial port on the HamStack is very useful for controlling external devices as well as for debugging your code.It is very easy to generate serial data output. You must include the usart.bas module in your code, set the serial port speed and you are ready to start sending serial data.For debugging your program code, you can insert write statements to the serial port and capture it using a terminal program such as HyperTerm or Tera Term.
Swordfish Basic Code
Circuit
Device = 18F4620
Clock = 10
Include "usart.bas"
Include "convert.bas"
Dim x As Word
SetBaudrate(br9600) ' Set baud rate to 9600
DelayMS (500)
x = 0
USART.Write ("HamStack is ready to go...", 10, 13)
'--- Main Program Loop ---
While true
x = x + 1
USART.Write("The count is = ", DecToStr(x), 10, 13)
DelayMS(500)
Wend
- 69 -
Using LCD Displays
Description
The HamStack supports the popular LCD displays that use the Hitachi LCD controller chips. This examples shows how to send text to the LCD display using the 4 bit parallel data mode. The LCD pins are D4, D5, D6, D7 and two pins for control, RS, E. These are mapped to the HamStack port D pins RD0 to RD5 respectively.Sending commands to the LCD is very simple using the WriteAt () subroutine in the LCD module.
Schematic
Swordfish Basic Code
Device = 18F4620
Clock = 10
#option LCD_DATA = PORTD.0
#option LCD_RS = PORTD.4
#option LCD_EN = PORTD.5
Include "usart.bas"
Include "lcd.bas"
SetBaudrate(br9600)
While true
Cls ' Clear LCD
WriteAt(1, 1, "Hello world")
USART.Write("Hello World", 10, 13)
DelayMS(1000)
Wend
+5V +5V
RD5RD4RD3RD2RD1RD0
- 70 -
Measuring Temperature with a DS18B20
Description
If you have the optional digital temperature probe you can measure temperature with the DEV-1 board.In this example we will use a DS18B20 digital temperature sensor. This device reads temperature and returns the value in degrees centigrade and Fahrenheit. The temperature value is sent to the serial port at 9600 baud.
Swordfish Basic Code
Circuit
Device = 18F4620
Clock = 10
Include "usart.bas"
Include "DS18B20.bas"
Include "convert.bas"
Dim LED As PORTC.0 ' Status LED
Dim TempA As ShortInt ' Temp C from DS18B20
Dim TempB As Word ' Temp C from DS18B20
Dim tempf As Word ' Temp converted from C to F
SetBaudrate (br9600) ' Set serial port to 9600 baud
SetPin(PORTD.7) ' Assign pin RE0 to temperature probe
ADCON1 = %00001011 ' Set 4 analog inputs, rest digital
Low(LED) ' Set status LED to off
If Not Find Then ' Look for temperature probe
USART.Write ("No temp probe", 10, 13)
Else ' Temperature probe found, process normally...
While true ' Do this loop forever
High (LED) ' Turn ON LED to show activity
Convert
GetTemp(TempA, TempB)
tempf = (TempA*1.8)+32
USART.Write ("Temp = ", DecToStr(tempf), 10, 13)
DelayMS (200)
Low (LED)
DelayMS (500)
Wend
EndIf
RD7
- 71 -
Section 6
Mini Projects
Typical program structure
Temperature controlled fan
CW beacon
- 72 -
Typical Program Structure
A complex Swordfish Basic program contains several sections. Most of these sections must occur in a specific order to work properly. Here is the standard program flow. Each section show one or two lines as examples.
1. Set configuration parameters Device = 18F4620 ' Assign CPU device type
Clock = 10 ' Set effective clock frequency
2. Include subroutine librariesInclude "ADC.bas" ' A/D converter subroutines
Include "eeprom.bas" ' Include EE PROM subroutines
3. Physical IO pin assignments Dim analog_in As PORTA.0
Dim button1 As PORTA.1
4. Variable declarations Dim x As Byte
Dim ainput0 As Word
5. Subroutines Public Sub relay_on () High (relay) End Sub
6. Serial Port Configuration SetBaudrate(br9600) ' Set baud rate
7. Difine pin directions TRISA.0 = 1 ' analog_in
TRISA.1 = 1 ' button1
8. CPU Configuration Parameters ADCON1 = %00001110 ' Set AN0 to be analog input
9. Initialize variables x = 0
10. PROGRAM STARTUser code to run at program start time - runs only once
Cls
WriteAt (1,1,"Welcome")
11. Main control loop - user code goes hereWriteAt (1,1,“Hello world! ")
- 73 -
Mini ProjectTemperature Controlled Fan
Description
This project illustrates how to read a temperature with a Dallas Semiconductor DS18B20 digital temperature sensor and use that temperature to turn on a cooling fan.When the temperature reaches the target temperature, it will turn on the relay which turns on power to the cooling fan.
The program will also send the current sampled temperature out the serial port at 9600 baud.
Circuit
RB4
+12VDC
RD7
- 74 -
Mini ProjectTemperature Controlled Fan
Swordfish Basic Code
' fan_control.bas
Device = 18F4620
Clock = 10
Include "usart.bas"
Include "DS18B20.bas"
Include "convert.bas"
Dim LED As PORTC.0 ' Status LED
Dim relay As PORTB.4 ' Fan relay
Dim TempA As ShortInt ' Temp C from DS18B20
Dim TempB As Word ' Temp C from DS18B20
Dim tempf As Word ' Temp converted from C to F
SetBaudrate (br9600) ' Set serial port to 9600 baud
SetPin(PORTD.7) ' Assign pin RE0 to temperature probe
ADCON1 = %00001011 ' Set first 3 inputs to analog
Low(LED) ' Set status LED to off
If Not Find Then ' Look for temperature probe
USART.Write ("No temp probe", 10, 13)
Else ' Temperature probe found, process normally...
While true ' Do this loop forever
High (LED) ' Turn ON LED to show activity
Convert
GetTemp(TempA, TempB)
tempf = (TempA*1.8)+32
USART.Write ("Temp = ", DecToStr(tempf), 10, 13)
If tempf > 70 Then ' Temperature trigger
High (relay)
Else
Low (relay)
EndIf
DelayMS (200)
Low (LED)
DelayMS (500)
Wend
EndIf
- 75 -
Mini ProjectCW Beacon
Description
This project shows how easy it is to generate CW. You set the cw_string variable to be the text you want to send. The program will send that string in CW keying output RB4 which would be connected to a relay or an open collector output buffer transistor. The program will send the string and loop forever.
Note: When the voltage is removed from a relay coil, an induced voltage transient may be generated across that coil as its magnetic flux, which is linked by the coilturns, collapses. This transient voltage spike can damage the transistor driving the coil.To eliminate this spike, you can put a diode across the relay coils with the anode connected to the ground side and the cathode connected to the voltage (+12v) supply side.
RB4
- 76 -
Mini Projectcw_beacon.basCW Beacon
Swordfish Basic Code
' cw_beacon.bas This program sends a message in CW forever
Device = 18F4620 ' Set the CPU type to a Microchip 18F4620
Clock = 10 ' Set CPU clock frequency to 10 MHz
Include "string.bas" ' Include the string manipulation subroutines
Include "usart.bas" ' Include the RS232 UART subroutines
'----- VARIABLE DEFINITIONS ---------------------------------------
Dim wpm As Byte ' CW speed in words per minute
Dim cw_string As String(30) ' CW message to be sent
Dim cw_time As Word ' Calculated time value of a dit in ms.
Dim cw_len As Byte ' Working variable, length of string
Dim i As Byte ' Working variable
Dim x As Byte ' Working variable
Dim y As Byte ' Workign variable
Dim cw_char As String(2) ' Holds the character being sent
Dim cw_bits As String(15) ' Dit / Dah pattern being sent
Dim cw_temp As String(2) ' Working variable
Dim led As PORTC.0 ' Assign the name "LED" to RC0
Dim relay As PORTB.3 ' Assign the name "relay" to port RB3
'----- DEFINE PIN DIRECTIONS --------------------------------------
'Pin function. GPIO is General Purpose IO.
TRISA.1 = 1 ' Mode button
TRISB.4 = 0 ' Relay 1
TRISC.0 = 0 ' Status LED
'----- INITIALIZE VARIABLES AND SERIAL PORT ------------------------
SetBaudrate(br9600) ' Set serial baud rate to 9600
cw_string = "CQ CQ CQ DE W6ABC W6ABC" ' CW message to be sent
wpm = 13 ' CW speed in words per minute
'----- START MAIN PROGRAM CODE -------------------------------------
DelayMS(500) ' Pause for 500ms after hardware reset
USART.Write("Beacon program will send " + cw_string + " forever.", 13, 10)
cw_time = 1200 / wpm ' Calculate the length of a dit
cw_len = Length(cw_string) ' Determine the length of the string
- 77 -
Mini ProjectCW Beacon
Swordfish Basic Code
'----- START MASTER CONTROL LOOP ------------------------------------
master_loop: ' Outer loop will process
the whole string.
For i = 0 To cw_len-1 ' Go through the string
cw_char = Mid(cw_string,i,1) ' Grab the current char
USART.Write("Sending: ", cw_char, 13, 10)' Send char serial port
Select cw_char
Case "A" : cw_bits = ".-"
Case "B" : cw_bits = "-..."
Case "C" : cw_bits = "-.-."
Case "D" : cw_bits = "-.."
Case "E" : cw_bits = "."
Case "F" : cw_bits = "..-."
Case "G" : cw_bits = "--."
Case "H" : cw_bits = "...."
Case "I" : cw_bits = ".."
Case "J" : cw_bits = ".---"
Case "K" : cw_bits = "-.-"
Case "L" : cw_bits = ".-.."
Case "M" : cw_bits = "--"
Case "N" : cw_bits = "-."
Case "O" : cw_bits = "---"
Case "P" : cw_bits = ".--."
Case "Q" : cw_bits = "--.-"
Case "R" : cw_bits = ".-."
Case "S" : cw_bits = "..."
Case "T" : cw_bits = "-"
Case "U" : cw_bits = "..-"
Case "V" : cw_bits = "...-"
Case "W" : cw_bits = ".--"
Case "X" : cw_bits = "-..-"
Case "Y" : cw_bits = "-.--"
Case "Z" : cw_bits = "--.."
Case "0" : cw_bits = "-----"
Case "1" : cw_bits = ".----"
Case "2" : cw_bits = "..---"
Case "3" : cw_bits = "...--"
Case "4" : cw_bits = "...-"
Case "5" : cw_bits = "....."
Case "6" : cw_bits = "-...."
Case "7" : cw_bits = "--..."
Case "8" : cw_bits = "---.."
Case "9" : cw_bits = "----."
Case "/" : cw_bits = "-..-."
Case "=" : cw_bits = "-...-"
Case " " : cw_bits = " "
EndSelect
- 78 -
Mini ProjectCW Beacon
Swordfish Basic Code
' This section sends the individual dits and dahs
x = Length(cw_bits) ' How many dits and dahs ?
For y = 0 To x-1 ' Loop through sending each
cw_temp = Mid(cw_bits,y,1) ' Grab the dit or dah
If cw_temp = "." Then ' Check for dit
High(led) ' Turn on the LED
High(relay) ' Key down relay #1
DelayMS(cw_time) ' Wait for one dit
Low(led) ' Turn off the LED
Low(relay) ' Unkey relay #1
DelayMS(cw_time) ' Wait for one dit
EndIf
If cw_temp = "-" Then ' Check for dah
High(led) ' Turn on the LED
High(relay) ' Key down relay #1
DelayMS(cw_time * 3) ' Wait for one dah
Low(led) ' Turn off the LED
Low(relay) ' Unkey relay #1
DelayMS(cw_time) ' Wait for one dit
EndIf
If cw_temp = " " Then ' If space? If so...
DelayMS(cw_time * 7) ' Wait for 7 dits
EndIf
Next ' Send the next dit or dah
' Now that all the dits and dahs are sent...
DelayMS(cw_time * 3) ' Delay the length of 3 dits
Next ' Go to the next character
' All characters in the string have been sent.
DelayMS(cw_time * 7) ' Delay the length of 7 dits
GoTo master_loop ' Go back and loop forever
- 79 -
Section 7
Accessory and Expansion Boards
Prototype backpack board
LCD with 4 bit interface
8A relay module
RS-485 & 2 Small Signal Relays
Serial to USB adapter
- 80 -
Prototype Backpack Board
- 81 -
Prototype Backpack Board Options
Typical configuration with
stacking connectors. All
interconnect signals brought
to the top of the board.
Additional power and ground
are available.
Two unwired pushbuttons
and three unwired LED are
convenient accessories.
A solderless breadboard
block can be attached to the
PCB providing a convenient
way to build and test new
circuits.
The backpack easily stacks
on top of the CPU board.
The CPU is slightly longer
allowing access to the
pushbuttons, LEDs and
RS232 connector.
- 82 -
Prototype Backpack Board – Rev 1
The prototype backpack board is used to build custom projects and easily plug them on top of the CPU board. Adding a solderless breadboard to the prototype backpack board allows you to experiment with circuits before soldering them in place. The prototype board has all the CPU IO pins brought up through stacking SIP connectors. In addition there are also 3 LED and 2 push buttons. These extra components are not connected to anything by default. The use of stacking connectors allow you to stack multiple accessory boards on the HamStack. The physical dimensions and electrical signals are compatible with the Arduino Uno and similar single board computers. While there can never be 100% compatibility, most Arduino shield boards should be hardware compatible with HamStack.
- 83 -
Prototype Backpack Board – Rev 1
6 Ground pads
6 +5v power pads
In-circuit programming jack connections
3 LEDs Resistor pack pull down to ground
LED jumper block
2 Push buttons
Push button jumper block
Solder pads connected together
Individual solder pads not connected to anything
- 84 -
Prototype Backpack Board – Rev 2
- 85 -
Prototype Backpack Board – Rev 2
6 Ground pads
6 +5v power pads
In-circuit programming jack connections
3 LEDs Resistor pack pull down to ground
LED connection points
2 Push buttons
Push button connection points
Solder pads connected together
Individual solder pads not connected to anything
Pullup resistors
LCD Jack
The rev 2 prototype backpack board includes a 10 pin header connector connected to CPU pins D0...D5.The HamStack LCD interface cable plugs directly into that socket making it easy to connect up the LCD wihout cutting any wires or soldering them to the pads.
- 86 -
Backpack Prototype Board Assembly
When assembling the backpack board, the minimum components necessary are the stacking connectors. These connectors provide all the power, CPU IO and other useful signals from the CPU board to the prototype boards.
The stacking connectors are single in-line header connectors with long leads that connect into the female connector below. Additionally there are female SIP connectors with short leads that are used to provide convenient connections for prototype jumpers to ground, +5v, LEDs and push buttons.
Note: Make sure you install the long stacking connectors along the edges. The short pin connectors are used inside the board.
The long lead stacking connectors are placed in the 7 positions shown in this picture.
When soldering the connectors, first place the connector and solder only one pin. Make sure the connector is snug against the PCB and it is vertical.
- 87 -
Backpack Solderless Breadboard
An option to prototyping new circuits is to use the solderless breadboard block. The block comes with sticky tape on the bottom. Just peel off the paper and stick the block to the prototype board. We recommend installing all the SIP sockets first to make sure none of the holes are covered by the bread board block.
When properly installed, the board looks like this.
With these breadboard blocks, the five horizontal holes on each side are bussed together. This allows easy placement of DIP components and other devices. Wire jumpers are used to make the connections between the parts on the bread board and the CPU IO pins that are brought up to the SIP header connectors on top of the prototype backpack board.
When assembling the prototype board, the components you choose to install are completely up to you. If you want to drill holes, add parts, do whatever you want. The prototype board is made for experimentation and exploration.
- 88 -
Fully Assembled Breadboard
Top view of completed prototype board with breadboard block.
Bottom view of the assembled prototype board.
Prototype board installed on top of the CPU board. Note that the pushbuttons, LEDs and serial IO connector are
easily accessible.
- 89 -
2 x 16 LCD Display with 4 Bit Interface
The LCD pack provides a 2 line by 16 character backlit LCD display and an interface board. The interface supports the standard 4 bit Hitachi control signals. There are 6 signals that must be hooked up. These are Data 4, 5, 6, 7, (called D4, D5, D6, D7) and the RS and E control lines. The interface cable supplied is a 10 wire ribbon cable with a 2x5 pin header connector on the end. When using the HamStack Project board or Prototype Backpack Rev 2 that supports this connector, you just plug it in and go. If you are interfacing to a HamStack CPU board directly, you will have to either adapt the connector or cut it off and wire the 6 control signals directly to the CPU board using solder pads.The schematic below shows how to make the proper connections when connecting directly to the CPU board.The interface board must be soldered to the LCD display. Mount the interface board to the back of the LCD display and solder the 16 pins in place.
Note: The CPU board provides limited current through connector J3. We recommend using an alternative source of the +5 voltage especially when the CPU board is powering additional devices.
Note: 10 pin header connector on the ribbon cable will plug directly into the Project board or the GPIO board.
- 90 -
Dual 8A Relay Module
This relay module provides two single pole, double throw relays with a maximum current rating of 8 AMPs. The relay 1 and 2 are connected to IO pins B3 and B2 respectively. Setting the IO pin on the CPU to a high state will actuate the relay.Connections are made to the relay board through screw terminal blocks or wires can be soldered directly to the board.
The board is designed with an absolute maximum current capacity of 8A. If your application will operate at the high end of the maximum current capacity, we recommend that you add additional wire tack soldered to the bottom of the board to ensure current spikes will not damage the circuit board traces.The relays are rated well above the 8A maximum
Powering the relaysJumpers are provided to route either the +5V DC or V-In from the CPU board. There are three options to power the relays as follows.
1 – Use the supplied 12 volt relays and an external 12 volt power supply connected to the +Vin screw terminal. This is a recommended method. Do not install any jumpers.
2 – Use the external +Vin from the CPU board. Assuming ther +Vin voltage is enough to actuate the relay (~12 DC). The only dowside to this approach is that you will also be powering the whole HamStack from the same supply. If you are using a lower supply voltage, say +7.5v DC, this may not reliably actuate the relays.
3 – You can hack the board to use your own 5v relays. The jumper is provided to route 5v DC to the relays but you must make sure the relays don't draw too much current
- 91 -
8A Relay Module
The 8A relay module can be mounted to a chassis with the 4 screw holes or built into a board stack. Due to the height of the relays, the 8A relay module must be the top board when building a board stack.and only one board will fit on a stack at a time.
- 92 -
8A Relay Module
Front view
The relay contacts are brought out to the front edge of the board. Each relay's SPST connections are represented byNC – Normally closedC - CommonNO – Normally openThe default wiring for control is from RB3 to the left terminal block and RB2 to the right terminal block.
Note: the ULN2803 transistor buffer array chip has built-in coil spike suppression diodes.
Rear view
The terminal block on the rear of the board is used to supply the coil voltage for the relays. The supplied relays are rated at a nominal 12v DC to operate. They will engage as low as 9v DC.
The relays are normally powered by an external 12v DC supply connected to the rear terminal block.
If you supply an input voltage to the CPU board over 9v DC, inserting the jumper labeled VI_En will route the CPU boards input voltage to the relay coils.
- 93 -
Serial to USB Adapter
The serial to USB interface converts the TTL signals from the CPU board to USB for connection to a PC. When using the adapter, remove the MAX232 lever converter chip on the CPU board.
The adapter is installed with a 6 pin SIP male header.
1. Do not install the DB9 connector.
2. Solder the six pin male header to the Project Board PCB.
3. Slip the USB adapter on to the 6 pin header and solder it in place.
4. Install the FTDI serial driver on your PC.
5. At this point you are ready to talk from the PC to the Project board through the USB connection.
- 94 -
Appendix
Prototype backpack board worksheet
Component identification guide
ASCII character table
- 95 -
Prototype Backpack Board Rev 1 Worksheet
- 96 -
Prototype Backpack Board Rev 2 Worksheet
LCD
- 97 -
Component Identification Guide
DiodeCommon part: 1N4004
The band on the diode is
The cathode side.
cathode
Integrated circuit
Make sure pin1 is in the right
position.
Pin 1 is indicated by the dot.
Resistor packMultiple resistors in a
package. Values indicated
by a 3 digit number. IE
“103” means 10k
Resistor
Quarter watt.
Value indicated by
color code.
Dipped monolithic
capacitor. 3 digit
number. IE “103”
means 10,000 pf or
0.01uf.
Electrolytic capacitor
Insert positive lead into
the square solder pad.
Long lead = positive.
Terminal block
Screw terminal block.
Crystal
Make sure the crystal
insulator is installed
under the crystal case
to prevent shorting out.
Inductor
Sealed inductor.
NPN transistor
TO-92 plastic case
transistor
(PN2222)
LM2576
Swtiching
voltage regulator
TO-220-5 case
Linear voltage regulator
TO-92 plastic case
(78L05, etc.)
LED (Size: T1)
Insert long lead
(anode) into the
square solder pad.
LED (Size: T 1-3/4)
Insert long lead (anode)
into the square solder
pad.
Optocoupler with
optically isolated
darlington transistor.
6 pin DIP package
Solid State Relay
6 pin DIP package
E
Com
Out In
C
E
B
Top view
B
E
C
Top viewC
O
I
B
C
- 98 -
Component Identification Guide
DC coaxial power jack Pushbutton
Momentary
contact
pushbutton.
Jumper block 3.5mm stereo jack
Shunt RJ45
Tab up configuration
with built in LEDs.
3 Pin connector DB9 connector
Reed Relay SPST
The reed relay is fast and
quiet. Make sure pin 1 is
in the proper orientation.
40 Pin machined IC socket
Install socket with the dimple on
one end pointing toward pin 1.
Crystal Insulator
Make sure the crystal
insulator is installed under
the crystal can.
6-18 Pin machined IC socket
Install socket with the dimple on
one end pointing toward pin 1.
3 pin connector
Molded plastic connector
with alignment tab
Contact point
Inserted into molded
plastic connector
8 Amp power relay
This power relay is designed to
switch medium power loads. Each
set of contacts supports up to 8
Amps.
DS18S20
Temperature sensor
using the DS OneWire interface in
a TO-92 plastic case
G
Top view
D
G
VV
D
100 uh inductor
This inductor is used in the switching
power supply.
- 99 -
AS
CII T
able
Dec Binary Hex Char Char Dec Binary Hex Char Dec Binary Hex Char
0 0 0 NUL 32 100000 20 80 1010000 50 P
1 1 1 ^A SOH 33 100001 21 ! 81 1010001 51 Q
2 10 2 ^B STX 34 100010 22 " 82 1010010 52 R
3 11 3 ^C ETX 35 100011 23 # 83 1010011 53 S
4 100 4 ^D EOT 36 100100 24 $ 84 1010100 54 T
5 101 5 ^E ENQ 37 100101 25 % 85 1010101 55 U
6 110 6 ^F ACK 38 100110 26 & 86 1010110 56 V
7 111 7 ^G BEL 39 100111 27 ' 87 1010111 57 W
8 1000 8 ^H BS 40 101000 28 ( 88 1011000 58 X
9 1001 9 ^I HT 41 101001 29 ) 89 1011001 59 Y
10 1010 A ^J LF 42 101010 2A * 90 1011010 5A Z
11 1011 B ^K VT 43 101011 2B + 91 1011011 5B [
12 1100 C ^L FF 44 101100 2C , 92 1011100 5C \
13 1101 D ^M CR 45 101101 2D - 93 1011101 5D ]
14 1110 E ^N SOH 46 101110 2E . 94 1011110 5E ^
15 1111 F ^O SI 47 101111 2F / 95 1011111 5F _
16 10000 10 ^P DLE 48 110000 30 0 96 1100000 60 `
17 10001 11 ^Q DC1 49 110001 31 1 97 1100001 61 a
18 10010 12 ^R DC2 50 110010 32 2 98 1100010 62 b
19 10011 13 ^S DC3 51 110011 33 3 99 1100011 63 c
20 10100 14 ^T DC4 52 110100 34 4 100 1100100 64 d
21 10101 15 ^U NAK 53 110101 35 5 101 1100101 65 e
22 10110 16 ^V SYN 54 110110 36 6 102 1100110 66 f
23 10111 17 ^W ETB 55 110111 37 7 103 1100111 67 g
24 11000 18 ^X CAN 56 111000 38 8 104 1101000 68 h
25 11001 19 ^Y EM 57 111001 39 9 105 1101001 69 i
26 11010 1A ^Z SUB 58 111010 3A : 106 1101010 6A j
27 11011 1B ^[ ESC 59 111011 3B ; 107 1101011 6B k
28 11100 1C ^\ FS 60 111100 3C < 108 1101100 6C l
29 11101 1D ^] GS 61 111101 3D = 109 1101101 6D m
30 11110 1E ^^ RS 62 111110 3E > 110 1101110 6E n
31 11111 1F ^_ US 63 111111 3F ? 111 1101111 6F o
64 1000000 40 @ 112 1110000 70 p
65 1000001 41 A 113 1110001 71 q
66 1000010 42 B 114 1110010 72 r
67 1000011 43 C 115 1110011 73 s
68 1000100 44 D 116 1110100 74 t
69 1000101 45 E 117 1110101 75 u
70 1000110 46 F 118 1110110 76 v
71 1000111 47 G 119 1110111 77 w
72 1001000 48 H 120 1111000 78 x
73 1001001 49 I 121 1111001 79 y
74 1001010 4A J 122 1111010 7A z
75 1001011 4B K 123 1111011 7B {
76 1001100 4C L 124 1111100 7C |
77 1001101 4D M 125 1111101 7D }
78 1001110 4E N 126 1111110 7E ~
79 1001111 4F O 127 1111111 7F •
- 100 -
Document Revision History
V1.1
Page 82 - Fixed errors on the 8A relay schematic to match the PCB.
Page 11, 12 - Noted on the CPU board revision 1, that J3 pin 5 should be ground but is isolated.
V1.2Various minor edits.
V1.3Added prototype backpack rev 2.
V2.0Several edits and minor corrections.
V3.0Add DEV-1 board information.
- 101 -
CP
U B
oard
v1,
v2,
v3 S
ch
em
ati
c
- 102 -
CPU Board V1, V2, V3 - Parts Placement
Parts List – Required Components
C1 10uf electrolytic capacitor
C2, C3 0.1 uf capacitor (104)
C4, C5 22pf capacitor (22)
C6 0.1 uf capacitor (104)
C7, C8, C9, C10
1 uf electrolytic capacitor
R1, R2 270 Ohm ¼ w resistor (270)
RN1 10k resistor pack (103)
D1, D2 Red T1 LEDs
S1, S2 Pushbutton switch
Y1 10 or 16 MHz crystal
INS1 Crystal insulator
U1 78L05 5v voltage regulator
U2 CPU chip
U3 MAX232 RS232 level shifter IC
J1, J2, J4, J6 Inner connector row 8 pin
female socket pointing up
J3, J5 Inner connector row 6 pin
female socket pointing up
J7 3 pin male connector with tab
J8 2.1mm DC power jack
J9 6 pin female socket pointing up
JP1 2 pin jumper and shunt
Parts List – Optional Components
J1, J2, J4, J6 Outer connector row, 8 pin
female socket pointing down
J3, J5 Outer connector row, 6 pin
female socket pointing down
- 103 -