DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 9 of 9

Thread: open Serial port, send array of hex bytes

  1. #1
    Join Date
    Jan 2009
    Posts
    4

    open Serial port, send array of hex bytes

    Hi

    I am trying to (a) open a serial port, and then (b) write a stream of bytes to it and read any responses from the serial port. I have some code so far (will post below) but what I really want to know is, am I on the right track. There seem to be lots of posts on lots of forums about serial programming, but very little in the way of simple examples that actually work. What method should I use to open the port? What method should I use to write bytes to the serial port? What method do I use to read a response from the port?

    This code doesn't actually work yet, and I am not sure if its even opening the port properly since I can still open the port in cutecom when this is running. I do get the message that it opened the port though.

    Thanks!

    Code:
    /*
     * Main.cpp
     *
     *  Created on: 9-Jan-2009
     *      Author: root
     */
    
    
    /////////////////////////////////////////////////
    // Serial port interface program               //
    /////////////////////////////////////////////////
    
    #include <stdio.h> // standard input / output functions
    #include <string.h> // string function definitions
    #include <unistd.h> // UNIX standard function definitions
    #include <fcntl.h> // File control definitions
    #include <errno.h> // Error number definitions
    #include <termios.h> // POSIX terminal control definitionss
    #include <time.h>   // time calls
    
    
    int open_port(void)
    {
    	int fd; // file description for the serial port
    	
    	fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
    	
    	if(fd == -1) // if open is unsucessful
    	{
    		//perror("open_port: Unable to open /dev/ttyS0 - ");
    		printf("open_port: Unable to open /dev/ttyS0. \n");
    	}
    	else
    	{
    		fcntl(fd, F_SETFL, 0);
    		printf("port is open.\n");
    	}
    	
    	return(fd);
    } //open_port
    
    int configure_port(int fd)      // configure the port
    {
    	struct termios port_settings;      // structure to store the port settings in
    
    	cfsetispeed(&port_settings, B115200);    // set baud rates
    	cfsetospeed(&port_settings, B115200);
    
    	port_settings.c_cflag &= ~PARENB;    // set no parity, stop bits, data bits
    	port_settings.c_cflag &= ~CSTOPB;
    	port_settings.c_cflag &= ~CSIZE;
    	port_settings.c_cflag |= CS8;
    	
    	tcsetattr(fd, TCSANOW, &port_settings);    // apply the settings to the port
    	return(fd);
    
    } //configure_port
    
    int query_modem(int fd)   // query modem with an AT command
    {
    	char n;
    	fd_set rdfs;
    	struct timeval timeout;
    	
    	// initialise the timeout structure
    	timeout.tv_sec = 10; // ten second timeout
    	timeout.tv_usec = 0;
    	
    	//Create byte array
    	unsigned char send_bytes[] = { 0x02, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x23, 0x01, 0x21, 0x03};
    	
    	write(fd, send_bytes, 13);  //Send data
    	printf("Wrote the bytes. \n");
    	sleep(10);
    	printf("After the usleep.\n");
    	
    	// do the select
    	n = select(fd + 1, &rdfs, NULL, NULL, &timeout);
    	
    	// check if an error has occured
    	if(n < 0)
    	{
    	 perror("select failed\n");
    	}
    	else if (n == 0)
    	{
    	 puts("Timeout!");
    	}
    	else
    	{
    	 printf("\nBytes detected on the port!\n");
    	}
    
    	return 0;
    	
    } //query_modem
    
    int main(void)
    { 
    	int fd = open_port();
    	configure_port(fd);
    	query_modem(fd);
    	
    	return(0);
    	
    } //main

  2. #2
    Join Date
    Nov 2003
    Posts
    4,118
    It's very OS-dependent. Your code should work on POSIX systems such as Linux but not on Vista for example. There's no standard port access libraries in C++ so you usually have to use the OS specific APIs. In other words, the question is: which OS are you aiming at?
    Danny Kalev

  3. #3
    Join Date
    Dec 2003
    Posts
    3,366
    right, on windows all you need is a createfile /writefile pair and you are done, very little to do. You can open them other ways, thats the quick and dirty way to do it. It should just be a simple call to open a file on unix, I thought that was the unix way (everything is a file) ?? That gets it open with the defaults, and as you have it, you need tweaks to control the port if you need something other than default.



    And bytes are bytes, hex is a human overlay of the data, the computer sees 'a', 0x23, 65, 045, etc as all the same thing (binary). Well, it would if those all were the same value, which they are not, because I don't care to convert a number 5 times.

    To test it, you can do the following:
    connect the tx and rx pins with a jumper (commonly known as a "paperclip"). Then send a small string, like "Hello" and then read back from your port. Make sure this is working with a known program like (windows again) hyperterminal. You can also connect com1 and com2 on a computer that has 2 ports, but this is becoming a rare thing.
    Last edited by jonnin; 01-13-2009 at 08:11 PM.

  4. #4
    Join Date
    Jan 2009
    Posts
    4
    Sorry - should have stated that right away. Linux, not windows.

  5. #5
    Join Date
    Jan 2008
    Posts
    100
    Hello,

    For a past project I used a class called CSerial.

    http://www.codeguru.com/cpp/i-n/netw...icle.php/c2503

    I cannot remember if it works on un(*/i)x operating systems.

    Hope this helps

    p.s There is a fatter version caled CSerialPort at...

    http://www.codeguru.com/Cpp/I-N/netw...icle.php/c2483

  6. #6
    Join Date
    Jan 2009
    Posts
    4
    Both are Windows only.

  7. #7
    Join Date
    Mar 2009
    Posts
    2
    Found a solution yet?

  8. #8
    Join Date
    Jan 2009
    Posts
    4
    Yes. I used Eclipse for coding - works nice, gcc built in now.

    Main.cpp:
    Code:
    /*
     * Main.cpp
     *
     *  Created on: 9-Jan-2009
     *      Author: root
     */
    
    
    #include <stdio.h>   /* Standard input/output definitions */
    #include <string.h>  /* String function definitions */
    #include <unistd.h>  /* UNIX standard function definitions */
    #include <fcntl.h>   /* File control definitions */
    #include <errno.h>   /* Error number definitions */
    #include <termios.h> /* POSIX terminal control definitions */
    
    #include "serprt.hpp"
    
    int fd;
    
    int initport(int fd) {
    	struct termios options;
    	// Get the current options for the port...
    	tcgetattr(fd, &options);
    	// Set the baud rates to 115200...
    	cfsetispeed(&options, B115200);
    	cfsetospeed(&options, B115200);
    	// Enable the receiver and set local mode...
    	options.c_cflag |= (CLOCAL | CREAD);
    	
    	//disable hardware flow control
    	options.c_cflag &= ~CRTSCTS;
    
    	//disable software flow control
    	options.c_iflag &= ~(IXON | IXOFF | IXANY);
    
    	//raw input
    	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    		
    	//raw output
    	options.c_oflag &= ~OPOST;
    	
    	//No parity - 8N1
    	options.c_cflag &= ~PARENB;
    	options.c_cflag &= ~CSTOPB;
    	options.c_cflag &= ~CSIZE;
    	options.c_cflag |= CS8;
    
    	// Set the new options for the port...
    	tcsetattr(fd, TCSANOW, &options);
    	
       
    	return 1;
    }
    
    int main(int argc, char **argv) {
    
    	fd = open("/dev/ttyS0", O_RDWR); // | O_NOCTTY); // | O_NDELAY);
    
    	if (fd == -1) {
    		perror("open_port: Unable to open /dev/ttyS0 - ");
    		return 1;
    	} else {
    		fcntl(fd, F_SETFL, 0);
    		//fcntl(fd, F_SETFL, FNDELAY);
    	}
    	
    	//printf("baud=%d\n", getbaud(fd));
    	initport(fd);
    	printf("baud=%d\n", getbaud(fd));
    
    	unsigned char sCmd[13]; 
    	sCmd[0] = 0x00
            sCmd[1] = 0x01
            //etc
    
    	if (!writeport(fd, sCmd, 13)) {
    		printf("write failed\n");
    		close(fd);
    		return 1;
    	}
    
    	//printf("write cmd:%d\n", sCmd[1]);
    	
    	usleep(50000);
    	unsigned char sResult[13];
    
    	fcntl(fd, F_SETFL, 0);
        //fcntl(fd, F_SETFL, FNDELAY); // don't block serial read
    
    	if (!readport(fd,sResult)) {
    		printf("read failed\n");
    		close(fd);
    		return 1;
    	}
    	
    	close(fd);
    	return 0;
    }
    serprt.hpp:
    Code:
    #ifndef SERPRT_HPP_
    #define SERPRT_HPP_
    
    int writeport(int fd, unsigned char *chars, int numBytes);
    int readport(int fd, unsigned char *result);
    int getbaud(int fd);
    
    #endif /*SERPRT_HPP_*/
    serprt.cpp:
    Code:
    #include <stdio.h>   /* Standard input/output definitions */
    #include <string.h>  /* String function definitions */
    #include <unistd.h>  /* UNIX standard function definitions */
    #include <fcntl.h>   /* File control definitions */
    #include <errno.h>   /* Error number definitions */
    #include <termios.h> /* POSIX terminal control definitions */
    
    #include "serprt.hpp"
    
    int writeport(int fd, unsigned char *chars, int numBytes) {
    	
    	//show array contents
    	//printf("write array contents:\n");
    	int counter = 0;
    	printf("write array = ");
    	while(counter < numBytes) {
    		printf("%d,", chars[counter]);
    		counter++;
    	}
    	printf("\n");
    	
    	int n = write(fd, chars, numBytes); //strlen(chars));
    	if (n < 0) {
    		fputs("write failed!\n", stderr);
    		return 0;
    	}
    	//all good
    	return 1;
    }
    
    int readport(int fd, unsigned char *result) {
    	
    	int iIn = read(fd, result, 254); //13); //254);
    	
    	//show result array
    	int counter = 0;
    	printf("result[] = ");
    	while(counter < iIn) {
    		printf("%d,",result[counter]);
    		counter++;
    	}
    	printf("\n");
    	
    	
    	//result[iIn-1] = 0x00;
    	if (iIn < 0) {
    		if (errno == EAGAIN) {
    			printf("SERIAL EAGAIN ERROR\n");
    			return 0;
    		} else {
    			printf("SERIAL read error %d %s\n", errno, strerror(errno));
    			return 0;
    		}
    	}                    
    	return 1;
    }
    
    int getbaud(int fd) {
    	struct termios termAttr;
    	int inputSpeed = -1;
    	speed_t baudRate;
    	tcgetattr(fd, &termAttr);
    	/* Get the input speed.                              */
    	baudRate = cfgetispeed(&termAttr);
    	switch (baudRate) {
    		case B0:      inputSpeed = 0; break;
    		case B50:     inputSpeed = 50; break;
    		case B110:    inputSpeed = 110; break;
    		case B134:    inputSpeed = 134; break;
    		case B150:    inputSpeed = 150; break;
    		case B200:    inputSpeed = 200; break;
    		case B300:    inputSpeed = 300; break;
    		case B600:    inputSpeed = 600; break;
    		case B1200:   inputSpeed = 1200; break;
    		case B1800:   inputSpeed = 1800; break;
    		case B2400:   inputSpeed = 2400; break;
    		case B4800:   inputSpeed = 4800; break;
    		case B9600:   inputSpeed = 9600; break;
    		case B19200:  inputSpeed = 19200; break;
    		case B38400:  inputSpeed = 38400; break;
    		case B115200:  inputSpeed = 115200; break;
    	}
    	return inputSpeed;
    }

  9. #9
    Join Date
    Mar 2009
    Posts
    2
    thanx!!!!

Similar Threads

  1. using kernel32 to read serial port into Excel
    By zerugamat in forum VB Classic
    Replies: 11
    Last Post: 01-12-2010, 06:34 PM
  2. Open a com Port
    By Thomas in forum Talk to the Editors
    Replies: 2
    Last Post: 07-30-2002, 01:56 AM
  3. OPEN FILE IN HEX.
    By MGH in forum VB Classic
    Replies: 1
    Last Post: 01-08-2002, 05:04 PM
  4. Serial Port
    By Ettienne in forum .NET
    Replies: 2
    Last Post: 10-22-2001, 01:12 PM
  5. Replies: 1
    Last Post: 04-03-2001, 02:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center