Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Thursday, February 7, 2008

BF537 performance measurements

Customized kernel image created in previous post provides a way to measure execution / performance time. It could be done with help of oscilloscope connected to the boards ground and LED connections. Application pflags-test is executed in user space of uClinux and is using GPIO driver to enable button and LEDs processing. Code below shows in comments measured with oscilloscope execution time.


    write(fd0,"0",sizeof("0"));    // 16 microseconds
    usleep(1000);                      //   4 milliseconds
    write(fd0,"1",sizeof("1"));    // 16 microseconds
    usleep(1000);                      //   4 milliseconds

Arithmetic operations could be tested with help of cycle. This will allow having sufficient amount of time to measure as shown in the code:

    long a, c, i = 0;
    for( i = 0; i < 100000; i++)
    {
         c = i + a;
    }
    printtime();

This time measurements were done with help of system time functions and results are presented in table below.

OperationCycle NumberVariable TypeTime
+100000long4 ms
+1000000long45 ms
*100000long6 ms
*1000000long48 ms
+100000float107 ms
+1000000float1061 ms
*100000float89 ms
*1000000float887 ms

Trigonometric functions measurements could be done with adding in C file #include <math.h>, and option "-lm" to the linker command. Review previous post on details of how to configure blackfin toolkit for uClinux program compilation.


bfin-uclinux-gcc -Wl,-elf2flt perftest.c -o perftest -lm

OperationCycle NumberVariable TypeTime
cos100000long6268 ms
cos1000000long62681 ms

Thursday, January 31, 2008

Compiling the Kernel for BF537

BF537 STAMP board has buttons and LEDs provided to be accessed by software for testing purpose. In order to do that is required to have customized kernel image. Default image for BF537 has no driver for such operations.

Source code for uClinux kernel could be downloaded from blackfin site. There are an easy way to uncompress it by just right click on a file in SUSE File Browser and selecting Extract Here. Lets open this folder and configure blackfin toolkit used for kernel compilation. Details on how to do that is provided in previous post.

Next command in terminal window will invoke kernel configuration utility.

make menuconfig

Choosing BF537-STAMP in Vendor/Product Selection will produce kernel for BF537. It is important to do that, otherwise kernel image will halt on boot up execution.



Ability to add required driver is provided with selection of Customize Kernel Settings (NEW):

Kernel/Library/Defaults Selection.
Device Drivers --->
Character devices --->
[*] Blackfin BF53x Programmable Flags Driver


Exit and saving configuration will bring back the terminal console. Executing next commands will reset cached objects and make a new kernel image:

make clean
make

The compilation process will take time and could last for about 30 minutes. BF537 U-Boot loader has a nice feature of loading kernel from a network over tftp. SUSE YaST in a few steps allows to configure TFTP server and then copy kernel image into server folder with File Browser.

Now let’s jump to Windows XP host environment and start HyperTerminal application.


For tftp command to work is necessary to configure BF537 U-Boot environment with ipaddress for tftp server and BF537. Saving environment settings into flash memory is an optional step. After that is loading kernel image to memory and booting uClinux.

BF537> setenv ipaddr x.y.z.n
BF537> setenv serverip x.y.z.m
BF537> saveenv
BF537> tftp 0x1000000 linux
BF537> bootelf 0x1000000

Now everything is ready to run test application on a custom kernel image. Source code for button test application could be found in user\blkfin-test\pflags-test subfolder where kernel was compiled. Check my previous post on how to compile and download application into BF537.

Wednesday, January 23, 2008

Hello World under uClinux

Let's test Hello World application compiled in previous post under uClinux. There are many ways how to copy application file into BF537 board and one of them with help of wget command by downloading file over HTTP protocol.

This command will communicate with web server installed on development platform. Ethernet connection between board and computer is necessary.

YaST allow an easy way to verify that HTTP server is enabled and take a look on my previous post on how to configure Linux SUSE to be development platform for BF537.

Then application file has to be placed into web server working folder. That could be done from command line as well by using Cut and Paste file operation.

cp ./hello /srv/www/htdocs/hello

The natural way of running BF537 under Windows XP is with use of HyperTerminal application and serial cable. Connection setting could be found on support site. After powering up board next text will be shown in terminal window:

With DHCP server available board's network settings could be configured by:

root> dhcpcd &

