Free Web Site - Free Web Space and Site Hosting - Web Hosting - Internet Store and Ecommerce Solution Provider - High Speed Internet
Search the Web

Liberty BASIC Developer
LBDev ezine

 

Home
About
Current Issue
Past Issues
Files
Links
FAQ
Contact

Liberty BASIC Developer

Vol. 1 No. 6 December 2001

Contents:

Editors Note

LB News

Serial Port Primer

COMMAND Focus: Open "Com...

Taking Liberties

Site links

Next Month

Feed back

Legal Stuff

Editors Note

Well Christmas will be upon us shortly and as usual time has slipped by quickly. I was not able to do 1/10 of the things that I wanted, such is life. In this issue I have written what I hope will be a helpful article on the serial port. Then our Command Focus looks at the open"com... command. Please let know what you think. This month Michael Martin has given us something new call TAKING LIBERTIES, I hope that you enjoy it.

Happy Programming

Neil Tremblay

top

LB News

Work on LB3 continues, Carl had said that beta testing should start soon. I am looking forward to giving it a try. If you are looking any programming information using LB first check the LB web site and then any links in the resource section.

If you missed it, Alyce has created a fun game called turkey trot (Thanksgiving theme). Unfortuneatly my goose got cooked. This game was created using the Game Workshop. Check it out, maybe we will see some interesting and fun MAD elf game.

top

Serial Port Primer

Introduction

Serial communications is the process of sending data bits down a wire in single file between 2 pieces of equipment. To have the recieving device understand what data is valid and not just random noise we require both devices to have some sort of synchronizing. There are 2 main types of serial communications, they are synchronous and asynchronous.

Synchronous Communications

Synchronous communications entails that each data bit be referenced to a clock signal which is common to the transmitting and receiving systems. This helps the recieving system distinguish between data bits arriving. If this clocking signal is lost no communications can take place. An example of this is the connection of your keyboard to your computer.

Asynchronous Communications

Asynchronous communications, which is a variation of syncronous communications, specify's that a marker pulse will be added to show the start of a stream of bits. This system does away with the clock signal which must be connected between the 2 devices, thus removing the number of wires required to have effective communication. Here is a diagram of a simple serial communications setup.

-figure 1-

Another note to this is that because you have a start pulse to a stream of bits the recieving system can be continually reset to the same timing as the sending system.

Communication Devices

There are 2 main groups of serial communication devices. They are Data Terminal Equipment (DTE) and Data Communication Equipment (DCE). Your computer is a DTE device. Your modem which you may have is a DCE device. Here are a couple of pictures of DTE and DCE devices.

DTE device

DCE devices

RS232

This is the protocol used for serial port communication between devices. It defines the rules which are to be followed for effective communications between equipment. This is a combination of the way data is transmitted, signal levels and control signals.

Signal Levels

The signal levels or polarity of data on the serial lines are opposite to that of normal logic levels. In normal ttl logic as positive voltage represents a '1' and zero volts represents '0'. For serial communications '1' is -3 to -25 volts and '0' is +3 to +25.

'0', Asserted, ON, Space, Active
'1', Disasserted, OFF, Mark, Inactive

Bit Rate

The speed at which data is sent is based upon the bit rate. That is the number of bits per second or bps. You will also hear this refered to as baud rate. This can go from 75 bps to 115200 bps.

Data Frame

The data frame used in serial communications is made up of a start bit, a number of data bits, a partity bit if desired and last 1-2 stop bits. Lets take a look at a couple of samples. The first one will be 8n1. This means 8 data bits, no parity bit and 1 stop bit.

-figure 3-

Looking at our drawing we have the start bit marked, this is #1. Following the start bit we have our 8 data bits which will be lsb(least significant bit) to msb(most significant bit) going from left to right. These are bits #2 to #9 which are in the blue cross hatch. This data byte contains no parity bit so all that is left is our stop bit, #10.

-figure 4-

Now for figure 4 we have an actual data byte. For this I am using the capital letter 'A'. Its ascii value is 65, which converts to 01000001 in binary. Looking at our data frame we see that the first bit is start. Then going from lsb to msb, bits 2 to 9, we transmit the letter 'A'. And finally our last bit to end the frame is the stop bit.

Parity

You can include an additional bit within the data frame, this is the parity bit. There are 5 possible parity selections. They are none, even, odd, mark and space. As in our previous data frame examples we had used no parity bit. The next four parity configurations insert the parity bit after the data bits, right before the stop bit.

Lets first look at the mark and space parity. They do nothing more than add an additional data bit to the frame. Mark being '1' and Space being '0'.

