EzDevInfo.com

serial-port interview questions

Top serial-port frequently asked interview questions

What is the difference between DTR/DSR and RTS/CTS flow control?

What's the difference between DTR/DSR and RTS/CTS hardware flow control? When is each one used? Why do we need more than one kind of hardware flow control? :)


Source: (StackOverflow)

Sysinternals' Portmon: Error 2

When I try to connect to local ports, Computer -> Connect local, using Portmon v. 3.02, I'm getting an error message, Error 2, in a small error dialog box:

Enter image description here

I run the tool as an administrator (if not, I get error 6).

By the way this is a Windows 7 x64. On 32-bit, in Windows 7 x86, it works fine. How can I fix this problem?


Source: (StackOverflow)

Advertisements

Issue reading smart card

I have reader which has doc almost exact as this one: http://www.jinmuyu.com/download/JMY680A_EN.pdf main difference being, my reader claims it supports also TYPE B cards.

I have three ISO 14443 cards, which I test consecutively, and following code:

   byte[] rs = null;

   Thread.Sleep(500);

   // Set module Idle 
   Random r = new Random();
   byte rInt = (byte) r.Next(0, 255);
   rs = send(new byte[] { 0x12, rInt });
   if (rs[1] == 0xED)
       throw new Exception("Failed set idle");

   Thread.Sleep(500);

   //// Request B
   //rs = send(new byte[] { 0x60, 0x00, 0x00 });
   //if (rs[1] == 0x9F)
   //    throw new Exception("Failed card requestB"); 

   // RequestA
   rs = send(new byte[] { 0x20, 0x00 });
   if (rs[1] == 0xDF)
       throw new Exception("Failed card requestA");

    // Reset cardA
    rs = send(new byte[] { 0x30 });
    if(rs[1] == 0xCF)
        throw new Exception("Failed card reset");

     // Do other work, Send some APDU to card, etc.
     // ........


     // Exit program

Most of the time, this code works well with all three cards. However, sometimes, when I bring one of the card near reader, the Card Request A (RequestA call) call fails. It will then always fail with this card, until I bring a new card to the reader. Does anyone have any idea what can be causing this? Maybe I need some delays between calls? Or need to call some other (ISO14443 related) function before calling RequestA?

send is method implemented using SerialPort class. In the following way:

  1. On each invocation of send, new SerialPort object is created
  2. Call Open on object created above
  3. Write and Read some data
  4. Close the connection using Close on object which was created in this method instance

btw. this is successful response from one of the cards (on which reader failed once) on RequestA command:

ID                 | ATQ     | SAK
0xe1 0x8f 0x68 0xe6 0x04 0x00 0x28

Source: (StackOverflow)

Java Serial Communication on Windows

I've been looking around for a Java API that can communicate with serial devices on Windows/Win32 but many of the APIs I've checked out are either for Linux, too outdated, or just had bad critics.

Can someone recommend one to me that they've tried or knows about that is easy to implement on Windows XP?


Source: (StackOverflow)

PuTTY Serial Communication

I am trying to use PuTTY to communicate over my computer's serial line. I have configured the correct serial line, baud rate, number of data bits, stop bits, parity, and flow control, and established the connection. When I click OK to open the connection, I am shown a black screen and each of my key presses are sent without being shown on the screen (the window remains black). How do I configure PuTTY so that it only sends my commands or opcodes after I press enter?

I have used PuTTY while at college for Telnet / SSH and it always showed my commands and input them only after I pressed the enter key, so I am a bit confused.

Thanks for the help in advance!


Source: (StackOverflow)

What is the cross-platform method of enumerating serial ports in Python (including virtual ports)?

Note: I'm using Python 2.7, and pySerial for serial communications.

I found this article which lists two ways: http://www.zaber.com/wiki/Software/Python#Displaying_a_list_of_available_serial_ports

This method works on Windows and Linux, but sometimes misses virtual ports on Linux:

import serial