Next commands will do switch to tmp folder as preferable place for this application, download file from web site, permission modification that allows program to be executed and finally now is possible to execute Hello World application

root:~> cd /tmp
root:/tmp> wget http://yourwebserver/hello
root:/tmp> chmod 777 hello
root:/tmp> ./hello

Wednesday, January 16, 2008

First program for BF537 STAMP board

BF537 STAMP board is possible to buy from Digi-Key. That is a nice board with a plenty of possibilities to create a handy functionality. I just recently got one as well. My board has newer version of software that could be found on companion CD which is dated as 2005 release, but everything could be downloaded from support web site. This wiki style site looks fresh and written for creative people, check remark about documentation.


Today’s laptops or PC are quite powerful devices and capable to run multiple OS at same time by using virtualizing software. This allows of choosing Linux as development platform even if main platform is Windows XP. Check my older post on how to install SUSE 10 on Virtual PC. One of advantage of this approach is to have less hardware on a desk and more time for development.

The STAMP board is a part of the Blackfin/uClinux open source project, and the good thing that schematics for the board available as well. Board could be accessed through serial cable by using terminal window. It has an Ethernet interface, six general-purpose LEDs and four general purpose push-buttons available for quick start hardware control programming.

To be ready for development is necessary to verify number of tools to be installed on development platform. Full list of applications could be found on support site and one of them is gcc compiler. These applications are part of a standard SUSE 10 distribution. Next in a list is latest blackfin-toolchain-07r1.1-3.i386.rpm package from Blackfin support site. Double clicking an RPM file will bring up a graphical front end for installing RPM's. Under SuSE Linux 10 this front-end is provided through YaST2.



After installing the Blackfin tool chain the environment variable PATH must be modified to include the directory where the Blackfin tool chain is installed. It could be done in File Browser by selecting File->Open In Terminal and typing next command line:

export PATH=$PATH:/opt/uClinux/bfin-uclinux/bin:/opt/uClinux/bfin-linux-uclibc/bin

At this point everything is ready for a hello world application:

#include <stdio.h>

int main() {
      printf("Hello, World\n");
      return 0;
}

Next command line will compile this file:

bfin-uclinux-gcc -Wl,-elf2flt hello.c -o hello

The output executable is 'hello' file in flat format, also it creates a file “hello.gdb” which is used for debugging. Check my next post for details on how to run this program on BF537 board.

Saturday, October 27, 2007

How to improve the focus for a goal

It is very difficult to work constantly on same topic, even if you like what you are doing. You loose your focus over time. This happens most often for a developer in a multitasking environment; where you need to take care of lot of things to succeed.

The best way to trick yourself is to use a mind game. Treat every successful action as goal you score in an imaginary game. High results at the end of the day can be considered as a good accomplishment showing your victory. This will help you to increase attention to details, and help to stay focus in same way as a game player is doing during a game.

If done well it will help you focus for a lot longer. At the end of the day you count successful moves as a positive and moves you failed to do as negative. You then add them up, if the sum if positive then you win, if negative then you lose.

Friday, October 5, 2007

How to Create a Schema.ini File Programmatically

1. Start a new project in Visual Basic 6, and save project to disk
2. Add reference to Microsoft ActiveX Data Objects 2.5 Library
3. Add button to the Form
4. Double click on button and add next code

Private Sub Command1_Click()
   Dim con As New ADODB.Connection
   Dim RS As ADODB.Recordset
   con.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
   "Data Source=" & App.Path & _
   ";Extended Properties=text;"
   con.Execute & _
   "CREATE TABLE [TEST1.CSV] " & _
   "( [Name] TEXT NULL, [MaxVolt] DOUBLE NULL)"
End Sub

6. Run project and click on a button
7. Verify that SCHEMA.INI and TEST1.CSV files were created in project folder
8. Use "DROP TABLE [TEST.CSV]" to delete TEST.CSV from SCHEMA.INI and delete TEST1.CSV file from a disk

Remarks: There is no way to update SCHEMA.INI and TEST1.CSV by using ALTER TABLE sql statement. Even if tables (files) does not contain any data, next statement "ALTER TABLE [TEST.CSV] ADD COLUMN [Name2] TEXT NULL" will raise an error "Operation not supported on a table that contains data".

Tuesday, October 2, 2007

Count number of lines in a project with VBScript

'
' www.pullnews.com
' Save this code as file LineCount.vbs
'

