Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Linux based serial programming     - NAT (network address translation) Realization (Linux)

- Linux system find command Detailed (Linux)

- Linux System Getting Started Learning: Linux command in w (Linux)

- Gentoo: !!! existing preserved libs problem (Linux)

- CentOS 6.7 install Nagios Tutorials (Server)

- To compiler and install MariaDB-10.0.20 under CentOS 6.6 (Database)

- Polymorphism of the C ++ compiler and run-time polymorphism (Programming)

- Java reflection mechanism explained in detail and Method.invoke explanation (Programming)

- Java 8 Lambda principle analysis (Programming)

- Using Linux stat command to view the files (Linux)

- Let's Encrypt with semiautomatic into Nginx configuration https (Server)

- Linux use iptables ban Ping (Linux)

- Parts of the partition is not recognized after Debian mount mobile hard disk (Linux)

- GCC and gfortran write MEX program (Matlab2012a) under Ubuntu 14.04 (Programming)

- Thinking in Java study notes - initialization and cleanup (Programming)

- Some practical tips Linux (Linux)

- Unix / Linux commonly used to clean up disk space command (Linux)

- In-depth summary of the PHP core of object-oriented (Programming)

- to install the deployment of LVS under CentOS 7.0 (Server)

- How to create a binary distribution with Bash (Linux)

 
         
  Linux based serial programming
     
  Add Date : 2018-11-21      
         
         
         
  Linux Serial programming, the configuration process is like stop bits, parity, baud rate and data bits. Open the file as open as serial devices, then configure the above said several parameters. Write serial port using a standard Linux system calls write, read with read. Of which there are some configuration in the code in detail, directly attached to the following Code:

Serial.cfg first with a configuration file to specify the parameters of the serial port, directly behind the changes to the configuration file to modify parameters. We call this configuration file in / etc / below

DEV = / dev / tq2440_serial2
SPEED = 115200
DATABITS = 8
STOPBITS = 1
PARITY = N

Here's some serial device file has been used to generate drive device nodes.

Definitions header file Serial.h, characterize the structure define the serial port

#ifndef SERIAL_PORT_H
#define SERIAL_PORT_H

#define TRUE 1
#define FALSE 0

#define z_U32 unsigned int
#define z_U8 unsigned char

#define SERIAL_NAME_LEN 32
extern int serial_config ();
extern int set_speed (int fd);
extern int set_other_parm (int fd);

typedef struct z_Serial_port {

 z_U8 serial_name [SERIAL_NAME_LEN];
 z_U32 serial_baud;
 z_U8 data_bits;
 z_U8 stop_bits;
 z_U8 parity;

} HI_Serial_port;

extern z_Serial_port get_current_serial ();
#endif

The next course is slightly serial.c file, set the serial port to achieve the various parameters

/ *
** Author: z
** CopyRight: z
** Funtion: serial port Interface
** Date: 2014
* /

#include / ** /
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "pthread.h"

#include "serial_port.h"

#define CFG_FILE "/etc/serial.cfg"// place where profile
#define DEBUG 1
#define ERROR -1
#define OK 1

/ * Serial Port Struct * /
z_Serial_port serial_port;

int speed_array [] = {B230400, B115200, B57600, B38400, B19200, B9600, B4800,
                    B2400, B1200, B300, B38400, B19200, B9600, B4800,
                    B2400, B1200, B300};
int name_array [] = {230400, 115200, 57600, 38400, 19200, 9600, 4800,
                    2400, 1200, 300, 38400, 19200, 9600, 4800,
                    2400, 1200, 300};

// Get the current serial structure

z_Serial_port get_current_serial () {
 z_Serial_port current_serial;
 memset (current_serial.serial_name, 0, sizeof (current_serial.serial_name));

  strncpy (current_serial.serial_name, serial_port.serial_name, sizeof (current_serial.serial_name));
  current_serial.serial_baud = serial_port.serial_baud;
  current_serial.data_bits = serial_port.data_bits;
  current_serial.stop_bits = serial_port.stop_bits;
  current_serial.parity = serial_port.parity;
  if (DEBUG) {
   printf ( "current_serial.serial_baud =% d n", current_serial.serial_baud);
   printf ( "current_serial.data_bits =% d n", current_serial.data_bits);
   printf ( "current_serial.stop_bits =% d n", current_serial.stop_bits);
   printf ( "current_serial.parity =% c n", current_serial.parity);
  }
  return current_serial;
}