def scan():
   # scan for available ports. return a list of tuples (num, name)
   available = []
   for i in range(256):
       try:
           s = serial.Serial(i)
           available.append( (i, s.portstr))
           s.close()
       except serial.SerialException:
           pass
   return available

print "Found ports:"
for n,s in scan(): print "(%d) %s" % (n,s)

And this one that only works on Linux, but includes virtual ports:

import serial, glob

def scan():
   # scan for available ports. return a list of device names.
   return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')

print "Found ports:"
for name in scan(): print name

I suppose I could do platform detection to use the second method (the one that includes virtual ports) when running on Linux, and the first method when running Windows, but what about Mac?

How should I enumerate serial ports (virtual too) regardless of platform?

Edit

I found a few pertinent questions:


Source: (StackOverflow)

A good serial communications protocol/stack for embedded devices?

After writing several different custom serial protocols for various projects, I've started to become frustrated with re-inventing the wheel every time. In lieu of continuing to develop custom solutions for every project, I've been searching for a more general solution. I was wondering if anyone knows of a serial protocol (or better yet, implementation) that meets the following requirements:

  • Support multiple devices. We'd like to be able to support an RS485 bus.
  • Guaranteed delivery. Some sort of acknowledgement mechanism, and some simple error detection (CRC16 is probably fine).
  • Not master/slave. Ideally the slave(s) would be able to send data asynchronously. This is mostly just for aesthetic reasons, the concept of polling each slave doesn't feel right to me.
  • OS independence. Ideally it wouldn't rely on a preemptive multitasking environment at all. I'm willing to concede this if I can get the other stuff.
  • ANSI C. We need to be able to compile it for several different architectures.

Speed isn't too much of an issue, we're willing to give up some speed in order to meet some of those other needs. We would, however, like to minimize the amount of required resources.

I'm about to start implementing a sliding window protocol with piggybacked ACKs and without selective repeat, but thought that perhaps someone could save me the trouble. Does anyone know of an existing project that I could leverage? Or perhaps a better strategy?

UPDATE
I have seriously considered a TCP/IP implementation, but was really hoping for something more lightweight. Many of the features of TCP/IP are overkill for what I'm trying to do. I'm willing to accept (begrudgingly) that perhaps the features I want just aren't included in lighter protocols.

UPDATE 2
Thanks for the tips on CAN. I have looked at it in the past and will probably use it in the future. I'd really like the library to handle the acknowledgements, buffering, retries etc, though. I guess I'm more looking for a network/transport layer instead of a datalink/physical layer.

UPDATE 3
So it sounds like the state of the art in this area is:

  • A trimmed down TCP/IP stack. Probably starting with something like lwIP or uIP.
  • A CAN based implementation, it would probably rely heavily on the CAN bus, so it wouldn't be useful on other physical layers. Something like CAN Festival could help along the way.
  • An HDLC or SDLC implementation (like this one). This is probably the route we'll take.

Please feel free to post more answers if you come across this question.


Source: (StackOverflow)

How to connect to a terminal to Serial-USB device on Ubuntu 10.10?

I am trying to connect minicom to a serial device that is connected via a USB to Serial adapter. This is a PL2303 and from everything I've read no additional drivers are required. The device is recognised as a PL2303.

I'm a beginner at minicom. Is this the correct command to execute? Or do I need to configure something?

$ sudo minicom --device /dev/ttyUSB0
minicom: cannot open /dev/ttyUSB0: No such file or directory

$ sudo lsusb -v

Bus 002 Device 006: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port
Device Descriptor:
  bLength                18
  bDescriptorType         1