If WScript.Arguments.Count= 0 Then
      MsgBox "Usage instruction:" & vbCrLf & _
      "Set folder as argument, or Drag source folder and drop on vbs file"
      WScript.Quit
End If
nCounter = 0
FolderName = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(FolderName) Then
    WScript.Echo "Invalid folder name"
Else
    CheckSubfolders fso.GetFolder(FolderName)
    WScript.Echo "Number of lines in all files is = " & nCounter
End If
' Subfolder recursion
Sub CheckSubfolders(thisFolder)
    Dim subFolder
    CountLinesInFolder thisFolder
    For Each subFolder In thisFolder.SubFolders
        CheckSubfolders subFolder
    Next
End Sub
Sub CountLinesInFolder(thisFolder)
    Const ForReading = 1
    Dim File, theFile
    For Each File In thisFolder.Files
        Set theFile = fso.OpenTextFile(File.Path, ForReading, False)
        Do While theFile.AtEndOfStream <> True
            theFile.ReadLine
            nCounter = nCounter + 1
        Loop
        theFile.Close
    Next
End Sub

Wednesday, September 26, 2007

Import from bin64 to binary file with VBScript

'
' www.pullnews.com
' Save this code into file ImportFromBin64.vbs
'

If WScript.Arguments.Count= 0 Then
      MsgBox "Usage instruction:" & vbCrLf & _
      "Drag source file and drop on vbs file to process"
      WScript.Quit
End If

Set fso = CreateObject("Scripting.FileSystemObject")
sInFName = WScript.Arguments(0)
sPath = fso.GetParentFolderName (WScript.ScriptFullName)
ConvertBin64ToBinary sInFName

' Convert bin64 from xml file into binary file
Sub ConvertBin64ToBinary(sInFileName)
    Set xmlDoc = CreateObject("microsoft.xmldom")
    xmlDoc.async = False
    'Load xml doc
    If xmlDoc.Load(sInFName) = False Then
        MsgBox "Invalid XML request"
    Else
        Set oNode = xmlDoc.selectSingleNode("DATA")
        sOutFName = oNode.getAttribute("FileName")
        SaveBinaryData sPath & "\" & sOutFName, _
            oNode.nodeTypedValue
    End If
End Sub

' Save binary buffer to file
Function SaveBinaryData(FileName,ByteArray)
    Const adTypeBinary = 1
    Const adSaveCreateOverWrite = 2
    'Create Stream object
    Dim BinaryStream
    Set BinaryStream = CreateObject("ADODB.Stream")
    BinaryStream.Type = adTypeBinary
    BinaryStream.Open
    'Write binary data to stream object
    BinaryStream.Write ByteArray
    'Save to file
    BinaryStream.SaveToFile FileName, adSaveCreateOverWrite
End Function

Tuesday, September 18, 2007

Convert binary file into bin64 string with VBScript

'
' www.pullnews.com
' Save this code into file ConvertToBin64.vbs
'

If WScript.Arguments.Count= 0 Then
      MsgBox "Usage instruction:" & vbCrLf & _
      "Drag source file and drop on vbs file to process"
      WScript.Quit
End If

Set fso = CreateObject("Scripting.FileSystemObject")
sInFName = WScript.Arguments(0)
sPath = fso.GetParentFolderName (WScript.ScriptFullName)
sOutFName = sPath & "\base64.xml"
SaveToXMLAsBin64 sInFName, sOutFName

' Save binary buffer into xml file in bin64 format
Sub SaveToXMLAsBin64(sInFileName, sOutFileName)
    Set xmlDoc = CreateObject("microsoft.xmldom")
    xmlDoc.async = False
    'create a node
    Set oElement = xmlDoc.createElement("DATA")
    oElement.dataType = "bin.base64"
    oElement.nodeTypedValue = ReadBinaryFile(sInFileName)
    'save file name as well
    oElement.setAttribute "FileName", fso.GetFileName( sInFName )
    xmlDoc.appendChild oElement
    'save file
    xmlDoc.save sOutFileName
End Sub

' Read binary or text file into buffer
Function ReadBinaryFile(FileName)
    Const adTypeBinary = 1
    'Create Stream object
    Dim BinaryStream
    Set BinaryStream = CreateObject("ADODB.Stream")
    'Specify stream type - we want To get binary data.
    BinaryStream.Type = adTypeBinary
    'Open the stream
    BinaryStream.Open
    'Load the file data from disk To stream object
    BinaryStream.LoadFromFile FileName
    'Open the stream And get binary data from the object
    ReadBinaryFile = BinaryStream.Read
