c++ serial communication linux 9data bits - linux

a bit exotic question :D
I'm programming c++ in ubuntu 10 and i need to code a mdb(multi drop bus) protocol which uses 9 data bits in serial communication (YES 9 data bits :D)
Some drivers do support 9 data bits on some uart chips, but mostly they do not.
To explain briefly:
mdb uses 8 data bits for data and 9th data bit for mode set.
So when master sends first BYTE it sets mode=9thbit to 1 which means that all devices on the bus are interrupted and are looking for this first byte that holds the address of a device.
If the listening device (one of many) finds its address in this first byte it knows that the following bytes will be data bytes for it. data bytes have bit 9 = mode bit set to 0
example in bits: 000001011 000000010 000000100 000000110 (1stbyte address and 3 data bytes)
The return situation from slave -> master mode bit is used for end of transmission.
So the master reads from serial so long until it finds a 9bit packet that has 9th bit = 1 usualy the last 9bit sequence is a chk byte + mode = 1
So finally my question:
I know how to user CMPAR flag in termios to use parity bit for mode bit eg. setting it to either MARK(1) or SPACE(0)
example FOR ALL that don't know how:
First check if this is defined if not probably no support in termios:
# define CMSPAR 010000000000 /* mark or space (stick) parity */
And the code for sending with mark or space parity eg. simulating 9th data bit
struct termios tio;
bzero(&tio, sizeof(tio));
tcgetattr(portFileDescriptor, &tio);
if(useMarkParity)
{
// Send with mark parity
tio.c_cflag |= PARENB | CMSPAR | PARODD;
tcsetattr(portFileDescriptor, TCSADRAIN, &tio);
}
else
{
// Send with space parity
tio.c_cflag |= PARENB | CMSPAR;
tio.c_cflag &= ~PARODD;
tcsetattr(portFileDescriptor, TCSADRAIN, &tio);
}
write(portFileDescriptor,DATA, DATALEN);
Now what i don't know HOW to set the parity checking on receive, i have tried almost all combinations and i cannot get that error parity byte sequence.
Can anyone help me how to set parity checking on receive that it does not ignore parity and does not strip bytes but it adds DEL before "bad" received byte:
As it says in the POSIX Serial help
INPCK and PARMRK If IGNPAR is enabled, a NUL character (000 octal) is
sent to your program before every character with a parity error.
Otherwise, a DEL (177 octal) and NUL character is sent along with
the bad character.
So how to correctly set PARMRK AND INPCK that it will detect mode bit = 1 as parity bit error and insert DEL 177 octal in the return stream.
Thank you :D

It sounds to me like you want to set space parity on the receiver and don't enable IGNPAR. That way when a byte with mark parity is received it should generate the parity error with the DEL.

I was having the same problem running in a Linux guest OS. Running the same program on another machine with Linux as the host OS works. I suspect that the virtual serial port does not pass on the parity error. See PARMRK termios behavior not working on Linux. It is still possible that the VM is not the problem because it was a completely different computer. I was able to get parity errors using Realterm in Windows (the host OS on the computer where Linux was the guest), however.
Also, note the code in n_tty.c shows it inserts '\377' '\0' rather than '\177' '\0'. This was also verified on the working configuration.

Related

writting 0D 0A insted of 0A when I tried to write into uart