Now we will look at how even and odd parity works. For the even parity designation, the bit is set according to the number of '1' bits in the data word, such that there will be an even number of '1' bits in the data word and parity bit. Lets use our example for the letter 'A' which has a ascii value of 65. The binary value is 1000001. If we have even parity, the parity bit will be '0' as there are an even number of '1's in the data word. If we had selected odd parity, the parity bit would be set to '1' for the letter 'A'.

Serial Connectors

Here are the serial connection pin outs for a DTE device. Also included is the direction which the signals flow.

DB-25 DB-9 Direction
Shield 1 -
Transmit Data(TD) 2 3 >
Receive Data(RD) 3 2 <
Request to Send(RTS) 4 7 >
Clear to Send(CTS) 5 8 <
DCE Ready(DSR) 6 6 <
Signal Ground(SG) 7 5 -
Received Line Signal Detector(DCD) 8 1 <
DTE Ready(DTR) 20 4 >
Ring Indicator(RI) 22 9 -

Handshaking

As long as equipment is able to assume that it is connected to something and that the other device is listen, serial communication can take place without any handshaking. Unfortuneately this type of communication is not always possible, therefore we need the ability for DTE and DCE equipment to tell each other that they are there and what they are doing. Using our connector diagram lets go through a couple of these signals.

Lets look at the DTR and DSR signals. Our computer, a DTE device will assert the DTR line to let a DCE device know that it is powered up and connected to the serial interface. Our DTE device looks at the DSR line to see if a DCE device is connected to the serial interface, we will know this when the DSR line is asserted by the DCE device.

The next 2 handshaking lines that we need to take a look at are RTS and CTS. Our computer will assert the RTS line to let the DCE device know that we can receive serial data. At this point the DCE device could begin to send data to our computer. If our computer becomes to busy (eg. rx buffer is full), it will disassert the RTS line to let the DCE device know that we are busy for a moment and to stop sending serial data. As soon as we have finished what ever house keeping that was necessary the computer can again assert the RTS line so that communications can continue. For the CTS line our computer looks to see if it is asserted. If so it tells us that we can send serial data to our DCE device. As soon as the DCE device disasserts the CTS line our computer will stop sending data as we know that the DCE device is currently busy with another task.

There are 2 more hardware lines which we should make mention too. The first is DCD, which can also be referred to as CD or Carrier Detect. Our computer will look at this line to check whether we would consider this valid serial data if we were using a modem. The last hardware signal which our computer can see from a DCE device is the RI line. When this line is asserted our computer could send commands to the DCE device to perform some task.

There is another form of handshaking which does not require the extra hardware lines, this is XON/XOFF. For this form of handshaking a control characters are used to stop and start data transfers. The way this works is, if a DTE device is sending info to a DCE device and the DCE buffer is getting to full it will tell the DTE device to stop transmitting by sending the stop control character to it. When the DCE has cleared up some space in its buffer it will send the start control character to tell the DTE device that it can begin transmitting again.

Wiring Connections

dte to dce

dte to dte

Happy programming!

top

COMMAND Focus: Open"Com...

This month we are going to look at opening a serial port for communications. Looking at the Liberty Basic help file we find the syntax for opening a comm port is as follows.

OPEN "COMn:baud,parity,data,stop{,options}" for random as #handle

The command starts with the OPEN statement. Next is our definition string of which comm port we want opened and its settings. Next is for random as we will be able to print to and input data from the comm port. Last is the handle which we assign to the comm port for reference purpose when we use the print or input command.

Lets take a closer look at the definition string to see the minimum information that we will need to set up the comm port for communications. The first part, COMn, where n is the number of the actual comm port within our system that we wish to use. This can be from 1 to 9 depending on were the port has been assigned by the system. Next is the speed at which we wish to transfer data. The available speed selections go from 75 to 115200 bps. This should match the speed of the device which we are communicating. For parity, we are selecting if we wish to use it, and how it will be used. There are 5 selections available, with n (none) and e (even) being the most common. Data is the number of bits in our data word. This can be from 5 to 8, depending on the piece of equipment that we are trying to communicate with. Last is stop, which sets the number of stop bits within the data frame. For stop we have a selection of 1 or 2 (I beleive that 1 is most common). We will cover options further in this article.

Lets create a sample statement and look at exactly what it means.
OPEN "com1:2400,n,8,1" for random as #commPort

This statement opens serial port 1 with the following settings. Speed is 2400 bits per second, no parity bit, 8 data bits and 1 stop bit. There are a couple of hidden things which happen also. The DTR and RTS lines are asserted to let our device which we are communicating with know that we are on and available to receive information. Also when we print to the comm port we will be checking the DSR and CTS lines to see whether the device is on line and available to receive data. Liberty BASIC defaults to allow the device we are communicating with 1 second before a communications error occurs.