// Read the serial port profile, and configure filled structure

int serial_config ()
{
    FILE * serial_fp;
    char read_buf [20] = {0};
    char temp [20];
    char parity;

    / * Read serial config from file * /
    serial_fp = fopen (CFG_FILE, "r");
    if (serial_fp == NULL) {
        printf ( "Can not open serial config file n");
        return ERROR;
    }
    memset (serial_port.serial_name, 0, sizeof (serial_port.serial_name));
    fscanf (serial_fp, "DEV =% s n", serial_port.serial_name);
    
    fscanf (serial_fp, "SPEED =% s n", temp);
    serial_port.serial_baud = atoi (temp);

    fscanf (serial_fp, "DATABITS =% s n", temp);
    serial_port.data_bits = atoi (temp);

    fscanf (serial_fp, "STOPBITS =% s n", temp);
    serial_port.stop_bits = atoi (temp);

    fscanf (serial_fp, "PARITY =% s n", temp);
    serial_port.parity = temp [0];

    if (DEBUG) {
        printf ( "Serial Dev =% s n", serial_port.serial_name);
        printf ( "Serial Speed ​​=% d n", serial_port.serial_baud);
        printf ( "Serial DataBits =% d n", serial_port.data_bits);
        printf ( "Serial StopBite =% d n", serial_port.stop_bits);
        printf ( "Serial Parity =% c n", serial_port.parity);
    }
    fclose (serial_fp);
    return OK;
}

/ *
 * Set Baudrate
 * Set the baud rate, fd is open handle to the device node
 * * /
int set_speed (int fd)
{
    struct termios option;
    struct termios old_option;
    int i = 0;

    // Get the old option
    tcgetattr (fd, & old_option); // termios structure is to be operated

    for (i = 0; i         if (serial_port.serial_baud == name_array [i]) {
    tcflush (fd, TCIOFLUSH);
        cfsetispeed (& option, speed_array [i]);
        cfsetospeed (& option, speed_array [i]);

    if (tcsetattr (fd, TCSANOW, & option)! = 0) {// configuration takes effect immediately
  printf ( "set serial baudrate failed n");
  return ERROR;
    } Else {
  tcflush (fd, TCIOFLUSH); // clear the input and output queues
        if (DEBUG) printf ( "set serial baudrate sucessed n");
  return OK;
    }
 }
    }
}

/ *
 * Set Other Paramters
 * Set the other parameters
 * * /
int set_other_parm (int fd)
{
    struct termios options;
    struct termios old_options;

    if (tcgetattr (fd, & old_options)! = 0) {
 printf ( "Failed to getattr n");
 return ERROR;
    }
    options.c_cflag | = (CLOCAL | CREAD);
    options.c_cflag & = ~ CSIZE;

    / * Set Date Bits * /
    switch (serial_port.data_bits) {
        case 7:
    options.c_cflag | = CS7;
    break;
 case 8:
    options.c_cflag | = CS8;
    break;
 default:
    options.c_cflag | = CS8;
        break;
    }

    / * Set Parity Bites * /
    switch (serial_port.parity) {
 case 'n':
 case 'N':
    options.c_cflag & = ~ PARENB;
    options.c_iflag & = ~ INPCK;
    break;
 case 'o':
 case 'O':
    options.c_cflag | = (PARODD | PARENB);
    options.c_iflag | = INPCK;
    break;
 case 'e':
 case 'E':
    options.c_cflag | = PARENB;
    options.c_cflag & = ~ PARODD;
    options.c_iflag | = INPCK;
    break;
 default:
    options.c_cflag & = ~ PARENB;
    options.c_iflag & = ~ INPCK;
        break;
    printf ( "default parity none parity n");
    }

    / * Set Stop Bites * /
    switch (serial_port.stop_bits) {
 case 1:
    options.c_cflag & = ~ CSTOPB;
    break;
 case 2:
    options.c_cflag | = CSTOPB;
    break;
 default:
    options.c_cflag & = ~ CSTOPB;
    }
    if (serial_port.parity! = 'n' || serial_port.parity! = 'N') {
 options.c_iflag | = INPCK;
    }
    options.c_cc [VTIME] = 0; // set timeout Timeout parma
    options.c_cc [VMIN] = 0; // read x bite return the number of bytes read before the operation, here is set to 0

 options.c_iflag | = IGNPAR | ICRNL;
    options.c_oflag | = OPOST; // original mode, there are two modes, if it is the original model, then this will be n only after output
    options.c_iflag & = ~ (IXON | IXOFF | IXANY);


    tcflush (fd, TCIFLUSH);
    if (tcsetattr (fd, TCSANOW, & options)! = 0) {
 printf ( "set serial other parma failed n");
 return ERROR;
    }
    return OK;
}