The following code configures UART port.
const char *UART2_path="/dev/ttymxc2";
int UART2;
void UART2_open(const char *UART2_path)
{
int flags = O_RDWR | O_NOCTTY ;
UART2 = open(UART2_path,flags);
tcgetattr(UART2, &ttyurt); //Get the current attributes of the serial port //
//Setting baud rate (input and output)
cfsetispeed(&ttyurt, B115200);
cfsetospeed(&ttyurt, B115200);
ttyurt.c_cflag &= ~PARENB; // Disables the Parity Enable bit(PARENB) //
ttyurt.c_cflag &= ~CSTOPB; // Clear CSTOPB, configuring 1 stop bit //
ttyurt.c_cflag &= ~CSIZE; // Using mask to clear data size setting //
ttyurt.c_cflag |= CS8; // Set 8 data bits //
ttyurt.c_cflag &= ~CRTSCTS; // Disable Hardware Flow Control //
tcsetattr(UART2, TCSANOW, &ttyurt); // Write the configuration to the termios structure//
tcflush(UART2, TCIFLUSH);
}
---------
--------
--------
buffer[8]={0x1f,0x0a,0x1a,0x89,0x85,0xbf,0x36,0x40};
write(UART2,&buffer,strlen(buffer));//sending on uart
expected output==>1f0a8985bf3640
actual output ==>1f0d0a8985bf3640
I'm able to send data, but for some reason 0x0A sent characters are received as 0x0D 0x0A. I'm fairly sure something in this port configuration is doing this.
extra byte 0d before 0a?
writting 0D 0A insted of 0A when I tried to write into uart
That appears to caused by a termios (mis)configuration that is inappropriate for your situation. The termios layer is capable of translating/expanding each occurrence of \n to \r\n for output (i.e. the ONLCR attribute, which is typically enabled by default).
The following code configures UART port.
Your program accesses a serial terminal (i.e. /dev/tty...) rather than a "UART port". There are several layers of processing in between your program and the UART hardware. See Linux serial drivers
Your initialization code is properly implemented (i.e. per Setting Terminal Modes Properly), but it is just the bare minimum that sets only the serial line parameters to 115200 8N1 and no HW flow control. Absolutely no other termios attributes are specified, which means that your program will use whatever previous (random?) settings (such as the ONLCR attribute), and may occasionally misbehave.
The most important consideration when using a serial terminal and termios configuration is determining whether the data should be handled in canonical (as lines of text) or non-canonical (aka raw or binary) mode. Canonical mode provides additional processing to facilitate the reading/writing of text as lines, delimited by End-of-Line characters. Otherwise syscalls are performed for an arbitrary number of bytes. See this answer for more details.
Your output data appears to be not (ASCII) text, so presumably you want to use non-canonical (aka raw) mode. For raw output, your program should specify:
ttyurt.c_oflag &= ~OPOST;
This will inhibit any data conversion on output by termios.
But your termios initialization is also incomplete for reading.
For a proper and concise termios initialization for non-canonical mode, see this answer.
If instead you need canonical mode, then refer to this answer.
You seem to be another victim of UNIX/Linux versus Windows "newline"/"line feed" handling: UNIX/Linux uses single character, like 0A (line feed) or 0D (newline) for going to another line, while Windows uses a combination 0D0A, so most probably you have some program that converts your "I-believe-the-data-to-be-UNIX-like" into "Windows-like".
That might go far: I had the situation where UNIX files were sent to a Windows computer, and the user was using a Windows file viewer to see the content of the files, and it was the file viewer itself which was doing that conversion. Therefore I advise you to check all intermediate programs.

spi_write_then_read with variant register size

As I understand the term "word length" (spi_bits_per_word) in spi, defines the CS (chip select) active time.
It therefore seems that linux driver will function correctly when dealing with simple spi protocols which keeps word size constant.
But, How can we deal with spi protocols which use different spi size as part of protocol.
for example cs need to be active for sending spi word - 9 bits, and then reading spi - 8 bits or 24 bits (the length of the register read is different each time, depends on register)
How can we implement that using spi_write_then_read ?
Do we need to set bits_per_word size for the sending and then another bits_per_word for the receiving ?
Regards,
Ran
"word length" means number of bits you can send in one transaction. It doesn't defines the CS (chip select) active time. You can keep it active for whatever time you want(least is for word-length).
SPI has got some format. You cannot randomly read-write whatever number of bits you want.Most of SPI supports 4-bit, 8-bit, 16-bit and 32-bit mode. If the given mode doesn't satisfy your requirement then you need to break your requirement. For eg:- To read 24-bit data, we need to use 8-bit word-length transfer for 3 times.
Generally SPI is fullduplex means it will read at same time it will write.

PARMRK termios behavior not working on Linux