Let us now take a look at the 4 optional parameters which we can specify within our definition string. Looking at the Liberty BASIC help file they are CSn, DSn, PE and RS. CSn controls the action taken on the CTS handshaking line. n specifices how long we should wait for the device we are trying to communicate with to assert the CTS line, this is in milliseconds. The device we are communicating with may disassert this line on occasion while it is busy taking care of another task. An important note, if we set n to 0 eg. cs0, then handshaking using the CTS line is ignored, or for some connections not required. DSn which is the DSR line is used to indicate whether the device we are trying to communicate with is on line. It operates much the same as the CSn parameter except that it is a different signal. It also can be shut off by setting ds0. When we place PE within the definition it turns on parity checking, but is only valid if we have some sort of parity bit. If a parity error occurs the system will report it. Last is RS which is the RTS handshaking line. If we put RS in the definition string we will not be asserting the RTS line at all.

This may not be of a concern most of the time but you should be aware that the DTR is asserted when the comm port is open. The reason I mention this is that the DCE device which I use, uses the DTR line for a different function.

Next month in command focus we will use the print and input statement for our comm port which we have opened.

top

Taking Liberties

We can all sing the praises for our favorite form of Basic Language . But we also , too quickly , condemn the idiosyncrasies of any new dialect of Basic that we acquire or adopt .

Half the fun of programming is getting to grips with a new language , like we do , while on vacation in a foreign land .

Where Basic is concerned we get the language to tell us about itself . By trying to do something , which at its worst , would be reported to us with the message ' FATAL ERROR ' . Most of our programming endeavors will never take us to that level of ecstasy .

Some of Liberty Basic's strange ways are what allow it to interface with more than one generation of 'Windows' .

So , how do we pass thru our learning curve with Liberty Basic ?

We look , we see , and we twiddle .

How have you twiddled ?

That is what TAKING LIBERTIES is all about

What liberties have you taken to get to grips with Carl's versions of Liberty Basic ?

Please use the following program snippet which is the result of my twiddling Liberty Basic to simulate what I had done previously with Microsoft Basic 7.1 .

Can you spot where I have taken liberties ?

'Annotated on Nov 9th 2001 ............... Michael Martin

nomainwin

WindowWidth = 640
WindowHeight = 480
UpperLeftX = 1
UpperLeftY = 1

BackgroundColor\$ = "lightgray"
ForegroundColor\$ = "black"
ListboxColor\$ = "lightgray"

'should the statictext string variable overhead\$ not line up properly over
'each of the 5 columns please tweak it by using the spacebar within the
'following program code line ( while in the LB editing environment ) as
'may be appropriate , until it does line up

overhead\$ = " #### Repayment "
overhead\$ = overhead$ + " Interest Red. of Debt Balance"

redim term\$( 1500 ) : redim over$(5)

over\$(1)="####":over$(2)="Repayment":over$(3)="Interest"
over\$(4)="Red. of Debt":over$(5)="Balance"

[Begin]
rate = 12 ' range 1% to 120% ANNUAL INTEREST RATE

i = rate / 1200 ' MONTHLY INTEREST FRACTION

duration = 12 ' duration of loan in MONTHS range 1 to 1500

amount = 1200 ' amount of loan .... range \$1 to $999999999999.99

'FIND what the monthly repayment is
payfind = payfind( amount, i, duration )

'and then ADJUST to the nearest cent
payment = payfind + .005

'this sub initially creates and loads the string array TERM\$()
'for the LISTBOX in correct column-order

CALL Amortize amount, i, duration, payment

listbox #lender.mortgage, term\$(), [action1], 30 , 50 , 700 , 210

statictext #lender , overhead\$ , 30 , 30 , 700 , 20

open "Show Amortization Schedule Of Repayments" for graphics_fs _
as #lender

print #lender.mortgage , "singleclickselect"

[waitHere]
wait

' *******************************************

' help from Alyce Watson for [action1] contribution
' gratefully acknowledged

[action1]

struct point, x as short, y as short
open "user" for dll as #user

