Serial port init frequency

I currently use LV to dialog with an RS232 device via the serial port.
How often does I have to re-init he serial port?
For the moment, I do it each time I want to send a string to the device.

perform a "dummy" read of the serial port and throw away the data before
sending the serial command.
that way you know the buffer is empty before you expect data.
Stu
"Zen" wrote in message
news:[email protected]..
>
>
> Johannes Niess a écrit :
>
> >
> > In theory: Once. It depends on whether you have an initialisation
> > phase or want to avoid it. If you don't need high speeds, you can
> > leave it the way it is.
>
> I send a string everery two seconds, and raed the reponse from the
> device. I just don't know if the serial buffer is emptied before
> receiving the response string. If not, there might be left old caracters
> causing a wrong response string.
Stu McFarlane
Viewpoint Systems, Inc.

Similar Messages

  • How can I define the start bit in Serial Port Init VI?

    I don't know if the number of start bits of the Serial Port Init VI match with the serial communications requirements of the device I need to communicate with.
    Is there any way of modifying this parameter?

    LabVIEW uses the standard WindowsAPI for all of its serial functions. As such, LabVIEW does not support a customizable start bit since the native serial driver does not.

  • I CAN NOT find serial port init.vi

    In labview8.6 , I CAN NOT find serial port init.vi.
    Other lots of icon can be found..... 

    Dennis Knutson wrote:
    for(imstuck) wrote:
    That's because it is called VISA Configure Serial Port. It is located in Instrument I/O->Visa->Visa->Visa Advanced-> Bus Interface Specific -> serial.
    And there it is. Sometimes you really gotta dig!
    You enjoy taking the long way there?
    Message Edited by Dennis Knutson on 05-20-2010 05:48 PM
     I just did a search of the palette and thats where it took me so thats what i posted to help the OP. Besides, sometimes the scenic route is nice. You pass lots of beautiful VIs on the way to your destination that you may have never known existed. And, I actually prefer the quick drop way .
    Message Edited by for(imstuck) on 05-20-2010 08:35 PM
    CLA, LabVIEW Versions 2010-2013

  • Reading CTS or DSR lines of Serial port

    Is there a way to read the status of CTS or DSR lines of a serial port?
    Also in what pins are these lines on standard PC?
    Ori Idan
    Helicon technologies LTD. National Instruments Alliance member in ISRAEL
    Email: [email protected]
    Home page: http://www.helicontech.co.il
    Tel: +972-6-6262353 Fax: +972-6-6262405
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Things should be made as simple as possible but not simpler
    Albert Einstein
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    On Thu, 04 May 2000 16:47:40 +0300, Ori Idan wrote:
    >Is there a way to read the status of CTS or DSR lines of a serial port?
    >Also in what pins are these lines on standard PC?
    While looking for info on printing I found the following:
    How can I control the DTR and RTS serial lines?
    Serial Port Init.vi can be used to configure the serial port for
    hardware handshaking; however, some applications may require manual
    toggling of the DTR and RTS lines. Because the interface to the
    serial ports is platform-dependent, each platform has a separate
    mechanism to control the lines.
    (Windows) The LavVIEW for Windows distribution contains a VI which you
    can use to drive the DTR and RTS serial lines. The VI serial line
    ctrl.vi, located in vi.lib\Instr\_sers
    up.llb, can be used to control
    these lines. The VI will toggle these lines according to the function
    input. Valid codes for the input are:
    0 noop
    1 clear DTR
    2 set DTR
    3 clear RTS
    4 set RTS
    5 set DTR protocol
    6 clr DTR protocol
    7 noop2
    (Macintosh) ..................
    (Sun).............................
    From LabVIEW User Manual page B-13
    Hope this helps.
    Regards,
    Steve Drake

  • Asserting the RTS signal for serial ports

    I've posted a few times, about asserting the DTR signal line for the serial
    ports.
    To start off with, i have now come to the realization that I was STUPIDLY
    trying to set the wrong thing... I needed to set the RTS, not the DTR!!!
    Most of the replies I got said to use the IN PORT and OUT PORT vi's, from
    the advanced, memory/portI/O palette.
    When i had a fiddle around with these, and looked them up in more depth, I
    found a few things...
    1. I have read a few times, that these are not portable, because of machine
    dependancy... Can anyone tell me how portable they are? Such as, are they
    fine for all Intel based architechure's, or what
    2. I found that if I initialize the serial port, using the Serial Port
    Init.vi, and then use
    the Out Port.vi, to set the RTS, by addressing the
    register at 0x2FC, for COM 2, the next thing I did, which was write to the
    serial port, hung. When I highlighted execution, it was stuck in the Serial
    Write.vi Can anybody tell me what I'm doing wrong?
    Your help would be greatly appreciated!
    Slade Squire
    Programmer
    Rectifier Technologies Pacific
    Melbourne, Australia
    [email protected]

    You should read replies to your posts more carefully since Craig Graham have
    pointed out that VI to use to assert RTS and DTR lines of a serial port. You
    also should search this group for the RS485 and RTS/DTR topic; it is a
    recurrent question and there are some pitfalls on toggling RS485 direction
    in LabVIEW.
    As for RTS flow control, you will see something only when the input buffer
    of the serial port is full, in which case RTS is asserted to signal the
    transmitter to pause transmission.
    Jean-Pierre Drolet
    "Slade Squire" a �crit dans le message de news:
    [email protected]...
    > Something else I forgot to mention....
    >
    > When I try and set RTS in the flow control parameter of Serial Port
    Init.vi,
    > it doesn't do anything!
    > Why?
    > (I know it doesn't do anything, because I have an oscilliscope set up on
    the
    > end of the com cable, wired to the RTS pin)
    >
    > "Slade Squire" wrote in message
    > news:[email protected]...
    > > I've posted a few times, about asserting the DTR signal line for the
    > serial
    > > ports.
    > > To start off with, i have now come to the realization that I was
    STUPIDLY
    > > trying to set the wrong thing... I needed to set the RTS, not the
    DTR!!!
    > >
    > > Most of the replies I got said to use the IN PORT and OUT PORT vi's,
    from
    > > the advanced, memory/portI/O palette.
    > >
    > > When i had a fiddle around with these, and looked them up in more depth,
    I
    > > found a few things...
    > >
    > > 1. I have read a few times, that these are not portable, because of
    > machine
    > > dependancy... Can anyone tell me how portable they are? Such as, are
    they
    > > fine for all Intel based architechure's, or what
    > >
    > > 2. I found that if I initialize the serial port, using the Serial Port
    > > Init.vi, and then use the Out Port.vi, to set the RTS, by addressing the
    > > register at 0x2FC, for COM 2, the next thing I did, which was write to
    the
    > > serial port, hung. When I highlighted execution, it was stuck in the
    > Serial
    > > Write.vi Can anybody tell me what I'm doing wrong?
    > >
    > > Your help would be greatly appreciated!
    > >
    > > --
    > > Slade Squire
    > > Programmer
    > > Rectifier Technologies Pacific
    > > Melbourne, Australia
    > > [email protected]
    > >
    > >
    > >
    >
    >
    LabVIEW, C'est LabVIEW

  • Multiple serial port initialisation problem

    Good Morning All
    I have attached a vi which is giving me a problem that I can't solve, and would appreciate any help.
    The vi is supposed to intialise up to 7 serial ports (only using 5 at the moment), and I'm assuming this is a plausible way to do the initialisation (could be wrong). The serial ports are connected to a pc via a usb hub. The windows XP o/s does recognise the ports according to the device manager.
    The problem is that when the vi is run the following error is reported as shown in the attached word document.
    I have compared the port settings in the device manager properties for each port to the vi settings and they match. What more can I do?
    If somebody has a setup with mutliple serial ports could they try the vi and see if it works for them?
    Thanks and best regards
    Ray
    Solved!
    Go to Solution.
    Attachments:
    ax500 serial port init.vi ‏37 KB
    init error.docx ‏518 KB

    It has nothing to do with multiple serial ports.  It has to do with an invalid setting you are trying to use to configure any one of the serial ports.
    Look at the information in the error message.  Argument 4 of the property node in Configure Serial Port VI is the Stop Bits setting.  I see a coercion dot going into that VI, so that tells me the datatype you are wiring in doesn't quite match.
    You have an array of I32 values, and your values consist of 1's.  Disconnect that array and right click on the terminal of Configure Serial Port VI and pick Create Constant.  You'll see you get a ring data type.  It is a U16.  But if you look at the items in there, you'll see that stop bits 1.0 has a value of 10.  1.5 has a value of 15, 2.0 has a value of 20.  So the value of 1 has no meaning to that property node and you get an error.  You should be wiring in a value of 10.
    Delete that array.  Create an array of the ring constants.  Turn it into a control, and choose the correct ring value for each element of your array.
    You have several other coercion dots.  They may not be causing you problems, but I would consider disconnecting them, creating a constant of the correct datatype, and using that in the array you wire to the Configure subVI.
    I modified your VI and attached it.  See if it works for you.
    Attachments:
    ax500SerialPortInitMOD.vi ‏37 KB

  • Strange init serial port issue

    Hello:
    My Labview application is reading data from the COM1..COM6 ports (I have
    added a MOXA serial board to get 4 more ports). I am using RS232 reading
    on each port (old legacy Vis, 9m long communication cables). The devices to which I am connected are weigh scale that continuously send weight readings to the Labview app through 3-wires RS232 (RD, TX and GND). Everything goes well for hours and hours. Then after a while (maybe after power is cut and restarted on the PC side?) I restart the PC and launch Labview. If I try to init the serial port that I use to connect to the weigh scale I get an error 37. I also tried to init thru HyperTerminal right after restarting the PC and could not. The only thing that works to unlock the port is
    this:
    - unplug the weigh scale communication cable from the Moxa connector
    - restart the PC
    - relaunch LV or HyperTerminal
    Unplug then restart Labview or HyperTerminal is not sufficient.
    To the same Moxa board I connect other devices such as PLC or PC through serial ports but never see any problems even after restarting the Host PC. So there is something strange with weigh scales (I tried two different brands) but what? I cannot use the built-in serial port as it is already in use by another application.
    Does someone out there have an explanation and ways to avoid this very annoying problem?
    Thank you very much, I am completely lost,
    Christophe

    Chris:
    Thank you for your help. I investigated the problem further and this is what I found. I am still clueless so if you think of other tracks that I might explore I would be glad to hear them.
    - Hard boot (power off, remove power cord, restart) does not release the port
    - I change the port ie. I used the built-in COM1 PC port, got the communication, could read char, then restarted the PC and fell into the same trap: could not init the port (Labview). I did the same after restarting and could not open the port with HyperT. Hence it is not a Moxa issue.
    - The question is: how can I resolve that, is it an HW or SW issue, a combination of the two, has it got something to deal with WIndows 2K, are there some tools that allow to diagnose whi
    ch service or application grasps the serial port during the boot sequence? Or is it a problem during the shutdown sequence that the port is not released properly?
    TIA,
    Christophe

  • Error 42 at init serial port

    I built a simple application  using LabView 7.1  using serial ports and using VISA . I finish the project and built the installer. on the development PC I test the application (from the "start" menu,  and it run correctly. when I try to insall it at another PC (after  checking  that the appropirate port is valid) I have got an error message "Error 42 occured at Init Serial Port"what could be the reason for this problem
    Haim

    I am using 7.0 but have never used 7.1. But check out this setting. It may help
    Besides which, my opinion is that Express VIs Carthage must be destroyed deleted
    (Sorry no Labview "brag list" so far)
    Attachments:
    sample.PNG ‏32 KB

  • Using a serial port under j9.. How?

    I am trying out j9 on an ipaq. I am trying to get javax.comm to work.
    When I call CommPortIdentifier.getIdentifiers ();
    I get java.lang.string.NoSuchMethodError: java/lang/String.<init>([BIII)V
    It would appear that the javax.comm package was implemented using a now deprecated String method, and that IBM has chosen not to implement deprecated methods in it's j9 vm (I get the same issue trying to run swing.)
    One would think that what is needed is an updated javax.comm package. However, there doesn't appear to be a javax.comm package on Sun's site, let alone an updated one. Whats going on here? Can someone give me an idea of how Sun and/or the JCP thinks about developers who want to use serial ports?
    Is there a workaround? A different way of talking to a serial port? Or should I abandon j9? I should add that I got my software running just fine on nsi.com's creme vm (javax.comm and swing too) and it worked without any hassles. It even understands jar files (is there a reason why IBM insists on having a link file?). However, the reason I persevered was that a) j9 is cheaper and more importantly b) nsi.com don't seem terribly keen on actually selling their product. I have lots of references to them selling their vm in bundles of 40 ($1000) which is a bit ouchy but hey I'm not paying for it. But, you'd think the nsi.com people would actually confirm this on their site?
    So.. can it be done? And why, in the world of embedded systems (my field) and now lots of phones and pdas, is so little attention given to the humble serial port? It doesn't matter how fancy the protocol is, underneath it all is a UART. grumble
    -Russel

    Hi Russel,
    I will probably soon be in the position you are in trying to get this to work. I found the following page which offers some promise.
    http://www.intrinsyc.com/support/I-Linux/405-cube/misc/smf_serial_port_access_example.htm
    Mike

  • Writing to serial port 1 from a PDA

    ok this program is driving me NUTS! i have this microchip which uses a certain protocol... now this protocol requires that you send it some characters in hexadecimal so it'll reset... afterwhich it'll send you a data packet containing the version of the microchip etc etc (it's an aduc812... which you can find on www.analog.com)... anyway, that's not important... i am having trouble actually WRITING to serial port 1... i noticed that doing it through an actual PC requires some sort of "open serial port.vi" which is not available in the pda version... all i have is init.vi which is apparently not enough from what i am told... i thas to be opened first... initialized next... then written to then read from... does anyone know how i can acc
    omplish this open procedure with the pda module? is that some sort of software i'm missing? why isn't it included with the pda module add on... etc etc... thank you in advance... i really need help with this so as much information as possible would be appreciated... let me know if you need further info...
    christina

    Hey Christina,
    Here is a link to a knowledge base one simply writing to the serial port from a PDA.
    http://sine.ni.com/apps/we/niepd_web_display.display_epd4?p_guid=E011F478861443EFE034080020E74861&p_node=%20DZ52363&p_source=External
    Hope this helps.
    Brett

  • How to access the serial port on sdk 3.1.3 ?

    Hi all,
    I know that accessing serial port is not possible on firmware 2.x for non jailbroken iPhones.
    But what about firmware 3.0?
    Apple has focused firmware 3.0 on accessories, through bluetooth or through serial port. So, accessing serial port should be possible.
    But I can't find any documentation / sample code for that.
    Would you please help me?
    Regards,
    Alx
    PS: I tried to read the port /dev/cu.iap and get this message:
    Error opening serial port /dev/cu.iap - Permission denied(13).
    Looks bad.

    Yes I am enregistred in the Mad For iPod program?
    And I try to communique with my accessorie
    So the Code
    +*// SerialPortsModuleAppDelegate.m*+
    +*// SerialPortsModule*+
    +*// Created by BPO iMac on 08/02/10.*+
    +*// Copyright _MyCompanyName_ 2010. All rights reserved.*+
    +*#import "SerialPortsModuleAppDelegate.h"*+
    +*#import <fcntl.h>*+
    +*@implementation SerialPortsModuleAppDelegate*+
    +*@synthesize window;*+
    +*- (void)applicationDidFinishLaunching:(UIApplication *)application {*+
    +*// Override point for customization after application launch*+
    +*[window makeKeyAndVisible];*+
    +* portSerie = [SerialManager alloc];*+
    +* [portSerie init];*+
    +* int nb_port;*+
    +* nb_port = [portSerie findRS232Ports];*+
    +* NSString path_port;+
    +* path_port = [NSString alloc];*+
    +* int num_port;*+
    +* if(nb_port!=0)*+
    +* {*+
    +* num_port=0;*+
    +* path_port=[portSerie pathAtIndex:num_port];*+
    +* int resultat= [portSerie openInput:path_port baudrate:9600 bits:8 parity:0 stopbits:1 flags:O_RDONLY];*+
    +* if(resultat==-1)*+
    +* {*+
    +* NSLog(@"Communication Error");*+
    +* }*+
    +* resultat= [portSerie openOutput:path_port baudrate:9600 bits:8 parity:0 stopbits:1];*+
    +* if(resultat==-1)*+
    +* {*+
    +* NSLog(@"Communication Error");*+
    +* }*+
    +* }*+
    +* [path_port release];*+
    +* *+
    +*- (void)dealloc {*+
    +*[window release];*+
    +*[super dealloc];*+
    @end
    +*// SerialPortsModuleAppDelegate.h*+
    +*// SerialPortsModule*+
    +*// Created by BPO iMac on 08/02/10.*+
    +*// Copyright _MyCompanyName_ 2010. All rights reserved.*+
    +*#import <UIKit/UIKit.h>*+
    +*#import "SerialManager.h"*+
    +*@interface SerialPortsModuleAppDelegate : NSObject <UIApplicationDelegate> {*+
    +*UIWindow window;+
    +* SerialManager portSerie;+
    +*@property (nonatomic, retain) IBOutlet UIWindow window;+
    @end
    +*// SerialManager.m*+
    +*// K3 Tools*+
    +*// Created by Kok Chen on 4/28/09.*+
    +*// Copyright 2009 Kok Chen, W7AY. All rights reserved.*+
    +*#import "SerialManager.h"*+
    +*#include <unistd.h>*+
    +*#include <termios.h>*+
    +*#include <sys/ioctl.h>*+
    +*#include <IOKit/IOKitLib.h>*+
    +*#include <IOKit/serial/IOSerialKeys.h>*+
    +*#import <fcntl.h>*+
    +*#import <UIKit/UIKit.h>*+
    +*@implementation SerialManager*+
    +*- (id)init*+
    +* self = [ super init ] ;*+
    +* if ( self ) {*+
    +* termiosBits = -1 ;*+
    +* inputfd = outputfd = -1 ;*+
    +* useTermiosThread = NO ;*+
    +* needsNotification = NO ;*+
    +* termioLock = [ [ NSLock alloc ] init ] ;*+
    +* }*+
    +* return self ;*+
    +*static int findPorts( CFStringRef *stream, CFStringRef *path, int maxDevice, CFStringRef type )*+
    +*kernreturnt kernResult ;*+
    +*machportt masterPort ;*+
    +* ioiteratort serialPortIterator ;*+
    +* ioobjectt modemService ;*+
    +*CFMutableDictionaryRef classesToMatch ;*+
    +* CFStringRef cfString ;*+
    +* int count ;*+
    +*kernResult = IOMasterPort( MACHPORTNULL, &masterPort ) ;*+
    +*if ( kernResult != KERN_SUCCESS ) return 0 ;*+
    +* *+
    +*classesToMatch = IOServiceMatching( kIOSerialBSDServiceValue ) ;*+
    +*if ( classesToMatch == NULL ) return 0 ;*+
    +* *+
    +* // get iterator for serial ports (including modems)*+
    +* CFDictionarySetValue( classesToMatch, CFSTR(kIOSerialBSDTypeKey), type ) ;*+
    +*kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, &serialPortIterator ) ;*+
    +* // walk through the iterator*+
    +* count = 0 ;*+
    +* while ( ( modemService = IOIteratorNext( serialPortIterator ) ) ) {*+
    +* if ( count >= maxDevice ) break ;*+
    +*cfString = IORegistryEntryCreateCFProperty( modemService, CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0 ) ;*+
    +*if ( cfString ) {*+
    +* stream[count] = cfString ;*+
    +* cfString = IORegistryEntryCreateCFProperty( modemService, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0 ) ;*+
    +* if ( cfString ) {*+
    +* path[count] = cfString ;*+
    +* count++ ;*+
    +* }*+
    +* }*+
    +*IOObjectRelease( modemService ) ;*+
    +* IOObjectRelease( serialPortIterator ) ;*+
    +* return count ;*+
    +*// return number of ports*+
    +*- (int)findPorts:(CFStringRef)type*+
    +* CFStringRef cstream[64], cpath[64] ;*+
    +* int i ;*+
    +* *+
    +* numberOfPorts = findPorts( cstream, cpath, 64, type ) ;*+
    +* for ( i = 0; i < numberOfPorts; i++ ) {*+
    +* stream = [ [ NSString stringWithString:(NSString*)cstream ] retain ] ;*+
    +* CFRelease( cstream ) ;*+
    +* path = [ [ NSString stringWithString:(NSString*)cpath ] retain ] ;*+
    +* CFRelease( cpath ) ;*+
    +* }*+
    +* return numberOfPorts ;*+
    +*- (int)findPorts*+
    +* return [ self findPorts:CFSTR( kIOSerialBSDAllTypes ) ] ;*+
    +*- (int)findModems*+
    +* return [ self findPorts:CFSTR( kIOSerialBSDModemType ) ] ;*+
    +*- (int)findRS232Ports*+
    +* return [ self findPorts:CFSTR( kIOSerialBSDRS232Type ) ] ;*+
    +*- (NSString)streamAtIndex:(int)n+
    +* if ( n < 0 || n >= numberOfPorts ) return nil ;*+
    +* return stream[n] ;*+
    +*- (NSString)pathAtIndex:(int)n+
    +* if ( n < 0 || n >= numberOfPorts ) return nil ;*+
    +* return path[n] ;*+
    +*// common function to open port and set up serial port parameters*+
    +*static int openPort( NSString *path, int speed, int bits, int parity, int stops, int openFlags, Boolean input )*+
    +* int fd, cflag ;*+
    +* struct termios termattr ;*+
    +* *+
    +* fd = open( [ path cStringUsingEncoding:NSASCIIStringEncoding], openFlags ) ;*+
    +* if ( fd < 0 ) return -1 ;*+
    +* *+
    +* // build other flags*+
    +* cflag = 0 ;*+
    +* cflag |= ( bits == 7 ) ? CS7 : CS8 ; // bits*+
    +* if ( parity != 0 ) {*+
    +* cflag |= PARENB ; // parity*+
    +* if ( parity == 1 ) cflag |= PARODD ;*+
    +* }*+
    +* if ( stops > 1 ) cflag |= CSTOPB ;*+
    +* *+
    +* // merge flags into termios attributes*+
    +* tcgetattr( fd, &termattr ) ;*+
    +* termattr.c_cflag &= ~( CSIZE | PARENB | PARODD | CSTOPB ) ; // clear all bits and merge in our selection*+
    +* termattr.c_cflag |= cflag ;*+
    +* *+
    +* // set speed, split speed not support on Mac OS X?*+
    +* cfsetispeed( &termattr, speed ) ;*+
    +* cfsetospeed( &termattr, speed ) ;*+
    +* // set termios*+
    +* tcsetattr( fd, TCSANOW, &termattr ) ;*+
    +* return fd ;*+
    +*- (int)openInput:(NSString*)pathname baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops flags:(int)openFlags*+
    +* return ( inputfd = openPort( pathname, speed, bits, parity, stops, openFlags, YES ) ) ;*+
    +*- (int)openInput:(NSString*)pathname baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops*+
    +* return ( inputfd = openPort( pathname, speed, bits, parity, stops, ( O_RDONLY | O_NOCTTY | O_NDELAY ), YES ) ) ;*+
    +*- (int)openOutput:(NSString*)pathname baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops flags:(int)openFlags*+
    +* return ( outputfd = openPort( pathname, speed, bits, parity, stops, openFlags, NO ) ) ;*+
    +*- (int)openOutput:(NSString*)pathname baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops*+
    +* return ( outputfd = openPort( pathname, speed, bits, parity, stops, ( O_WRONLY | O_NOCTTY | O_NDELAY ), NO ) ) ;*+
    +*- (void)closeInput*+
    +* if ( inputfd > 0 ) close( inputfd ) ;*+
    +*- (void)closeOutput*+
    +* if ( outputfd > 0 ) close( outputfd ) ;*+
    +*- (int)inputFileDescriptor*+
    +* return inputfd ;*+
    +*- (int)outputFileDescriptor*+
    +* return outputfd ;*+
    +*- (int)getTermios*+
    +* int bits ;*+
    +* *+
    +* if ( inputfd > 0 ) {*+
    +* [ termioLock lock ] ;*+
    +* ioctl( inputfd, TIOCMGET, &bits ) ;*+
    +* [ termioLock unlock ] ;*+
    +* return bits ;*+
    +* }*+
    +* return 0 ;*+
    +*- (void)setRTS:(Boolean)state*+
    +* int bits ;*+
    +* if ( inputfd > 0 ) {*+
    +* [ termioLock lock ] ;*+
    +* ioctl( inputfd, TIOCMGET, &bits ) ;*+
    +* if ( state ) bits |= TIOCM_RTS ; else bits &= ~( TIOCM_RTS ) ;*+
    +* ioctl( inputfd, TIOCMSET, &bits ) ;*+
    +* [ termioLock unlock ] ;*+
    +* }*+
    +*- (void)setDTR:(Boolean)state*+
    +* int bits ;*+
    +* if ( inputfd > 0 ) {*+
    +* [ termioLock lock ] ;*+
    +* ioctl( inputfd, TIOCMGET, &bits ) ;*+
    +* if ( state ) bits |= TIOCM_DTR ; else bits &= ~( TIOCM_DTR ) ;*+
    +* ioctl( inputfd, TIOCMSET, &bits ) ;*+
    +* [ termioLock unlock ] ;*+
    +* }*+
    +*// IO Notifications*+
    +*// prototype for delegate*+
    +*- (void)port:(NSString*)name added:(Boolean)added*+
    +* if ( delegate && [ delegate respondsToSelector:@selector(port:added:) ] ) [ delegate port:name added:added ] ;*+
    +*// this is called from deviceAdded() and deviceRemoved() callbacks*+
    +*- (void)portsChanged:(Boolean)added iterator:(ioiteratort)iterator*+
    +* ioobjectt modemService ;*+
    +* CFStringRef cfString ;*+
    +* while ( ( modemService = IOIteratorNext( iterator ) ) > 0 ) {*+
    +* cfString = IORegistryEntryCreateCFProperty( modemService, CFSTR( kIOTTYDeviceKey ), kCFAllocatorDefault, 0 ) ;*+
    +* if ( cfString ) {*+
    +* [ self port:(NSString*)cfString added:added ] ;*+
    +* CFRelease( cfString ) ;*+
    +* }*+
    +* IOObjectRelease( modemService ) ;*+
    +* }*+
    +*// callback notification when device added*+
    +*static void deviceAdded(void *refcon, ioiteratort iterator )*+
    +* ioobjectt modemService ;*+
    +* *+
    +* if ( refcon ) [ (SerialManager*)refcon portsChanged:YES iterator:iterator ] ;*+
    +* else {*+
    +* while ( modemService = IOIteratorNext( iterator ) ) IOObjectRelease( modemService ) ;*+
    +* }*+
    +*static void deviceRemoved(void *refcon, ioiteratort iterator )*+
    +* ioobjectt modemService ;*+
    +* *+
    +* if ( refcon ) [ (SerialManager*)refcon portsChanged:NO iterator:iterator ] ;*+
    +* else {*+
    +* while ( modemService = IOIteratorNext( iterator ) ) IOObjectRelease( modemService ) ;*+
    +* }*+
    +*- (void)startNotification*+
    +* CFMutableDictionaryRef matchingDict ;*+
    +* *+
    +* notifyPort = IONotificationPortCreate( kIOMasterPortDefault ) ;*+
    +* CFRunLoopAddSource( CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource( notifyPort ), kCFRunLoopDefaultMode ) ;*+
    +* matchingDict = IOServiceMatching( kIOSerialBSDServiceValue ) ;*+
    +* CFRetain( matchingDict ) ;*+
    +* CFDictionarySetValue( matchingDict, CFSTR(kIOSerialBSDTypeKey), CFSTR( kIOSerialBSDAllTypes ) ) ;*+
    +* *+
    +* IOServiceAddMatchingNotification( notifyPort, kIOFirstMatchNotification, matchingDict, deviceAdded, self, &addIterator ) ;*+
    +* deviceAdded( nil, addIterator ) ; // set up addIterator*+
    +* IOServiceAddMatchingNotification( notifyPort, kIOTerminatedNotification, matchingDict, deviceRemoved, self, &removeIterator ) ;*+
    +* deviceRemoved( nil, removeIterator ) ; // set up removeIterator*+
    +*- (void)stopNotification*+
    +* if ( addIterator ) {*+
    +* IOObjectRelease( addIterator ) ;*+
    +* addIterator = 0 ;*+
    +* }*+
    +* if ( removeIterator ) {*+
    +* IOObjectRelease( removeIterator ) ;*+
    +* removeIterator = 0 ;*+
    +* }*+
    +* if ( notifyPort ) {*+
    +* CFRunLoopRemoveSource( CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource( notifyPort ), kCFRunLoopDefaultMode ) ;*+
    +* IONotificationPortDestroy( notifyPort ) ;*+
    +* notifyPort = nil ;*+
    +* }*+
    +*// prototype for delegate or subclass*+
    +*- (void)controlFlagsChanged:(int)termbits*+
    +* if ( delegate && [ delegate respondsToSelector:@selector(controlFlagsChanged:) ] ) [ delegate controlFlagsChanged:termbits ] ;*+
    +*- (void)termiosThread*+
    +* NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init ] ;*+
    +* int termbits ;*+
    +* while ( 1 ) {*+
    +* if ( useTermiosThread == NO ) break ;*+
    +* if ( inputfd > 0 ) {*+
    +* if ( [ termioLock tryLock ] ) {*+
    +* ioctl( inputfd, TIOCMGET, &termbits ) ;*+
    +* if ( termiosBits != termbits ) [ self controlFlagsChanged:termbits ] ;*+
    +* termiosBits = termbits ;*+
    +* [ termioLock unlock ] ;*+
    +* }*+
    +* [ NSThread sleepUntilDate:[ NSDate dateWithTimeIntervalSinceNow:0.25 ] ] ;*+
    +* }*+
    +* else {*+
    +* [ NSThread sleepUntilDate:[ NSDate dateWithTimeIntervalSinceNow:1.0 ] ] ;*+
    +* }*+
    +* }*+
    +* [ pool release ] ;*+
    +*// If delegate is set, setDelegate also starts a termiosThread if delegate responds to -controlFlagsChanged:*+
    +*- (void)setDelegate:(id)object*+
    +* delegate = object ;*+
    +* if ( delegate == nil ) {*+
    +* useTermiosThread = NO ;*+
    +* if ( needsNotification ) {*+
    +* needsNotification = NO ;*+
    +* [ self stopNotification ] ;*+
    +* }*+
    +* }*+
    +* else {*+
    +* if ( [ delegate respondsToSelector:@selector(controlFlagsChanged:) ] ) {*+
    +* useTermiosThread = YES ;*+
    +* [ NSThread detachNewThreadSelector:@selector(termiosThread) toTarget:self withObject:nil ] ;*+
    +* } *+
    +* if ( [ delegate respondsToSelector:@selector(port:added:) ] ) {*+
    +* needsNotification = YES ;*+
    +* [ self startNotification ] ;*+
    +* }*+
    +* }*+
    +*- (id)delegate*+
    +* return delegate ;*+
    @end
    +*// SerialManager.h*+
    +*// K3 Tools*+
    +*// Created by Kok Chen on 4/28/09.*+
    +*// Copyright 2009 Kok Chen, W7AY. All rights reserved.*+
    +*//#import <Cocoa/Cocoa.h>*+
    +*#import <Foundation/Foundation.h>*+
    +*#import <UIKit/UIKit.h>*+
    +*#import <CoreData/CoreData.h>*+
    +*//#import <IOKit/IOKitLib.h>*+
    +*//#import <IOKitLib.h>*+
    +*#include <IOKit/IOKitLib.h>*+
    +*typedef int FileDescriptor ;*+
    +*@interface SerialManager : NSObject {*+
    +* NSLock *termioLock ;*+
    +* FileDescriptor outputfd ;*+
    +* FileDescriptor inputfd ;*+
    +* id delegate ;*+
    +* // serial ports in system*+
    +* NSString *stream[64] ;*+
    +* NSString *path[64] ;*+
    +* int numberOfPorts ;*+
    +* *+
    +* // termios*+
    +* int termiosBits ;*+
    +* Boolean useTermiosThread ;*+
    +* *+
    +* // IO notifications*+
    +* IONotificationPortRef notifyPort ;*+
    +* ioiteratort addIterator, removeIterator ;*+
    +* Boolean needsNotification ;*+
    +*- (void)setDelegate:(id)sender ;*+
    +*- (int)findPorts ;*+
    +*- (int)findModems ;*+
    +*- (int)findRS232Ports ;*+
    +*- (NSString*)streamAtIndex:(int)n ;*+
    +*- (NSString*)pathAtIndex:(int)n ;*+
    +*- (FileDescriptor)openInput:(NSString*)path baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops ;*+
    +*- (FileDescriptor)openInput:(NSString*)path baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops flags:(int)openFlags ;*+
    +*- (FileDescriptor)openOutput:(NSString*)path baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops ;*+
    +*- (FileDescriptor)openOutput:(NSString*)path baudrate:(int)speed bits:(int)bits parity:(int)parity stopbits:(int)stops flags:(int)openFlags ;*+
    +*- (void)closeInput ;*+
    +*- (void)closeOutput ;*+
    +*- (FileDescriptor)inputFileDescriptor ;*+
    +*- (FileDescriptor)outputFileDescriptor ;*+
    +*- (int)getTermios ;*+
    +*- (void)setRTS:(Boolean)state ;*+
    +*- (void)setDTR:(Boolean)state ;*+
    +*- (void)setDelegate:(id)object ;*+
    +*- (id)delegate ;*+
    +*// delegates*+
    +*- (void)port:(NSString*)name added:(Boolean)added ;*+
    +*- (void)controlFlagsChanged:(int)termbits ;*+
    @end
    Could you help me ?

  • How to detect serial port

    CommPortIdentifier portId;
              Enumeration en = CommPortIdentifier.getPortIdentifiers();
              Vector v=new Vector();
              while (en.hasMoreElements())
                   portId = (CommPortIdentifier) en.nextElement();
                   if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                             v.addElement(portId.getName());
              }

    refer this URL
    http://www.java2s.com/Code/Java/Development-Class/ReadfromaSerialportnotifyingwhendataarrives.htm
         * Project                     :
         * Class                     : GUIFrame.java
         * Purpose                    :
         * Date_Created               :
         * @ Version 1.0
    import javax.swing.JFrame;
    // import javax.swing.JPanel;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import java.awt.event.*;
    import javax.comm.*;
    import java.awt.*;
    import javax.swing.*;
    // import javax.swing.border.TitledBorder;     
    public class GUIFrame extends JFrame implements ActionListener
         JButton connectPort;
         JComboBox combo;     
         //JButton baudRate;
         //JComboBox baudRateCombo;     
         public JTextArea textArea;     
         JButton sendData;
         public SerialConnection serialConnection;
         public GUIFrame()
              setLayout(null);
              setTitle("First Frame");
              serialConnection = new SerialConnection();                    
              setJMenuBar(createMenuBar());
              combo = new JComboBox();
              combo.setBounds(50, 50, 80, 25);
              listPort();
              combo.addActionListener(this);
              connectPort = new JButton("Connect");
              connectPort.setBounds(150, 50, 100, 25);
              connectPort.addActionListener(this);
              sendData = new JButton("Send Data");
              sendData.setBounds(150, 150, 100, 25);
              sendData.addActionListener(this);
              textArea = new JTextArea();
              textArea.setBounds(300, 300, 400, 300);
              textArea.setFont(new Font("sansserif",0,18));
              add(connectPort);
              add(combo);
              add(sendData);
              add(textArea);;
              setSize(400, 300);
              setVisible(true);
              addWindowListener(new MainWindowAdapter());
         public static void main(String arg[])
              System.out.println("Hi");
              new GUIFrame();
         public JMenuBar createMenuBar()
              JMenuBar menuBar = new JMenuBar();
              JMenu fileMenu = new JMenu("File");
              JMenuItem connectMenuItem = new JMenuItem("Connect");
              connectMenuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae){
                        try{
                             if(serialConnection.portName == null){
                                  serialConnection.portName = combo.getSelectedItem().toString();
                             serialConnection.openConnection();
                        catch(Exception ex)
              JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
              disconnectMenuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae){
                        try{
                             serialConnection.closeConnection();
                        catch(Exception ex)
              fileMenu.add(connectMenuItem);
              fileMenu.add(disconnectMenuItem);
              menuBar.add(fileMenu);
              return menuBar;
         public void listPort()
              CommPortIdentifier portId;          
              java.util.Enumeration enumeration = CommPortIdentifier.getPortIdentifiers();
              while(enumeration.hasMoreElements())
                   portId = (CommPortIdentifier)enumeration.nextElement();
                   if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                        if(!portId.isCurrentlyOwned())
                             combo.addItem(portId.getName());
         public void actionPerformed(ActionEvent ae)
              if(ae.getSource() == connectPort)
                   System.out.println("Connect is clicked");     
                   try
                        if(serialConnection.portName == null)
                             serialConnection.portName = combo.getSelectedItem().toString();
                        serialConnection.openConnection();
                   catch(Exception ex)
              if(ae.getSource() == combo)
                   System.out.print("Port Name = " + combo.getSelectedItem().toString());
                   serialConnection.portName = combo.getSelectedItem().toString();
              if(ae.getSource() == sendData)
                   byte b[] = new byte[5];
                   b[0] = (byte)0xaa;
                   b[1] = (byte)0xbb;
                   b[2] = (byte)0xcc;
                   b[3] = (byte)0xdd;
                   b[4] = (byte)0xee;     
                   try
                        serialConnection.getOutputStream().write(b);
                        display(b);
                   catch(Exception ex)
         public class MainWindowAdapter extends WindowAdapter
              public void windowClosing(WindowEvent win)
                   dispose();
                   System.exit(0);
         public void display(byte[] b)
              for(int i=0; i< b.length; i++)
                   textArea.append(Integer.toHexString (b[i] & 0xff) + " ");
              textArea.append("\n");
         * Project                     :
         * Class                     : SerialConnection.java
         * Purpose                    :
         * Date_Created               :
         * @ Version 1.0
    import javax.comm.*;
    import java.io.*;
    public class SerialConnection
         private OutputStream os;
         private InputStream is;
         private CommPortIdentifier portId;
         public SerialPort sPort;
         private boolean open;
         public String portName;
         SerialConnection serialConnection;
         public SerialConnection()
              serialConnection=this;
              PortHandler portHandler = new PortHandler(serialConnection);
              portHandler.init(serialConnection);
         public void setOutputStream(OutputStream os)
              this.os=os;
         public OutputStream getOutputStream()
              return os;
         public void setInputStream(InputStream is)
              this.is=is;
         public InputStream getInputStream()
              return is;
         * A Method to open the SerialConnection
    public void openConnection() throws Exception
              try
                   portId = CommPortIdentifier.getPortIdentifier(portName);
              catch (javax.comm.NoSuchPortException e)
                   System.out.println("noPort : "+e);
              try
                   sPort = (SerialPort)portId.open("port", 3000);               
                   open = true;
              catch (javax.comm.PortInUseException e)
                   throw new Exception();
              try
                   setOutputStream(sPort.getOutputStream());
                   setInputStream(sPort.getInputStream());               
                   System.out.println("IO stream is opened");
              catch (java.io.IOException e)
                   sPort.close();                    
         *A Method to Close the port and clean up associated elements.
         public void closeConnection()
              // If port is already closed just return.
              if (!open)
                   return;
              if (sPort != null)
                   try
                        this.os.close();
                        this.is.close();
                        System.out.println("IO stream is opened - CloseConnection");
                   catch (java.io.IOException e)
                        System.err.println(e);
                   sPort.close();
                   System.out.println("Port is closed");
              System.out.println("Flag Open - 1 : " + open );
              open = false;
              System.out.println("Flag Open - 2 : " + open);
         * Send a one second break signal.
         public void sendBreak()
              sPort.sendBreak(1000);
         * Reports the open status of the port.
         * @return true if port is open, false if port is closed.
         public boolean isOpen()
              return open;
         * A Method to add the event listener to the SerialPort
         public void addEventListener(java.util.EventListener listener)throws Exception
              System.out.println("Is not in opened state");
              if(isOpen())
                   System.out.println("Is in opened state");
                   try
                        sPort.addEventListener((javax.comm.SerialPortEventListener)listener);
                   catch (java.util.TooManyListenersException e)
                        sPort.close();               
                   // Set notifyOnDataAvailable to true to allow event driven input.
                   sPort.notifyOnDataAvailable(true);
                   // Set notifyOnBreakInterrup to allow event driven break handling.
                   sPort.notifyOnBreakInterrupt(true);
                   // Set receive timeout to allow breaking out of polling loop during
                   // input handling.
                   try
                   sPort.enableReceiveTimeout(50);
                   //sPort.enableReceiveTimeout(-1);
                   catch (javax.comm.UnsupportedCommOperationException e)
                        e.printStackTrace();
                   // Add ownership listener to allow ownership event handling.
                   portId.addPortOwnershipListener((javax.comm.CommPortOwnershipListener)listener);
         import javax.comm.*;
         public class PortHandler implements SerialPortEventListener,CommPortOwnershipListener{
              public SerialConnection serialConnection;
              public PortHandler(SerialConnection serialConnection)
                   this.serialConnection=serialConnection;
                   try{
                        serialConnection.addEventListener((SerialPortEventListener)this);
                        System.out.println("New Port Handler is called");
                   catch(Exception e)
                        System.out.println("Exception PortHandler(); " +e);
                        e.printStackTrace();
                   // Add this object as an event listener for the serial port.
                   System.out.println("PortHandler is initialised...");
              public SerialConnection getConnection(){
                   return serialConnection;
              public void setSerialConnection(SerialConnection serialConnection){
                   this.serialConnection = serialConnection;
              public void init(SerialConnection serialConnection){
                   setSerialConnection(serialConnection);
              public void serialEvent(SerialPortEvent e){
                   System.out.println("Event Initialised");
                   //Determine type of event.
                   switch (e.getEventType())
                        case SerialPortEvent.DATA_AVAILABLE:
                             try{
                                  readData();                              
                             catch(java.io.IOException e1)
                                  System.out.println("IO Excep "+e1.getMessage());
                                  e1.printStackTrace();
                             catch(Exception e1)
                                  System.out.println("Exception from Serial Event "+e1.getMessage());
                                  e1.printStackTrace();
                        break;
                        case SerialPortEvent.BI:
                        break;
              public void readData() throws java.io.IOException
                   byte b[]=new byte[8500];
                   int i=0,selectOption=0;
                   int newData=0;
                   int doubleLength=0;
                   int length=0;
                   // String mid="",strLen="";
                   while (newData != -1)
                        try     
                             System.out.println("getInputStream().available() : " + serialConnection.getInputStream().available());
                             newData = serialConnection.getInputStream().read();
                             System.out.println("newData\t"+newData);
                             if (newData == -1)
                                  System.out.println("\n End of the File\n");
                                  break;
                             if(i==0){
                                  b=(byte)newData;
                                  System.out.print("\n MSg ID \t= " + Integer.toString(newData&0xff,16)+"\n----------------------------");
                                  if(b[0] == (byte)0x00)
                                       i=-1;
                                       i++;
                                       continue;
                                  i++;
                                  //System.out.println("Method is called - selectOption : " + selectOption);
                                  continue;
                             if(i==1)
                                  b[i]=(byte)newData;
                                  System.out.print("\n Length =\t"+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                  length=newData;
                                  if(length == 0)
                                       i=0;
                                       continue;
                                  i++;
                                  continue;
                             b[i]=(byte)newData;
                             if((b[0] == (byte)0x07) && (i == 2) || (b[0] == (byte)0xaf) && (i == 2) || (b[0] == (byte)0xec) && (i == 2)
                                  || (b[0] == (byte)0x5c) && (i == 2) || (b[0] == (byte)0xbe) && (i == 2) )
                                  String string = String.valueOf((byte)b[0]);
                                  String strLen = Integer.toString(b[2]&0xff,16) + Integer.toString(b[1]&0xff,16);
                                  System.out.println("\n\nLength String = " + strLen + "\n\n");
                                  java.math.BigInteger bi=new java.math.BigInteger(strLen,16);
                                  strLen = bi.toString();
                                  doubleLength = Integer.parseInt(strLen);
                                  System.out.println("\nLength int = " + doubleLength + "\n");
                                  //System.out.println("Method is called");
                             i++;
                             // Added by Siva on Jan 06
                             switch(selectOption)
                                  case 0:
                                       if(i>length+1)
                                            try
                                                 b[i]=(byte)newData;     
                                                 System.out.print("\nThe Last Byte =\t"+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                                 System.out.print("\n"+i+" i Value =\t"+Integer.toString(newData&0xff,16));
                                                 System.out.println("\n----------------------- FINISHED------------------------------");
                                                 // service(b);     
                                                 System.out.println("\n----------------------- After Service------------------------------");
                                                 i=-1;
                                                 i++;               
                                                 continue;
                                            }catch (Exception e)
                                                 System.out.println("Exception in calling service 0:"+e.getMessage());
                                                 e.printStackTrace();
                                                 b[i]=(byte)newData;
                                       System.out.print("\nMSg ID \t= "+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                       break;
                   }catch (java.io.IOException ex)     {
                        System.err.println("Abstarct Port handler Exception\t"+ex);
                   catch(Exception e1)
                        System.out.println("Exception from Read Data "+e1.getMessage());
                        e1.printStackTrace();
                   System.out.println("-----------------------------");
              public void ownershipChange(int type){
                   if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED){
              public void destroy()     
                   try{
                        serialConnection.closeConnection();     
                   }catch(Exception e){
                        System.out.println("Exception 2:"+e);     
                        e.printStackTrace();
              public void finalize(){
                   destroy();

  • How to add control buttons using Java thorugh serial port?

    Hi everyone,
    I'm new to this forum.
    I have some questions on Java and serial port.
    I want to write a Java program to control my robot, through serial port. For example, when I click "Forward", the robot will go forward, and so on.
    Now I already have the buttons, so next I would like to ask how to interface the buttons with the serial port.
    I already have all the javax.comm things installed.
    below is the code for my buttons:
    import java.awt.*;
    public class ControlButtons extends java.applet.Applet
         GridLayout myLayout = new GridLayout(3, 3);
         Button button1 = new Button(" ");
         Button buttonForward = new Button("Forward");
         Button button2 = new Button(" ");
         Button buttonLeft = new Button("Left");
         Button buttonStop = new Button("Stop");
         Button buttonRight = new Button("Right");
         Button button3 = new Button(" ");
         Button buttonReverse = new Button("Reverse");
         Button button4 = new Button(" ");
         public void init()
              setLayout(myLayout);
              add(button1);
              button1.setVisible(false);
              add(buttonForward);
              add(button2);
              button2.setVisible(false);
              add(buttonLeft);
              add(buttonStop);
              add(buttonRight);
              add(button3);
              button3.setVisible(false);
              add(buttonReverse);
              add(button4);
              button4.setVisible(false);
    }Now I would like to ask for direction on how to add in the code to make it work with serial port.
    Thanks

    The plan is, I have a robot device connected to the serial port.We don't know anything about that device. We don't know how to control it. We don't know what you have to write to the device to make it do anything. Only you know what.
    For example, when I click "Forward", the robot will go forward, and so on.So what do you have to send to make it do that? and same for the other buttons.
    Next, you need to work out from the javax.comm API how to open the serial port and send data to it. This is a standard exercise in learning a new API. You must be able to do this. Again and again.
    But the program is useless. The button can be clicked, but didn't do anything.Because (a) they have no ActionListeners and (b) there is no code to send anything to the serial port.
    You have to write all that. So you also have to look up ActionListener in the Java API and how to attach it to a button. You can do that. We all do that kind of thing every day.
    So next I would like to ask how to interface the buttons with the serial port.You've been asking nothing else since you started, but you've also only done enough investigation of your own to create the buttons. That's only the start.
    The problem is what method and command should I use to make those buttons actually functioning.See above. You've been told part of it several times. The rest only you can answer, because it's your robot.

  • Function for reading from serial port

    Hi experts,
    We are trying to read data from the serial port with the following function we got from internet.
    The problem is when creating the object with the sentence CREATE OBJECT o_obj '"MSCOMMLib.MSComm.1"'.
    This returns a sy-subrc = 2 and shows the exception NO_CREATE_OBJECT.
    We already copied the file MSCOMM32.OCX in c:\windows\system32 and we successfuly registered it, with regsvr32.exe.
    We tried it with Windows XP and Vista.
    Anybody has any idea?
    Thanks in advance
    FUNCTION ZSERIALCOM.
    ""Interfase local
    *"  IMPORTING
    *"     REFERENCE(MODE) TYPE  I DEFAULT 0
    *"     REFERENCE(COMMPORT) TYPE  I DEFAULT 1
    *"     REFERENCE(SETTINGS) TYPE  C DEFAULT '2400,N,8,1'
    *"     REFERENCE(OUTPUT) TYPE  C OPTIONAL
    *"  EXPORTING
    *"     REFERENCE(INPUT) TYPE  C
    *"  EXCEPTIONS
    *"      NO_CREATE_OBJECT
      TYPE-POOLS: sabc.
      INCLUDE ole2incl.
      PERFORM init.
      PERFORM open_port USING commport settings.
      IF mode = 0.
        PERFORM read_port
        CHANGING input.
      ENDIF.
      IF mode = 1.
        PERFORM write_port
        USING output
        CHANGING input.
      ENDIF.
      PERFORM final.
    ENDFUNCTION.
    DATA: o_obj TYPE ole2_object.
    *& Form Init
    text
    --> p1 text
    <-- p2 text
    FORM init.
    DATA:
    wa_repid LIKE sy-repid.
    wa_repid = sy-repid.
    CALL FUNCTION 'AUTHORITY_CHECK_OLE'
    EXPORTING
    program = wa_repid
    activity = sabc_act_call
    application = 'MSCOMMLib.MSComm.1'
    EXCEPTIONS
    no_authority = 1
    activity_unknown = 2
    OTHERS = 3.
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    CREATE OBJECT o_obj '"MSCOMMLib.MSComm.1"'.
    IF sy-subrc <> 0.
    RAISE no_create_object.
    ENDIF.
    ENDFORM. " Init
    FORM open_port *
    --> COMMPORT *
    --> SETTINGS *
    FORM open_port USING commport settings.
    SET PROPERTY OF o_obj 'CommPort' = commport.
    SET PROPERTY OF o_obj 'Settings' = settings.
    SET PROPERTY OF o_obj 'InputLen' = 0.
    SET PROPERTY OF o_obj 'PortOpen' = 1.
    ENDFORM. "open_port
    FORM read_port *
    --> INPUT *
    FORM read_port
    CHANGING input.
    DATA:
    wa_buffer TYPE i.
    DO 10 TIMES.
    GET PROPERTY OF o_obj 'InBufferCount' = wa_buffer.
    IF wa_buffer > 0.
    GET PROPERTY OF o_obj 'Input' = input.
    EXIT.
    ENDIF.
    ENDDO.
    ENDFORM. " read_port
    FORM write_port *
    --> OUTPUT *
    FORM write_port
    USING output
    CHANGING input.
    DATA:
    wa_buffer TYPE i.
    SET PROPERTY OF o_obj 'Output' = output.
    DO 10 TIMES.
    GET PROPERTY OF o_obj 'InBufferCount' = wa_buffer.
    IF wa_buffer > 0.
    GET PROPERTY OF o_obj 'Input' = input.
    EXIT.
    ENDIF.
    ENDDO.
    ENDFORM.
    *& Form final
    text
    --> p1 text
    <-- p2 text
    FORM final.
    SET PROPERTY OF o_obj 'PortOpen' = 0.
    FREE OBJECT o_obj.
    ENDFORM. " finalbligw

    Hi ,
    I want to read value form weigh bridge through COMM port. I have developed the FM and done the setting as mentioned in the below link
    Read COMM port using ABAP w/o third party software 
    but while executing the FM independently I am able to get the value from the COMM port,but when I call the FM from a program I am not able to get the output value from the FM.I am calling the FM from the report program.please find the code below.
    report test.
    data : lv_input TYPE c.
    CALL FUNCTION 'ZFM_WEIGHINTERFACE'
      EXPORTING
        MODE                         = 0
        COMMPORT               = 1
        SETTINGS                  = '1200,N,8,1'
        OUTPUT                     = ''
      IMPORTING
        INPUT                        = lv_input
      EXCEPTIONS
        NO_CREATE_OBJECT       = 1
        OTHERS                 = 2
    IF SY-SUBRC <> 0.
    * Implement suitable error handling here
    ENDIF.
    if I execute the FM independently the output is getting perfectly.but while calling from a program i am facing the issue..
    any suggestion is appreciated.
    Thanks
    Vivek

  • Count time between 2 readings from serial port... help!.

    Hi guys,
    I am using my application to get the readings sent by microcontroller from serial port. It works perfectly. But i have the problem, the pic uses 16bits counter, and sometimes i measure frequency lower than 15hz (65535-->16bits). Thats why I thought to measure the time between each pulse that it recieved in serial port. So i could multiply the reading about the time which spend in arrive to serial port. I know if any pulse spend more than 15hz, i should add 65535 to this reading.
    Then, the idea is count the time spent between each reading in serial port. SInce pics count and later send each turn.
    I dont know if it is possible, and exist any easy way.. Can ayone help me?.
    I would like to see any example of it, always it is possible.
    Regards, Fonsi.
    Attachments:
    capture.GIF ‏19 KB

    You're not going to be able to get even close to 1 usec resolution using the built-in time functions though I don't see any of those in your attachment. The windows clock is simply not that accurate. If you need to precisely time your serial reads you might want to look at using the timed loop. You can set the period of that to 1 msec.

Maybe you are looking for

  • Inputting technical name for varaints in portal makes it viewable to all

    Hello all, we are BI 7.0 using Portal for reporting This is the issue I am facing, when an user is trying to save a varaint for any particular query it asks for description and technical name. Now if the user only enters description and not tech name

  • Condition Record Price is not updated in Inforecord

    Dear Experts For a material , the price in the condituion record is maintained as below.But in the info record the value is showing as 14 , instead of 10 at present. Validity from      Validity to      amount 3/2/2008     3/30/2011     14 3/31/2011  

  • Report Pagination Scheme not working

    I have a report and I'm using the Select List Pagination Scheme. When I select Next or Previous, I end up with a blank page stating, no data found. I've searched all the threads and I've tried all the suggestions but I still can't get it to work. If

  • Snippets

    I have having problems with my custom snippets. I get the right click link to display but they snippets do not save. This is my entry in ide.conf file: AddVMOption -Draptor.user.snippets=h:\SQL_Dev\sqldeveloper\nkramer\snippets.xml I create a snippet

  • Data Mapper to relational database

    I've been reading the "Patterns of Enterprise Application Architecture" book and it has opened my mind to a lot of different designs. I'm trying to design a large accounting system in OO. I'm unclear on how I should design the mapping inbetween the d