I'm trying to receive messages from a device that uses mark parity for an address byte and space parity for the message body. The device is a "master" of a multi-drop serial bus. Based on the termios man page, I am using CMSPAR, PARENB, ~PARODD, INPCK, ~IGNPAR, and PARMRK. I expect to get a 3-byte sequence on each address byte: '\377' '\0' . It doesn't happen... I always get the address byte (and the body bytes) but no leading '\377' '\0' chars.
I tried to get PARMRK to work with odd and even parity setups just in case CMSPAR was not supported. Still no 3-byte sequences in the data stream. I'm using Ubuntu 12.04 LTS.
n_tty.c: n_tty_receive_parity_error() has the logic that implements PARMRK. 8250_core.c has the logic to flag parity errors. dmesg | grep ttyS0 shows serail8250: ... is a 16550A. Hmmm... a subsequent message shows 00:0a: ... is a 16550A. Perhaps the 8250 driver is not actually processing ttyS0?
Any ideas? Even if you don't see what I've done wrong but have gotten PARMAR to work, comments about your situation might help me.
UPDATE:
My Linux is running in a VMware VM so I tried a non-VM config and now it works! I case someone knows, I'd still like to know why parity errors are not detected in a VM.
Here is my configuration code:
struct termios tio;
bzero(&tio, sizeof(tio));
tcgetattr(fd, &tio);
// Frame bus runs at 38,400 BAUD
const int BAUD_Rate = B38400;
cfsetispeed(&tio, BAUD_Rate);
cfsetospeed(&tio, BAUD_Rate);
// Initialize to raw mode. PARMRK and PARENB will be over-ridden before calling tcsetattr()
cfmakeraw(&tio);
// Ignore modem lines and enable receiver
tio.c_cflag |= (CLOCAL | CREAD);
// No flow control
tio.c_cflag &= ~CRTSCTS; // No HW flow control
tio.c_iflag &= ~(IXON | IXOFF); // Set the input flags to disable in-band flow control
// Set bits per byte
tio.c_cflag &= ~CSIZE;
tio.c_cflag |= CS8;
// Use space parity to get 3-byte sequence (0xff 0x00 <address>) on address byte
tio.c_cflag |= CMSPAR; // Set "stick" parity (either mark or space)
tio.c_cflag &= ~PARODD; // Select space parity so that only address byte causes error
// NOTE: The following block overrides PARMRK and PARENB bits cleared by cfmakeraw.
tio.c_cflag |= PARENB; // Enable parity generation
tio.c_iflag |= INPCK; // Enable parity checking
tio.c_iflag |= PARMRK; // Enable in-band marking
tio.c_iflag &= ~IGNPAR; // Make sure input parity errors are not ignored
// Set it up now
if (tcsetattr(fd, TCSANOW, &tio) == -1)
{
cout << "Failed to setup the port: " << errno << endl;
return -1;
}
I was having a similar issue (but from the opposite side):
The master of a serial protocol should be sending the 1st byte of a frame with parity mark and all the rest with parity space, while the slave would respond only with parity space.
Many serial comms drivers will ignore the "CMSPAR" bit without returning an error, so you may think that you've setup parity Mark/Space, while you've actually have selected parity Odd/Even instead.
I had to use a protocol analyser to realise that.
So I ended up checking the data of each byte before sending it and switching between odd/even parity in order to simulate the Mark/Space parity that I needed.
Most USB to Serial adapters will need a similar approach because they don't support parity mark/space.
For example, let's say we want to send the following data:
01 03 07 0F 1F
The 1st byte should be sent with parity Mark and the rest with parity space
We could do the following:
Send 01 with odd parity (parity bit=1)
Send 03 with odd parity (parity bit=0)
Send 07 with even parity (parity bit=0)
Send 0F with odd parity (parity bit=0)
Send 1F with even parity (parity bit=0)
That way we can simulate the needed result.
The catch here is that when you are switching parity, the driver is performing a lot of checks that are time consuming and this can affect the final rate of data transfer.
I was using a hacked version of the serial comms driver on an embedded device that could switch parity very fast by omitting some of the unnecessary checks for the application (like baud rate changes for example).
If your inter-character delay is critical, you may need a different solution.

How to get the parity bit from characters received by serial port?