hList=hwnd(#lender.mortgage) 'listbox handle

calldll #user, "GetCursorPos",_
point as struct, ret as void

calldll #user, "ScreenToClient",_
hList as short, point as struct,_
ret as void

'need to know location of all columns
loc=point.x.struct

' *******************************************

'determines which column has been accessed by user

column=0 'reset column pointer

column=column+(loc>0)+(loc>32)+(loc>192)+(loc>352)+(loc>512)+(loc>672)

' prevents overspill by mouse into an off-data 6th column
if column=6 then column=0

close #user

'text pixel pointer
textPoint=int((loc)/8)+1

print #lender.mortgage , "selection? selected\$"
checkText= asc(mid\$(selected$,textPoint,1))

'invalidates off-data pickup by mouse
if checkText=0 then checkText=32

print #lender.mortgage , "selectionindex? index"

wtemp\$ = "selection data LOC = " + str$(loc) + " COLUMN = "
wtemp\$ = wtemp$ + str$(column) + " ASC = "
wtemp\$ = wtemp$+str$(checkText) + " CHARACTER under CURSOR = "
wtemp\$ = wtemp$ + chr$(34) + chr$(checkText) + chr$(34)

print #lender, "stringwidth? wtemp\$ width"
term\$(0)=wtemp$

print #lender.mortgage , "reload"

'display the selected column from selected\$ using temphold$

if index > 1 then
temphold\$ = word$( selected$, column ) + chr$(13) + " from month number " + str$(index-1)
end if

if checkText = 32 then temphold\$ = "OF A SPACE"

if index = 1 then completed\$ = " YOU CANNOT currently SELECT THIS LINE " + chr$(13)
if index = 1 then completed\$ = completed$ + " be a devil ---- TRY IT !!! "


if index > 1 then completed\$ =" you selected the value " + _
temphold\$+chr$(13)+"under the heading ... "+chr$(34)+over$(column)+chr$(34)

notice completed\$


goto [waitHere]

end


SUB Amortize amount, i, duration, payment

CLS : dpoint = 2

balance = int( 100 * amount ) 'BALANCE as cents

showMoney\$ = right$(space$(84) + moneyFormat$(dpoint,balance), 84)
term\$( counter ) = term$( counter ) + showMoney$

payment = int( 100 * payment ) ' MONTHLY REPAYMENT as cents

FOR payNum = 1 TO duration

showLine\$= "" : counter = payNum

'current MONTHLY INTEREST as cents
interest = int( i * balance + .5 )

'If interest exceeds payment then payment = interest + one cent
if interest >= payment then payment = interest + 1

'if this is the last payment
IF payNum = duration THEN payment = interest + balance

reductionOfLoan = payment - interest
balance = balance - reductionOfLoan

if balance < 0 then
payNum = duration
balance = balance + reductionOfLoan
payment = interest + balance
reductionOfLoan = payment - interest
balance = balance - reductionOfLoan
end if

term\$(counter) = right$(space$(4) + trim$(str$(counter)),4)

showMoney\$ = right$(space$(20) + moneyFormat$(dpoint,payment),20)
term\$( counter ) = term$( counter ) + showMoney$

showMoney\$ = right$(space$(20) + moneyFormat$(dpoint,interest),20)
term\$( counter ) = term$( counter ) + showMoney$

showMoney\$ = right$(space$(20)+moneyFormat$(dpoint,reductionOfLoan),20)
term\$(counter) = term$(counter) + showMoney$

showMoney\$ = right$(space$(20)+moneyFormat$(dpoint,balance),20)
term\$(counter) = term$(counter) + showMoney$

a = int(paynum/12)
y = paynum -(12*a):if y = 0 then y = 12
monthnum = y

NEXT payNum

END SUB


function payfind(amount, i, duration)

repaid = i * amount : payhold = 1 /( 1 + i )
paytime = payhold ^ duration : payhold = 1 - paytime
payfind = repaid / payhold

end function


function moneyFormat\$(dpoint,value)

comma\$=",":hold$=trim$(str$(value)):hlen=len(hold$):whole$="0"

zeroValue\$="0000":part$=""

if value<100 then part\$="."+right$(zeroValue$+hold$,dpoint):goto _
[complete]

whole\$=left$(hold$,hlen-dpoint):wlen=len(whole$)
part\$="."+right$(zeroValue$+hold$,dpoint):if wlen<4 then [complete]
commatest=3*(int((wlen-1)/3)):LeftLen=wlen-commatest
if LeftLen=0 then LeftLen=3

numhold\$=left$(whole$,LeftLen)
for i=LeftLen+1 to wlen step 3
numhold\$=numhold$+comma$+mid$(whole$,i,3):next i:whole$=numhold$

[complete]

'if val(whole\$)= 0 then whole$="0"
moneyFormat\$=whole$+part$

end function

end

top

Site links

http://www.libertybasic.com Liberty BASIC home page

Turkey trotAlyce's Thanksgiving game!

Game WorkshopAlso by Alyce, so you can make your own games.

http://lcsoftlb.50megs.com Liberty BASIC software from the Left Coast. Editors home site

http://lbdev.5u.com Liberty BASIC Developer home page

top

Next Month

  • Guest article
  • Command Focus: Print & Input for Comm Port

top

Feed back

All readers feed back is welcome whether its to do with this issue, future acticles or comments in general. Send your message to mailto:neiltrem@hotmail.com

Any one who wishes to submit an article for publication, please send it to the editor. mailto:neiltrem@hotmail.com

top

Legal Stuff

The Liberty BASIC Developer ezine and lbdev.5u.com are © Neil Tremblay 2001 all rights reserved.

top

 
Copyright (c) 2001 Neil Tremblay
13316