$ tail /var/log/syslog  #then removed and attached the device.
Mar 13 23:31:49 ubuntu kernel: [807996.786805] usb 2-1: pl2303 converter now attached to ttyUSB0
Mar 13 23:34:44 ubuntu kernel: [808172.155129] usb 2-1: USB disconnect, address 7
Mar 13 23:34:44 ubuntu kernel: [808172.156321] pl2303 ttyUSB0: pl2303 converter now disconnected from ttyUSB0
Mar 13 23:34:44 ubuntu kernel: [808172.156374] pl2303 2-1:1.0: device disconnected
Mar 13 23:34:52 ubuntu kernel: [808179.497856] usb 2-1: new full speed USB device using uhci_hcd and address 8
Mar 13 23:34:52 ubuntu kernel: [808179.785845] pl2303 2-1:1.0: pl2303 converter detected
Mar 13 23:34:52 ubuntu kernel: [808179.872309] usb 2-1: pl2303 converter now attached to ttyUSB0

Source: (StackOverflow)

How do I get a list of available serial ports in Win32?

I have some legacy code that provides a list of the available COM ports on the PC by calling the EnumPorts() function and then filtering for the port names that start with "COM".

For testing purposes it would be very useful if I could use this code with something like com0com, which provides pairs of virtual COM ports looped together as a null-modem.

However the com0com ports are not found by the EnumPorts() function (even without filtering for "COM"). HyperTerminal and SysInternals PortMon can both see them, so I'm sure it is installed correctly.

So is there some other Win32 function that provides a definitive list of available serial ports?


Source: (StackOverflow)

Stable alternative to RXTX

After using RXTX for a number of different projects, I've come across many annoying discrepancies and issues that can only sensibly be put down to bugs in the library - deadlocks, race hazards, and monitor threads deep in the RXTX library being left open preventing the program from closing (even though all ports I was using have been closed!) Running the latest "unstable" version has helped a bit, but it's still far from where I'd call it reliable, and activity on the project seems rather low at present.

However, searching for free cross-platform alternatives to RXTX doesn't seem to come up with much else.

Is there another library that anyone's tried with more luck? I don't need parallel port support, just serial, and it doesn't necessarily have to be compatible with RXTX or the javax.comm API.


Source: (StackOverflow)

writing to serial port from linux command line

From windows I can communicate with a serial port device using following commands:

mode com1: baud=9600 data=8 parity=n stop=1
copy con com1
alt+18alt+2ctrl+z

Device starts the requested operation.

When I try to accomplish the same operation from a stand alone debian box or from a debian virtualbox instance of the same windows machine, I had no luck so far.

Here's equivalent linux commands(at least I think so)

stty -F /dev/ttyS0 speed 9600 cs8 -cstopb -parenb
echo '\x12\x02' > /dev/ttyS0

Nothing happens.

Can somebody please direct me to the right direction?


Source: (StackOverflow)

What's the easiest, most practical way to toggle several lightbulbs with a PC? [closed]

This question is mainly electronics related, but it also has a programming aspect.

Some background on the problem

We have a traffic light on a wall in our office. When people come in to the office, they can immediately tell from the traffic light whether last night's automatic build & test runs went smoothly: Green means all tests passed, yellow means some tests failed and red means some builds failed.

Right now, there are three switches on three cables hanging from the traffic light and someone has to manually toggle these every morning. I'm looking for an easy way to automate this process with a PC.

Some background on me

I can write software. I have some soldering experience. I know digital design theory, but I've never built a physical device. I don't have a lot of time on my hands.

The question

How can I control three 110V lightbulbs (or any device) from a PC with the minimum amount of effort (and investment)?

Some lax constraints

  • I don't care about the effort to write the software to control a serial/USB port.
  • Having said that, it would be nice if I don't have to write any software and just use existing tools.
  • I prefer not to do any soldering! I can go with one of those hobby kits where you push components into slots etc. Or perhaps it could be something from Toys "R" Us.
  • I'm willing to purchase an existing device like an Arduino board.
  • It would be nice if I can get this done with just parts that are lying around. For instance, I have an old 2400Bd modem that I can take apart (though, that would probably be followed by some soldering).


Update

Similar projects that are mentioned in the answers:


Source: (StackOverflow)

Use a handheld bluetooth printer with android