I am writing a driver for a device that is connected by serial port. Unfortunately, the 9th data bit indicates whether the character should be interpreted as command or as data.
Using the built-in parity check does not work for me because an error is indicated by an additional character (NUL). And then I don't know wheter I received two data bytes or one with an parity error.
Is there a way to get this parity bit elsewhere?
EDIT: Apparently, this problem also exists on Windows (see http://gilzu.com/?p=6). It ended up with rewriting the serial driver. Is this also my only option on Linux?
As I see it, you should be able to use PARMRK as is, assuming that the \377 \0 pattern is unlikely to appear in your input. otherwise, yes, you may modify your serial driver to prepend the parity (or rather, if this byte had a parity error) to each byte. I'd go with the former, though.

Is it possible to use 9-bit serial communication in Linux?

RS-232 communication sometimes uses 9-bit bytes. This can be used to communicate with multiple microcontrollers on a bus where 8 bits are data and the extra bit indicates an address byte (rather than data). Inactive controllers only generate an interrupt for address bytes.
Can a Linux program send and receive 9-bit bytes over a serial device? How?
The termios system does not directly support 9 bit operation but it can be emulated on some systems by playing tricks with the CMSPAR flag. It is undocumented and my not appear in all implementations.
Here is a link to a detailed write-up on how 9-bit emulation is done:
http://www.lothosoft.ch/thomas/libmip/markspaceparity.php
9-bit data is a standard part of RS-485 and used in multidrop applications. Hardware based on 16C950 devices may support 9-bits, but only if the UART is used in its 950 mode (rather than the more common 450/550 modes used for RS-232).
A description of the 16C950 may be found here.
This page summarizes Linux RS-485 support, which is baked into more recent kernels (>=3.2 rc3).
9-bit data framing is possible even if a real world UARTs doesn't.
Found one library that also does it under Windows and Linux.
See http://adontec.com/9-bit-serial-communication.htm
basically what he wants is to output data from a linux box, then send it on let's say a 2 wire bus with a bunch of max232 ic's -> some microcontroller with uart or software rs232 implementation
one can leave the individual max232 level converter's away as long as there are no voltage potency issues between the individual microcontrollers (on the same pcb, for example, rather than in different buildings ;) up until the maximum output (ttl) load of the max232 (or clones, or a resistor and invertor/transistor) ic.
can't find linux termios settings for MARK or SPACE parity (Which i'm sure the hardware uarts actually do support, just not linux tty implementation), so we shall just hackzor the actual parity generation a bit.
8 data bits, 2 stop bits is the same length as 8 databits, 1 parity bit, 1 stop bit. (where the first stopbit is a logic 1, negative line voltage).
one would then use the 9th bit as an indicator that the other 8 bits are the address of the individual or group of microcontrollers, which then take the next bytes as some sort of command, or data, as well, they are 'addressed'.
this provides for an 8 bit transparant, although one way traffic, means to address 'a lot of things' (256 different (groups of) things, actually ;) on the same bus. it's one way, for when one would want to do 2 way, you'd need 2 wire pairs, or modulate at multiple frequencies, or implement colission detection and the whole lot of that.
PIC microcontrollers can do 9 bit serial communication with ehm 'some trickery' (the 9th bit is actually in another register ;)
now... considering the fact that on linux and the likes it is not -that- simple...
have you considered simply turning parity on for the 'address word' (the one in which you need 9 bits ;) and then either setting it to odd or even, calculate it so that the right one is chosen to make the 9th (parity) bit '1' with parity on and 8 bit 'data', then turn parity back off and turn 2 stop bits on. (which still keeps a 9 bit word length in as far as your microcontroller is concerned ;)... it's a long time ago but as far as i recall stop bits are just as long as data bits in the timing of things.
this should work on anything that can do 8 bit output, with parity, and with 2 stop bits. which includes pc hardware and linux. (and dos etc)
pc hardware also has options to just turn 'parity' on or off for all words (Without actually calculating it) if i recall correctly from 'back in the days'
furthermore, the 9th bit the pic datasheet speaks about, actually IS the parity bit as in RS-232 specifications. just that you're free to turn it off or on. (on PIC's anyway - in linux it's a bit more complicated than that)
(nothing a few termios settings on linux won't solve i think... just turn it on and off then... we've made that stuff do weirder things ;)
a pic microcontroller actually does exactly the same, just that it's not presented like 'what it actually is' in the datasheet. they actually call it 'the 9th bit' and things like that. on pc's and therefore on linux it works pretty much the same way tho.
anyway if this thing should work 'both ways' then good luck wiring it with 2 pairs or figuring out some way to do collission detection, which is hell a lot more problematic than getting 9 bits out.
either way it's not much more than an overrated shift register. if the uart on the pc doesn't want to do it (which i doubt), just abuse the DTR pin to just shift out the data by hand, or abuse the printer port to do the same, or hook up a shift register to the printer port... but with the parity trick it should work fine anyway.
#include<termios.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdint.h>
#include<string.h>
#include<stdlib.h>
struct termios com1pr;
int com1fd;
void bit9oneven(int fd){
cfmakeraw(&com1pr);
com1pr.c_iflag=IGNPAR;
com1pr.c_cflag=CS8|CREAD|CLOCAL|PARENB;
cfsetispeed(&com1pr,B300);
cfsetospeed(&com1pr,B300);
tcsetattr(fd,TCSANOW,&com1pr);
};//bit9even
void bit9onodd(int fd){
cfmakeraw(&com1pr);
com1pr.c_iflag=IGNPAR;
com1pr.c_cflag=CS8|CREAD|CLOCAL|PARENB|PARODD;
cfsetispeed(&com1pr,B300);
cfsetospeed(&com1pr,B300);
tcsetattr(fd,TCSANOW,&com1pr);
};//bit9odd
void bit9off(int fd){
cfmakeraw(&com1pr);
com1pr.c_iflag=IGNPAR;
com1pr.c_cflag=CS8|CREAD|CLOCAL|CSTOPB;
cfsetispeed(&com1pr,B300);
cfsetospeed(&com1pr,B300);
tcsetattr(fd,TCSANOW,&com1pr);
};//bit9off
void initrs232(){
com1fd=open("/dev/ttyUSB0",O_RDWR|O_SYNC|O_NOCTTY);
if(com1fd>=0){
tcflush(com1fd,TCIOFLUSH);
}else{printf("FAILED TO INITIALIZE\n");exit(1);};
};//initrs232
void sendaddress(unsigned char x){
unsigned char n;
unsigned char t=0;
for(n=0;n<8;n++)if(x&2^n)t++;
if(t&1)bit9oneven(com1fd);
if(!(t&1))bit9onodd(com1fd);
write(com1fd,&x,1);
};
void main(){
unsigned char datatosend=0x00; //bogus data byte to send
initrs232();
while(1){
bit9oneven(com1fd);
while(1)write(com1fd,&datatosend,1);
//sendaddress(223); // address microcontroller at address 223;
//write(com1fd,&datatosend,1); // send an a
//sendaddress(128); // address microcontroller at address 128;
//write(com1fd,&datatosend,1); //send an a
}
//close(com1fd);
};
somewhat works.. maybe some things the wrong way around but it does send 9 bits. (CSTOPB sets 2 stopbits, meaning that on 8 bit transparant data the 9th bit = 1, in addressing mode the 9th bit = 0 ;)
also take note that the actual rs232 line voltage levels are the other way around from what your software 'reads' (which is the same as the 'inverted' 5v ttl levels your pic microcontroller gets from the transistor or inverter or max232 clone ic). (-19v or -10v (pc) for logic 1, +19/+10 for logic 0), stop bits are negative voltage, like a 1, and the same lenght.
bits go out 0-7 (and in this case: 8 ;)... so start bit -> 0 ,1,2,3,4,5,6,7,
it's a bit hacky but it seems to work on the scope.
Can a Linux program send and receive 9-bit bytes over a serial device?
The standard UART hardware (8251 etc.) doesn't support 9-bit-data modes.
I also made complete demo for 9-bit UART emulation (based on even/odd parity). You can find it here.
All sources available on git.
You can easily adapt it for your device. Hope you like it.

Resources