Topics Collections Trending Learning Lab Open source guides. Network; Serial port. Interface to VideoLAN libvlc.dll and VCL player component for Delphi / FreePascal based on. Designed for fast 32-bit graphics handling on Delphi, Kylix and Lazarus. Library for blocking communication on serial ports. Newer versions of FPC/Lazarus may support newer MySQL client libraries. Make sure you are using the correct connection component for your client library version. So if you have the client libraries installed for MySQL 4.1 then you have to use TMySQL41Connection component, even if the server is running version 4.0 or 5.0. The reason for this is. 5dpo Component Library for Lazarus (Sdpo) provides a comport (serial port) component, an IEEE1394 camera component based on libdc1394, an UVC video driver component for webcams, a Gtk fast painting form and a Joystick component. Using ActiveXperts Serial Port Component with Delphi. ActiveXperts Serial Port Component is a software development kit (SDK) that enables the user to communicate to a device over a serial interface. Such a device can be: a weight indicator, a modem, a scanner, or any other device that is equiped with a serial port. Serial Port Component For Lazarus. 0 Comments Serial Port ActiveX Control is a powerful and versatile ActiveX component that lets you control serial ports, manage them and track their activity. It is a great alternative to complicated WinAPI for serial ports. The Serial Port and USB devices work with a serial.
NextPreviousContentsCommon serial port names are /dev/ttyS0, /dev/ttyS1, etc. Thenaround the year 2000 came the USB bus with names like /dev/ttyUSB0 and/dev/ttyACM1 (for the ACM modem on the USB bus). Multiport serialcard used somewhat differnt names (depending on the brand) such as/dev/ttyE5.
Since DOS provided for 4 serial ports on the old ISA bus:COM1-COM4, or ttyS0-ttyS3 in Linux, most serial ports on the newer PCIbus used higher numbers such as ttyS4 or ttyS14 (prior to kernel2.6.13). But since most PCs only came with one or two serial ports,ttyS0 and possibly ttyS1 (for the second port) the PCI bus can now usettyS2 (kernel 2.6.15 on). All this permits one to have both ISAserial ports and PCI serial ports on the same PC with no nameconflicts. 0-1 (or 0-3) are reserved for the old ISA bus (or thenewer LPC bus) and 2-upward (or 4-upward or 14-upward) are used forPCI, where older schemes are shown in parentheses . It's not requiredto be this way but it often is.
If you're using udev (which puts only the device you have on yourcomputer into the /dev directory at boottime) then there's an easy wayto change the device names by editing files in /etc/udev/. Forexample, to change the name of what the kernel detects as ttyS3 towhat you want to name it: ttyS14, add a line similar to this to/etc/udev/udev.rules
BUS'pci' KERNEL'ttyS3',NAME='ttyS14'
On-board serial ports on motherboards which have both PCI and ISAslots are likely to still be ISA ports. Even for all-PCI-slotmotherboards, the serial ports are often not PCI. Instead, they areeither ISA, on an internal ISA bus or on a LPC bus which is intendedfor slow legacy I/O devices: serial/parallel ports and floppy drives.
Devices in Linux have major and minor numbers. The serial portttySx (x=0,1,2, etc.) is major number 4. You can see this (and theminor numbers too) by typing: 'ls -l ttyS*' in the /dev directory. Tofind the device names for various devices, see the 'devices' file inthe kernel documentation.
There formerly was a 'cua' name for each serial port and it behavedjust a little differently. For example, ttyS2 would correspond tocua2. It was mainly used for modems. The cua major number was 5 andminor numbers started at 64. You may still have the cua devices inyour /dev directory but they are now deprecated. For details seeModem-HOWTO, section: cua Device Obsolete.
For creating the old devices in the device directory see:
Dos/Windows use the COM name while the messages from the serial driveruse ttyS00, ttyS01, etc. Older serial drivers (2001 ?) used justtty00, tty01, etc.
The tables below shows some examples of serial device names. TheIO addresses are the default addresses for the old ISA bus (not forthe newer PCI and USB buses).
For more info see the usb subdirectory in the kernel documentationdirectory for files: usb-serial, acm, etc.
On some installations, two extra devices will be created,/dev/modem
for your modem and /dev/mouse
for amouse. Both of these are symbolic links to the appropriatedevice in /dev
.
Historical note: Formerly (in the 1990s) the use of/dev/modem
(as a link to the modem's serial port) wasdiscouraged since lock files might not realize that it was really say/dev/ttyS2
. The newer lock file system doesn't fall intothis trap so it's now OK to use such links.
Inspect the connectors
Inspecting the connectors may give some clues but is often notdefinitive. The serial connectors on the back side of a PC areusually DB connectors with male pins. 9-pin is the most common butsome are 25-pin (especially older PCs like 486s). There may be one9-pin (perhaps ttyS0 ??) and one 25-pin (perhaps ttyS1 ??). For two9-pin ones the top one might be ttyS0.
If you only have one serial port connector on the back of your PC,this may be easy. If you also have an internal modem, a program likewvdial may be able to tell you what port it's on (unless it's a PnPthat hasn't been enabled yet). A report from setserial (atboot-time or run by you from the command line) should help youidentify the non-modem ports.
If you have two serial ports it may be more difficult. You could haveonly one serial connector but actually have 2 ports, one of whichisn't used (but it's still there electronically). First check manuals(if any) for your computer. Look at the connectors for meaningfullabels. You might even want to take off the PC's cover and see ifthere are any meaningful labels on the card where the internal ribbonserial cables plug in. Labels (if any) are likely to say something like'serial 1', 'serial 2' or A, B. Which com port it actually is willdepend on jumper or PnP settings (sometimes shown in a BIOS setupmenu). But 1 or A are more likely to be ttyS0 with 2 or B ttyS1.
Send bytes to the port
Labels are not apt to be definitive so here's another method. Ifthe serial ports have been configured correctly per setserial, thenyou may send some bytes out a port and try to detect which connector(if any) they are coming out of. One way to send such a signal is tocopy a long text file to the port using a command like: cpmy_file_name /dev/ttyS1. A voltmeter connected to the DTR pin (seeSerial-HOWTO for Pinout) will display a positive voltage as soon asyou give the copy command.
The transmit pin should go from several volts negative to a voltagefluctuating around zero after you start sending the bytes. If it doesn't(but the DTR went positive) then you've got the right port but it'sblocked from sending. This may be due to a wrong IRQ, -clocal beingset, etc. The command 'stty -F /dev/ttyS1 -a
' should showclocal (and not -clocal). If not, change it to clocal.
Another test is to jumper the transmit and receive pins (pins 2 and 3of either the 25-pin or 9-pin connector) of a test serial port. Thensend something to each port (from the PCs keyboard) and see if it getssent back. If it does it's likely the port with the jumper on it.Then remove the jumper and verify that nothing gets sent back. Notethat if 'echo' is set (per stty) then a jumper creates an infiniteloop. Bytes that pass thru the jumper go into the port and come rightback out of the other pin back to the jumper. Then they go back inand out again and again. Whatever you send to the port repeats itselfforever (until you interrupt it by removing the jumper, etc.). Thismay be a good way to test it as the repeating test messages halt whenthe jumper is removed.
As a jumper you could use a mini (or micro) jumper cable (sold in someelectronic parts stores) with mini alligator clips. A small scrap ofpaper may be used to prevent the mini clips from making electricalcontact where it shouldn't. Metal paper clips can sometimes be bentto use as jumpers. Whatever you use as a jumper take care not to bendor excessively scratch the pins. To receive something from a port,you can go to a virtual terminal (for example Alt-F2 and login) andtype something like 'cp /dev/ttyS2 /dev/tty'. Then at another virtualterminal you may send something to ttyS2 (or whatever) by 'echotest_message > /dev/ttyS2'. Then go back to the receive virtualterminal and look for the test_message. See Serial Electrical Test Equipment for more info.
Connect a device to the connector
Another way to try to identify a serial port is to connect somephysical serial device to it and see if it works. But a problem hereis that it might not work because it's not configured right. A serialmouse might get detected at boot-time if connected.
You may put a device, such as a serial mouse (use 1200 baud), on a portand then use minicom or picocom to communicate with that port. Thenby clicking on the mouse, or otherwise sending characters with thedevice, see if they get displayed. It not you may have told picocomthe wrong port (such as ttyS0 instead of ttyS1) so try again.
Missing connectors
If the software shows that you have more serial ports than youhave connectors for (including an internal modem which counts as aserial port) then you may have a serial port that has no connector.Some motherboards come with a serial port with no cable or externalserial DB connector. Someone may build a PC from this and decide notto use this serial port. There may be a 'serial' connector and labelon the motherboard but no ribbon cable connects to its pins. To usethis port you must get a ribbon cable and connector. I've seendifferent wiring arrangements for such ribbon cables so beware.
If you don't use devfs (which automatically creates such devices) anddon't have a device 'file' that you need, you will have to create it.Use the mknod
command or with the MAKEDEV shell script.Example, suppose you needed to create ttyS0
:
ttyS0
you would just type:If the above command doesn't work (and you are the root user), lookfor the MAKEDEV script in the /dev directory and run it.
This handles the devices creation and should set the correct permissions.For making multiport devices see Making multiport devices in the /dev directory.
NextPreviousContents│English (en) │ español (es) │ français (fr) │
Databases portal |
References: Tutorials/practical articles: Databases
|
- 4SQLDB tutorials and example code
- 4.3Connecting to MySQL from a Lazarus Application
- 7MySQL package: the low level units
Overview
You can use Free Pascal/Lazarus to access a MySQL database server. Also you can use MySQL Data access components (MyDAC) as a Lazarus component to connect Lazarus and MySQL. Lazarus components MyDAC are free to download.
Win64: please see warning here on not using certain FPC/Lazarus Win64 versions.
Advantages of MySQL:
- It is very widely used and available
- Though older versions had a deserved reputation of not being true RDBMSes, newer versions support ACID properties if properly set up (with the right storage backend)
Disadvantages of MySQL:
- The MySQL maintainers break binary compatibility between client library versions. This means that an FPC/Lazarus translation needs to be made for each new version, which slows things down.
- The license may be restrictive to some users (e.g. in commercial deployments). There are compatible, possibly less restrictive alternatives like MariaDB.
A lot of Lazarus/FPC users prefer Firebird or PostgreSQL databases for this reason.
MySQL licensing
Before a significant MySQL deployment, don't forget to read its license.
SQLDB
Lazarus 1.2 (with FPC 2.6.2), supports
- MySQL 4.0 client library
- MySQL 4.1 client library
- MySQL 5.0 client library
- MySQL 5.1 client library
- MySQL 5.5 client library (supported since Lazarus 1.0.8)
- MySQL 5.6 client library (supported since Lazarus )
Newer versions of FPC/Lazarus may support newer MySQL client libraries.
Make sure you are using the correct connection component for your client library version. So if you have the client libraries installed for MySQL 4.1 then you have to use TMySQL41Connection component, even if the server is running version 4.0 or 5.0. The reason for this is that MySQL client libraries often break compatibility of their API so each version needs a different Pascal driver.
On *nix systems, the SQLDB code may look for the plain version of the library without version number suffixes. There are several ways you can deal with this:
- (on many Linuxes) installing the -dev version of the library
- symlinking your specific library name to the one FPC is looking for (rather hackish)
- use TSQLDBLibraryLoader to specify the library name before loading the connection
SQLDB tutorials and example code
BigChimp September 2012: note: a lot of this is duplicate code and could be consolidated. I propose to move as much as possible to the GUI-oriented SQLDB Tutorial1 and create a separate page FPC database tutorial to create a text mode sample
Get MySQL working in Linux or Windows
Follow the instructions in the MySQL User Manual. Make sure that the mysqld daemon runs reliably, and that all potential users (including root, mysql, yourself and anybody else that may need it) have as many privileges as they need, from as many hosts as may be needed (such as 'localhost', the local host's name, and other hosts on your network) as far as is consistent with security. It is preferable that all users including root have passwords. Test the action of the database system using the examples given in the manual, and check that all users really do have reliable access.
Get MySQL working for FPC in text mode
There is a directory with an example program in $(fpcsrcdir)/packages/base/mysql/. You can find the fpc source directory in Lazarus: Tools -> Options -> Files -> FPC source directory. Possible paths for the mysql directory are /usr/share/fpcsrc/packages/base/mysql/ (rpm install) or C:lazarusfpcsrcpackagesbasemysql (windows). This directory also contains the units mysql.pp, mysql_com.pp and mysql_version.pp. Before running the test script, you need to create a database called testdb: do this by logging into the mysql monitor (as root with full privileges) and issuing the following SQL statement
then make sure that all relevant users have appropriate access privileges to it
There is a script called mkdb which you should now try to run:
This will probably fail, as the system will not allow an anonymous user to access the database. So change the script using an editor so that the line invoking mysql reads:
and try running it again, entering your password when prompted. With luck you might have managed to create the test database: test it (while logged in to the mysql monitor) by issuing the mysql statement
You should see a table listing the ID, username and email address of some of the FPC developers.
Now try to run the test program testdb.pp (this may need to be compiled, and will almost certainly fail on the first attempt!!).
I found that the program could not connect to mysql for several reasons:
- My system (SuSE Linux v9.0) installs mysql v4.0.15, not the version3 for which the package was designed.
- The program needs to have user names and passwords to get access to the database.
- The compiler needs to know where to find the mysql libraries (IF YOU HAVEN'T INSTALLED THE MYSQL DEVELOPMENT LIBRARIES, DO SO NOW!)
I created a copy of testdb.pp called trydb.pp, rather than editing the original - this means that the original files still get fixed in subsequent CVS updates.I also copied the files found in the subdirectory mysql/ver40/ into the main mysql/ subdirectory, renaming them mysql_v4.pp, mysql_com_v4.pp and mysql_version_v4.pp, being sure to rename the units within each file correspondingly. I changed the uses statement in trydb.pp to
and the statement in mysql_v4.pp to
I added a line to /etc/fpc.cfg to point to my libraries:
The following step might not be necessary if the devel-libraries are installed as the links will be created for you, but it never hurts to check.I had to find the real name of the mysqlclint library in the /usr/lib directory and in my case I had to issue the shell command:
to make a symbolic link allowing FPC to find the library. For good measure I also created the link
and placed similar links in various other directories: not strictly necessary, but just in case ..!Some users might need to add the following link:
I modified trydb.pp to include user details, initially by adding host, user and password as constants:
Warning: This section looks extremely outdated. If you are still on MySQL 4 perhaps it is time to upgrade
I also found that I couldn't connect to mysql using the mysql_connect() call, but had to use mysql_real_connect() which has many more parameters. To complicate things further, the number of parameters seems to have changed between version3 (where there are seven) and version4 (where there are eight). Before using mysql_real_connect I had to use mysql_init() which is not found in the original mysql.pp but is found in mysql_v4.pp.
So the code for connection to the database is now:
Now - ready to start compiling trydb.pp?
success! Now run it:
whoopee! I got the listing of the FPC developers!
A few extra refinements: make the entry of user details and the mysql commands interactive, using variables rather than constants, and allow several SQL commands to be entered, until we issue the quit command: see the full program listing, where user details are entered from the console, and the program goes into a loop where SQL commands are entered from the console (without the terminal semicolon) and the responses are printed out, until 'quit' is entered from the keyboard.
See Sample Console Listing.
Connecting to MySQL from a Lazarus Application
This tutorial shows how to connect Lazarus to the MySQL database, and execute simple queries, using only the basic Lazarus components; it uses no Data Aware components, but illustrates the principles of interfacing with the database.
Lazarus Examples
Create a new project in Lazarus:
A new automatically generated Form will appear.
Enlarge the form to fill about half of the screen, then re-name the form and its caption to 'TryMySQL'.
From the Standard Component tab place three Edit Boxes on the upper left side of the Form, and immediately above each box place a label. Change the names and captions to 'Host' (and HostLLabel,HostEdit), 'UserName' (and UserLabel, UserEdit) and 'Password' (with PasswdLabel and PasswdEdit). Alternatively you could use LabelledEdit components from the Additional tab.
Select the Passwd Edit box and find the PasswordChar property: change this to * or some other character, so that when you type in a password the characters do not appear on your screen but are echoed by a series of *s. Make sure that the Text property of each edit box is blank.
Now place another Edit box and label at the top of the right side of your form. Change the label to 'Enter SQL Command' and name it CommandEdit.
Place three Buttons on the form: two on the left under the Edit boxes, and one on the right under the command box.
Label the buttons on the left 'Connect to Database' (ConnectButton)and 'Exit' (ExitButton) and the one on the right 'Send Query' (QueryButton).
Place a large Memo Box labelled and named 'Results' (ResultMemo) on the lower right, to fill most of the available space. Find its ScrollBars property and select ssAutoBoth so that scroll bars appear automatically if text fills the space. Make the WordWrap property True.
Place a Status Bar (from the Common Controls tab) at the bottom of the Form, and make its SimpleText property 'TryMySQL'.
A screenshot of the Form can be seen here: Mysql Example Screenshot
Now we need to write some event handlers.
J edit download for macmadeprogram. The three Edit boxes on the left are for entry of hostname, username and password. When these have been entered satisfactorily, the Connect Button is clicked. The OnCLick event handler for this button is based on part of the text-mode FPC program above.
The responses from the database should be converted into strings and displayed in the Memo box. Text mode Pascal write and writeln statements are capable of performing a lot of type conversion 'on the fly', but the use of a memo box for text output requires explicit conversion of data types to the correct string: so Pchar variables have to be converted to strings using StrPas, and integers have to be converted with IntToStr.
Strings are displayed in the Memo box using:
The ConnectButton event handler thus becomes:
The Text Box on the right allows entry of a SQL statement, without a terminal semicolon; when you are satisfied with its content or syntax, the SendQuery button is pressed, and the query is processed, with results being written in the ResultsMemo box.
The SendQuery event handler is again based on the FPC text-mode version, except that once again explicit type-conversion has to be done before strings are displayed in the box.
A difference from the text-mode FPC program is that if an error condition is detected, the program does not halt and MySQL is not closed; instead, control is returned to the main form and an opportunity is given to correct the entry before the command is re-submitted. The application finally exits (with closure of MySQL) when the Exit Button is clicked.
The code for SendQuery follows:
Save your Project, and press Run -> Run
Download example source code
Warning: Current versions of Lazarus/FPC require committing all MySQL transactions. This was not necessary in earlier versions. The code download likely will not work until it is updated.
A full listing of the program is available here Sample Source Code
Lazarus For Windows
Lazarus, MySQL and UTF-8
The following step might not be necessary if the devel-libraries are installed as the links will be created for you, but it never hurts to check.I had to find the real name of the mysqlclint library in the /usr/lib directory and in my case I had to issue the shell command:
to make a symbolic link allowing FPC to find the library. For good measure I also created the link
and placed similar links in various other directories: not strictly necessary, but just in case ..!Some users might need to add the following link:
I modified trydb.pp to include user details, initially by adding host, user and password as constants:
Warning: This section looks extremely outdated. If you are still on MySQL 4 perhaps it is time to upgrade
I also found that I couldn't connect to mysql using the mysql_connect() call, but had to use mysql_real_connect() which has many more parameters. To complicate things further, the number of parameters seems to have changed between version3 (where there are seven) and version4 (where there are eight). Before using mysql_real_connect I had to use mysql_init() which is not found in the original mysql.pp but is found in mysql_v4.pp.
So the code for connection to the database is now:
Now - ready to start compiling trydb.pp?
success! Now run it:
whoopee! I got the listing of the FPC developers!
A few extra refinements: make the entry of user details and the mysql commands interactive, using variables rather than constants, and allow several SQL commands to be entered, until we issue the quit command: see the full program listing, where user details are entered from the console, and the program goes into a loop where SQL commands are entered from the console (without the terminal semicolon) and the responses are printed out, until 'quit' is entered from the keyboard.
See Sample Console Listing.
Connecting to MySQL from a Lazarus Application
This tutorial shows how to connect Lazarus to the MySQL database, and execute simple queries, using only the basic Lazarus components; it uses no Data Aware components, but illustrates the principles of interfacing with the database.
Lazarus Examples
Create a new project in Lazarus:
A new automatically generated Form will appear.
Enlarge the form to fill about half of the screen, then re-name the form and its caption to 'TryMySQL'.
From the Standard Component tab place three Edit Boxes on the upper left side of the Form, and immediately above each box place a label. Change the names and captions to 'Host' (and HostLLabel,HostEdit), 'UserName' (and UserLabel, UserEdit) and 'Password' (with PasswdLabel and PasswdEdit). Alternatively you could use LabelledEdit components from the Additional tab.
Select the Passwd Edit box and find the PasswordChar property: change this to * or some other character, so that when you type in a password the characters do not appear on your screen but are echoed by a series of *s. Make sure that the Text property of each edit box is blank.
Now place another Edit box and label at the top of the right side of your form. Change the label to 'Enter SQL Command' and name it CommandEdit.
Place three Buttons on the form: two on the left under the Edit boxes, and one on the right under the command box.
Label the buttons on the left 'Connect to Database' (ConnectButton)and 'Exit' (ExitButton) and the one on the right 'Send Query' (QueryButton).
Place a large Memo Box labelled and named 'Results' (ResultMemo) on the lower right, to fill most of the available space. Find its ScrollBars property and select ssAutoBoth so that scroll bars appear automatically if text fills the space. Make the WordWrap property True.
Place a Status Bar (from the Common Controls tab) at the bottom of the Form, and make its SimpleText property 'TryMySQL'.
A screenshot of the Form can be seen here: Mysql Example Screenshot
Now we need to write some event handlers.
J edit download for macmadeprogram. The three Edit boxes on the left are for entry of hostname, username and password. When these have been entered satisfactorily, the Connect Button is clicked. The OnCLick event handler for this button is based on part of the text-mode FPC program above.
The responses from the database should be converted into strings and displayed in the Memo box. Text mode Pascal write and writeln statements are capable of performing a lot of type conversion 'on the fly', but the use of a memo box for text output requires explicit conversion of data types to the correct string: so Pchar variables have to be converted to strings using StrPas, and integers have to be converted with IntToStr.
Strings are displayed in the Memo box using:
The ConnectButton event handler thus becomes:
The Text Box on the right allows entry of a SQL statement, without a terminal semicolon; when you are satisfied with its content or syntax, the SendQuery button is pressed, and the query is processed, with results being written in the ResultsMemo box.
The SendQuery event handler is again based on the FPC text-mode version, except that once again explicit type-conversion has to be done before strings are displayed in the box.
A difference from the text-mode FPC program is that if an error condition is detected, the program does not halt and MySQL is not closed; instead, control is returned to the main form and an opportunity is given to correct the entry before the command is re-submitted. The application finally exits (with closure of MySQL) when the Exit Button is clicked.
The code for SendQuery follows:
Save your Project, and press Run -> Run
Download example source code
Warning: Current versions of Lazarus/FPC require committing all MySQL transactions. This was not necessary in earlier versions. The code download likely will not work until it is updated.
A full listing of the program is available here Sample Source Code
Lazarus For Windows
Lazarus, MySQL and UTF-8
The following may be required for other codepages/character sets as well
UTF-8 Unicode is a convenient multibyte character set encoding, that allows working with multilingual texts without requiring WideStrings. It is supported both by Lazarus SQLdb components and by MySQL since version 4.1 by choosing the appropriate character set.
However, simply setting this encoding as default for
- your tables and
- the MySQL connection component (e.g.
TMySQL51Connection.CharSet:='UTF8';
)
will result in incorrect storage and retrieval of UTF-8 strings: any accented/international character will show up as question mark (?). Apparently, the reason for this is that MySQL client library is compiled to expect Latin1 character set by default.
In order to enable proper communication between Lazarus, MySQL client library and MySQL server, additional two queries need to be executed each time a connection to the database is established:
and
The first query will ensure your application receives strings in correct encoding, and the second tells MySQL not to convert strings it receives from your application.
Simple MySQL Demo Using the TMySQL5xConnection Component
Here is code that functions as a quick demo to get up and running simply. As with all SQLDB components, make sure the database client library is in the correct place:
- on Windows: the DLL, e.g. libmysql.dll is put in the project output directory (where the executable is generated). Alternatively, you could also place it in your Windows/system32 directory
- on Linux/OSX: install the mysql client library in your path (e.g. using your distribution's package manager)
When distributing your application, make sure the proper MySQL client library is present on your user's computer. As this can be a problem, perhaps using a different database engine may make more sense.
Code-driven sample
The example below uses code to fill your controls with data. You can also use