I have a bluetooth Handheld printer that I am able to communicate to using a SPP connection from my Mac(using Coolterm). When I'm trying to do the same from Android (using platform 7) I am running into multiple issues:

  • The printer doesn't seem to support/need PIN Authentication. When connecting from OSX, I just selected the option that said "Do not use a pin" and it got paired. In Android, when I use device.createRfcommSocketToServiceRecord(), it always ends up asking me for a PIN/Key(which I don't have/need). I solved this using the reflection trick:

    Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
    BluetoothSocket connection = (BluetoothSocket) m.invoke(device, 1);
    

    I am unsure whether this actually worked, but the blinking LED on the printer stops blinking, which makes me believe it did.

  • Once I have the socket, I try to write byte data to the stream using:

    byte[] buffer = new byte[3];
    buffer[0] = (byte) 0x8A;
    buffer[1] = (byte) 0xC1;
    buffer[2] = (byte) 0x04;
    outStream.write(buffer);
    int response = inStream.read();
    mySocket.close();
    

    Sending the same three-byte sequence from Coolterm on OSX printed a test page from the printer. However, this seems to make the thread hang on Android(the read).

Is there something I am missing out here?

EDIT: This seems to work only when I set channel to 1. So that means I am on to something here.


Source: (StackOverflow)

Python AttributeError: 'module' object has no attribute 'Serial'

I'm trying to access a serial port with Python 2.6 on my Raspberry Pi running Debian. My script named serial.py tries to import pySerial:

import serial
ser = serial.Serial('/dev/ttyAMA0', 9600)
ser.write("hello world!")

For some reason it refuses to establish the serial connection with this error:

AttributeError: 'module' object has no attribute 'Serial'

When I try to type the same code in the interactive Python interpreter it still doesn't work.

Strangely, it used to work about a couple hours ago.

What could be the problem? I've tried to fix this for a while, installing pySerial again, rewriting my code, double-checking the serial port, etc.

Thanks in advance!


Source: (StackOverflow)

IOException: read failed, socket might closed - Bluetooth on Android 4.3