Here, the basic parameters on the configuration finished, to note here configurations and configuration VMIN and VTIME original model.

Interface written, write a test program to test like the test program write more ugly, forgive me, ha ha:

#include
#include
#include
#include

#include "serial_port.h"

int main (int argc, char * argv [])
{
 int ret;
 int fd;
 unsigned char data [50];

    z_Serial_port serial_p;

 printf ( "Configing serial from local file ... n");
 ret = serial_config ();
 if (ret! = 1) {
  printf ( "Failed to config serial n");
  return -1;
 }
 serial_p = get_current_serial ();
 fd = open (serial_p.serial_name, O_RDWR, 0); // open the way to read and write
 printf ( "opening% s n..", serial_p.serial_name);
 if (fd == -1) {
  printf ( "Can not open tty n");
  return -1;
 }
 // Set speed
    if (set_speed (fd) <0) {
  printf ( "set speed Failed n");
  return -1;
 }
 if (fcntl (fd, F_SETFL, O_NONBLOCK) <0) {
  printf ( "fcntl failed n");
  return -1;
 }
    if (isatty (STDIN_FILENO) == 0)
    {
        printf ( "not a terminal device n");
    } Else
        printf ( "! isatty success n");
 // Set other parma like stopbites etc.
    if (set_other_parm (fd) <0) {
  printf ( "set other parm failed n");
  return -1;
 }
 // Write data
 int i;
    char buff [512];
    char buff21 [] = "Hi Babby!";

    int nread, nwrite = 0;
    int nx;
    printf ( "fd =% d n", fd);
    nx = write (fd, buff21, sizeof (buff21));


    printf ( "nx =% d n", nx);
    while (1)
    {
        if ((nread = read (fd, buff, 512))> 0)
        {
            buff [nread] = ' 0';
            // Write (fd, buff, nread);
            printf ( " nrecv:% d n", nread);
            // Printf ( "% s", buff);
   printf ( "% d", buff [0]);
   printf ( "% d", buff [1]);
   printf ( "% d", buff [2]);
   printf ( "% d", buff [3]);
            printf ( " n");
        }
 
    }
 return 1;
}

He put MakeFile

CC = arm-linux-gcc
SEND_EXEC = serial_send

all: serial_port.c serial_port.h serial_send_msg.c
 $ (CC) -o $ (SEND_EXEC) serial_port.c serial_send_msg.c
#chmod 777 $ (SEND_EXEC)
clean:
 rm -rf * .o serial_send

Haha, is completed, the next step is testing. Here the circuit board TXD2 and RXD2 short, that spontaneous self-reading, serial print "Hi Babby!" Hey, get. Back will play out a GSM module. Also serial

Send AT commands to communicate. To pass the time during the relevant transfer analysis.
     
         
         
         
  More:      
 
- Linux Network Programming - raw socket Example: sending a UDP packet (Programming)
- Linux Network Programming - raw socket programming (Programming)
- JavaScript basic types and type conversion (Programming)
- Android project using the command to create and install the package (Programming)
- Windows7 system using Vagrant to build Linux virtualized development environment (Linux)
- Simple comparison of MySQL and Oracle in a sql analytical details (Database)
- expdp / impdp use version parameter data migration across versions (Database)
- Ubuntu 14.04 Configuring cuda-convnet (Linux)
- Advanced Linux security settings (Linux)
- iTerm - let your command line can also be colorful (Linux)
- RabbitMQ tutorial examples: the Hello RabbitMQ World Java realization (Linux)
- Based Docker build stand-alone high-availability cluster Hadoop2.7.1 Spark1.7 (Server)
- LVM mirrored logical volume to achieve (Linux)
- Install Krita 2.8 on Ubuntu 13.10 / 12.04 / 12.10 (Linux)
- Puppet centralized configuration management system (Server)
- Unity Greeter Badges: the lost session icon back to the login screen Ubuntu (Linux)
- lolcat: an output terminal rainbow effects in the Linux command-line tool (Linux)
- gzip, bzip2, xz, tar, zip compression, archive Detailed (Linux)
- Samhain: Powerful intrusion detection system under Linux (Linux)
- Java garbage collection (Programming)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.