End Function

Thursday, July 5, 2007

Send output to serial port in VBScript

'
' How To use VBScript with serial communication.
' Save this as test.vbs file
' Run by double-click
'

Dim MSComm

Set MSComm = CreateObject("MSCommLib.MSComm")
MSComm.CommPort = 2
MSComm.PortOpen = True

' send text
MSComm.Output = "otput text to send"

'send binary data
MSComm.Output = GetData(4321) & GetData(0) & _
GetData(1234) & GetData(0) & GetData(2345)

Function GetData(w)
Dim LoByte,HiByte
LoByte = w And &HFF
HiByte = (w And &HFF00&) \ &H100
GetData = ChrB(HiByte) & ChrB(LoByte)
End Function


Wednesday, June 20, 2007

How to add text in CEditView

1. CEdit::ReplaceSel

ReplaceSel replaces only a portion of the text in an edit control.
To access CEdit control, use GetEditCtrl() function.

GetEditCtrl().SetSel(-1, -1); // end of edit text
GetEditCtrl().ReplaceSel(buf); // append string..
GetEditCtrl().SendMessage(EM_SCROLLCARET); // ..and show caret

2. CWnd::SetWindowText

SetWindowText will replace all of the text, therefore first is required get all widows text into local variable, append text to the end and show on screen by using SetWindowText

CString str;
GetWindowText(str);
str += " appended string ";
SetWindowText(str);

Tuesday, May 15, 2007

How To find information in SQL Server database

1. Enumerate all columns in tables with table name like BAND

SELECT CL.* FROM INFORMATION_SCHEMA.TABLES CL WHERE TABLE_NAME LIKE '%BAND%'

2. Enumerate all columns in all tables with column name like MYCOLNAME

SELECT CL.* FROM INFORMATION_SCHEMA.COLUMNS CL WHERE column_name
LIKE '%MYCOLNAME%' ORDER BY table_name

3. Enumerate all columns in all tables with column name like MYCOLNAME, show table name as well

SELECT CL.TABLE_NAME, CL.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS CL
INNER JOIN INFORMATION_SCHEMA.TABLES TB
ON TB.TABLE_NAME = CL.TABLE_NAME
WHERE CL.COLUMN_NAME LIKE '%MYCOLNAME%'
AND TB.TABLE_TYPE = 'BASE TABLE'
ORDER BY CL.TABLE_NAME

4. Find duplicate rows in a table in SQL Server

SELECT COL1, COL2, COUNT(*)
FROM T1
GROUP BY COL1, COL2
HAVING COUNT(*) > 1

5. Enumerate processes

USE master
SELECT * FROM sysprocesses

Wednesday, April 18, 2007

excel printing

Tips for fast updates and printing in automating of Microsoft Excel

1. Use ScreenUpdating property
Application.ScreenUpdating = False
' code here
Application.ScreenUpdating = True

2. Use ADO to update xls file - is much faster than updating cell by cell

3. Use cell array - is much faster than updating cell by cell

Tuesday, April 17, 2007

Save File to msaccess mdb

MSDN site provides example how to save picture ( could be any binary data file ) into SQL Server. No example has been provided for MSAccess, this database is not designed for such services.

Other references are:

ACC: Reading, Storing, & Writing Binary Large Objects (BLOBs)
http://support.microsoft.com/kb/103257

How To Access and Modify SQL Server BLOB Data by Using the ADO Stream Object
http://support.microsoft.com/kb/258038

HOWTO: Use the Picture Box in a UserControl and in a DataRepeater Control
http://support.microsoft.com/kb/250577

Wednesday, April 11, 2007

Useful information for File operations

PRB ReadDirectoryChangesW Not Giving Consistent Notification
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q245214#appliesto

FindFirstChangeNotification May Not Notify All Processes on File Changes
http://support.microsoft.com/kb/188321/EN-US/

QuickWin - Turn a console application into a Windows program - The Code Project - Dialog and Windows
http://www.codeproject.com/dialog/quickwin.asp?df=100&forumid=1348&exp=0&select=683473

Event Logging, Part I XEventLog - Basic NT Event Logging - The Code Project - System
http://www.codeproject.com/system/xeventlog.asp