Currently I am trying to deal with a strange Exception when opening a BluetoothSocket on my Nexus 7 (2012), with Android 4.3 (Build JWR66Y, I guess the second 4.3 update). I have seen some related postings (e.g. http://stackoverflow.com/questions/13648373/bluetoothsocket-connect-throwing-exception-read-failed), but none seems to provide a workaround for this issue. Also, as suggested in these threads, re-pairing does not help, and constantly trying to connect (through a stupid loop) also has no effect.

I am dealing with an embedded device (a noname OBD-II car adapter, similar to http://images04.olx.com/ui/15/53/76/1316534072_254254776_2-OBD-II-BLUTOOTH-ADAPTERSCLEAR-CHECK-ENGINE-LIGHTS-WITH-YOUR-PHONE-Oceanside.jpg). My Android 2.3.7 phone does not have any issues connecting, and the Xperia of a colleague (Android 4.1.2) also works. Another Google Nexus (I dont know if 'One' or 'S', but not '4') also fails with Android 4.3.

Here is the Snippet of the connection establishment. It is running in its own Thread, created within a Service.

private class ConnectThread extends Thread {

    private static final UUID EMBEDDED_BOARD_SPP = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");

    private BluetoothAdapter adapter;
    private boolean secure;
    private BluetoothDevice device;
    private List<UUID> uuidCandidates;
    private int candidate;
    protected boolean started;

    public ConnectThread(BluetoothDevice device, boolean secure) {
        logger.info("initiliasing connection to device "+device.getName() +" / "+ device.getAddress());
        adapter = BluetoothAdapter.getDefaultAdapter();
        this.secure = secure;
        this.device = device;

        setName("BluetoothConnectThread");

        if (!startQueryingForUUIDs()) {
            this.uuidCandidates = Collections.singletonList(EMBEDDED_BOARD_SPP);
            this.start();
        } else{
            logger.info("Using UUID discovery mechanism.");
        }
        /*
         * it will start upon the broadcast receive otherwise
         */
    }

    private boolean startQueryingForUUIDs() {
        Class<?> cl = BluetoothDevice.class;

        Class<?>[] par = {};
        Method fetchUuidsWithSdpMethod;
        try {
            fetchUuidsWithSdpMethod = cl.getMethod("fetchUuidsWithSdp", par);
        } catch (NoSuchMethodException e) {
            logger.warn(e.getMessage());
            return false;
        }

        Object[] args = {};
        try {
            BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    BluetoothDevice deviceExtra = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");

                    uuidCandidates = new ArrayList<UUID>();
                    for (Parcelable uuid : uuidExtra) {
                        uuidCandidates.add(UUID.fromString(uuid.toString()));
                    }

                    synchronized (ConnectThread.this) {
                        if (!ConnectThread.this.started) {
                            ConnectThread.this.start();
                            ConnectThread.this.started = true;
                            unregisterReceiver(this);
                        }

                    }
                }

            };
            registerReceiver(receiver, new IntentFilter("android.bleutooth.device.action.UUID"));
            registerReceiver(receiver, new IntentFilter("android.bluetooth.device.action.UUID"));

            fetchUuidsWithSdpMethod.invoke(device, args);
        } catch (IllegalArgumentException e) {
            logger.warn(e.getMessage());
            return false;
        } catch (IllegalAccessException e) {
            logger.warn(e.getMessage());
            return false;
        } catch (InvocationTargetException e) {
            logger.warn(e.getMessage());
            return false;
        }           

        return true;
    }

    public void run() {
        boolean success = false;
        while (selectSocket()) {

            if (bluetoothSocket == null) {
                logger.warn("Socket is null! Cancelling!");
                deviceDisconnected();
                openTroubleshootingActivity(TroubleshootingActivity.BLUETOOTH_EXCEPTION);
            }

            // Always cancel discovery because it will slow down a connection
            adapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                bluetoothSocket.connect();
                success = true;
                break;

            } catch (IOException e) {
                // Close the socket
                try {
                    shutdownSocket();
                } catch (IOException e2) {
                    logger.warn(e2.getMessage(), e2);
                }
            }
        }

        if (success) {
            deviceConnected();
        } else {
            deviceDisconnected();
            openTroubleshootingActivity(TroubleshootingActivity.BLUETOOTH_EXCEPTION);
        }
    }

    private boolean selectSocket() {
        if (candidate >= uuidCandidates.size()) {
            return false;
        }

        BluetoothSocket tmp;
        UUID uuid = uuidCandidates.get(candidate++);
        logger.info("Attempting to connect to SDP "+ uuid);
        try {
            if (secure) {
                tmp = device.createRfcommSocketToServiceRecord(
                        uuid);
            } else {
                tmp = device.createInsecureRfcommSocketToServiceRecord(
                        uuid);
            }
            bluetoothSocket = tmp;
            return true;
        } catch (IOException e) {
            logger.warn(e.getMessage() ,e);
        }

        return false;
    }

}

The code is failing at bluetoothSocket.connect(). I am getting a java.io.IOException: read failed, socket might closed, read ret: -1. This is the corresponding source at GitHub: https://github.com/android/platform_frameworks_base/blob/android-4.3_r2/core/java/android/bluetooth/BluetoothSocket.java#L504 Its called through readInt(), called from https://github.com/android/platform_frameworks_base/blob/android-4.3_r2/core/java/android/bluetooth/BluetoothSocket.java#L319

Some metadata dump of the used socket resulted in the following information. These are exactly the same on Nexus 7 and my 2.3.7 phone.

Bluetooth Device 'OBDII'
Address: 11:22:33:DD:EE:FF
Bond state: 12 (bonded)
Type: 1
Class major version: 7936
Class minor version: 7936
Class Contents: 0
Contents: 0

I have some other OBD-II adapters (more expansives) and they all work. Is there any chance, that I am missing something or might this be a bug in Android?


Source: (StackOverflow)