Communication. Serial port programming

Similar documents
Socket programming in C

Programming refresher and intro to C programming

File IO and command line input CSE 2451

Experiment Number: 02. Title: PC-to-PC communication through RS-232 port

UNIX System Programming

CS240: Programming in C

File Descriptors and Piping

CSE 410: Systems Programming

Operating System Labs. Yuanbin Wu

CSE 333 SECTION 3. POSIX I/O Functions

HE-GE Linux USB Driver - User Guide. 1vv r2 03/25/2013

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra

More on C programming

Advanced C Programming Topics

Input / Output Functions

System Software Experiment 1 Lecture 7

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Standard File Pointers

Input/Output and the Operating Systems

Goals of this Lecture

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

Processes often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Operating System Labs. Yuanbin Wu

CS240: Programming in C

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Operating systems. Lecture 7

File I/O. Preprocessor Macros

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Lab # 4. Files & Queues in C

QC Linux USB Driver - User Guide 1vv r7 04/11/2014

CSE 333 SECTION 3. POSIX I/O Functions

UNIX Terminals. Terminology. Serial Ports. Serial connection. Terminal Types. Terminal Types

Standard C Library Functions

EL2310 Scientific Programming

Section 3: File I/O, JSON, Generics. Meghan Cowan

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Embedded programming, AVR intro

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

CMPSC 311- Introduction to Systems Programming Module: Input/Output

UNIX System Calls. Sys Calls versus Library Func

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

File I/O. Arash Rafiey. November 7, 2017

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O

C mini reference. 5 Binary numbers 12

File Handling in C. EECS 2031 Fall October 27, 2014

File Access. FILE * fopen(const char *name, const char * mode);

UNIX input and output

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu

Standard I/O in C, Computer System and programming in C

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

PL-2303 specific usb-uart serial communications manager for QNX Neutrino

Preview. Interprocess Communication with Pipe. Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Lecture 03 Bits, Bytes and Data Types

Stream Model of I/O. Basic I/O in C

25.2 Opening and Closing a File

Operating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

A brief introduction to C programming for Java programmers

Recitation 8: Tshlab + VM

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

Course organization. Course introduction ( Week 1)

Process Management! Goals of this Lecture!

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

ECE551 Midterm Version 1

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators

File and Console I/O. CS449 Spring 2016

Naked C Lecture 6. File Operations and System Calls

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

Terminal Modem Mice. Computer Center, CS, NCTU

Computer Center, CS, NCTU. Serial devices. Terminal Modem Mice

CS 261 Fall Mike Lam, Professor. Structs and I/O

CSC209H Lecture 7. Dan Zingaro. February 25, 2015

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

C Basics And Concepts Input And Output

Files. Eric McCreath

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

211: Computer Architecture Summer 2016

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Engineering program development 7. Edited by Péter Vass

EL2310 Scientific Programming

Preview. System Call. System Call. System Call. System Call. Library Functions 9/20/2018. System Call

Input and Output System Calls

How do we define pointers? Memory allocation. Syntax. Notes. Pointers to variables. Pointers to structures. Pointers to functions. Notes.

System Programming. Standard Input/Output Library (Cont d)

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

2009 S2 COMP File Operations

SWEN-250 Personal SE. Introduction to C

File (1A) Young Won Lim 11/25/16

SYNOPSIS #include <termios.h> #include <unistd.h>

CS 201. Files and I/O. Gerson Robboy Portland State University

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

Transcription:

Applied mechatronics Communication. Serial port programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2017

Outline 1 Introduction 2 Terminal I/O programming (in C) Raw I/O Structured I/O 3 Serial port programming Serial port configuration Serial port I/O Conclusion 4 Summary 5 Byte order Communication. Serial port programming 2/1

(Computer) mechatronics Controlling the physical world from a computer Sensors Actuators Communication with the user (operator) with other equipment Design systems for debugging Introduction Communication. Serial port programming 3/38

The lab project Building and programming a small servo system Building from PC towards embedded system Communication (serial port) Interface hardware Host (PC) programming Embedded system Building a simple microcontroller card Programming it Sensors and actuators The system depends on communication between PC and microcontroller Introduction Communication. Serial port programming 4/38

Communication between host and embedded system During operation Operator communication Mode changes, start/stop Implementing a feedback loop Reading process values Setting setpoints Setting parameters Make it possible to tune controllers during operation Less hard-coded parameters, less reprogramming, faster development cycle During development Monitoring the state of the program Printing or logging process values Facilitates debugging Introduction Communication. Serial port programming 5/38

A typical protocol Host to embedded system control word: mode changes data: reference (set-point) values Embedded system to host status word: current mode of operation, warnings and faults data: process values (feedback) Introduction Communication. Serial port programming 6/38

A typical protocol, simple example Message frames Master telegram: master (PC) slave (embedded system) Control word Position setpoint Velocity feedforward Slave telegram: slave master Status word Position feedback Velocity feedback Mode of operation controlled by control and status words Data format may depend on mode of operation Introduction Communication. Serial port programming 7/38

A typical protocol example (CANopen DS 402) Control word Status word Bit Name Bit Name 0 Switch on 8 Pause/halt 1 Disable voltage 9 Reserved 2 Quick stop 10 Reserved 3 Enable Operation 11 Ack. error 4 Op. mode specific 12 Reset position 5 Op. mode specific 13 Manufacturer specific 6 Op. mode specific 14 Manufacturer specific 7 Reset fault 15 Manufacturer specific Bit Name Bit Name 0 Ready to switch on 8 Reserved 1 Switched on 9 Remote 2 Operation enable 10 Target reached 3 Fault 11 Internal limit active 4 Disable voltage 12 Op. mode specific 5 Quick stop 13 Op. mode specific 6 Switch on disabled 14 Manufacturer specific 7 Warning 15 Manufacturer specific Introduction Communication. Serial port programming 8/38

Design decisions Trade-off communication efficiency vs. complexity of decoding messages A few large, complex or many small telegram types What data to send? Data types, sizes, ranges, and scaling Reserve space for future additions Byte order for >8 bit data types Introduction Communication. Serial port programming 9/38

Terminal Input/Output The fundamental concepts file descriptor - low level access open(), close() (more on these later) read(), write() Stream (FILE*) - structured access fdopen(), fclose() fprintf(), fgetc(), fgets() Tips: use fprintf() for output, but read() for input. or fgetc() for reading a single character See the serial port lab memo for details Terminal I/O programming (in C) Communication. Serial port programming 10/38

read() ssize_t read(int fd, void *buf, size_t count); Reads up to count characters from a file descriptor Returns on success: the number of characters read zero on end-of-file a negative value on error Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 11/38

Reading a single char with read() # include <stdio.h> # include <unistd.h> int main () { int run =1; } while ( run ){ ssize_t res ; char c; res = read ( STDIN_FILENO, &c, 1); if(res > 0 ) { printf (" Read : %c\n", c); } else { run = 0; } } return 0; Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 12/38

Reading a string with read() # include <stdio.h> # include <unistd.h> # define SIZE 10 int main () { int run =1; } while ( run ){ char c[ SIZE +1]; // +1: space for terminating null ssize_t res = read ( STDIN_FILENO, c, SIZE ); if(res > 0 ) { c[ res ] = \0 ; // add terminating null printf (" Read : %s\n", c); } else { run = 0; } } return 0; Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 13/38

Reading all input with read() Check return value and increment position # define SIZE 30 int main () { int run =1; char c[ SIZE +1]; size_t pos = 0; while ( run && pos < SIZE ){ ssize_t res = read ( STDIN_FILENO, c+pos, SIZE - pos ); if( res > 0 ) { // if more chars to read pos += res ; // increment pos } else { run = 0; } } c[ pos ] = \0 ; // add terminating null printf (" Buffer after read : %s\n", c); return 0; } Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 14/38

Raw access, writing with write() # include <sys / types.h> # include <string.h> # define BUFSIZE 20... char buf [ BUFSIZE ]; size_t nbytes ; ssize_t bytes_written ; int fd;... strncpy ( buf, " This is a test \n", BUFSIZE ); nbytes = strnlen ( buf, BUFSIZE ); bytes_written = write (fd, buf, nbytes );... Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 15/38

Structured I/O Opening and closing streams FILE *fopen(const char *path, const char *mode); FILE *fdopen(int fd, const char *mode); where mode is (r)ead, (w)rite or (a)ppend. For read/write use r+, w+, or a+. # include < stdio.h> # include < errno.h> int fd;... FILE *f = fdopen (fd, "r"); if (!f){ perror (" fdopen "); } int fclose(file *fp); if( fclose (f )){ perror (" fclose "); } Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 16/38

Reading a single char from a stream: fgetc() int fgetc(file *stream); Reads one character from a stream Returns an unsigned char cast to int or the constant EOF (End-of-file) Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 17/38

Example: fgetc() # include <stdio.h> int main () { int res ; int run =1; } while ( run ){ res = fgetc ( stdin ); if( res!= EOF ) { char c = res ; printf (" Read : %c\n", c); } else { run = 0; } } return 0; Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 18/38

Read a C-string from a stream: fgets() char *fgets(char *s, int size, FILE *stream); Reads up to size 1 characters from a stream until a newline of EOF Adds a terminating null byte If a newline is read, it is stored into the buffer Returns s on success, or NULL on error of if no characters were read Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 19/38

More structured I/O Reading C strings: char *fgets(char *s, int size, FILE *stream); Example: char buf [ BUFSIZE ]; // BUFSIZE -1 chars + terminating null int fd;... FILE *f = fdopen (fd, "r"); if (! f){ // handle error or return error code...} char * res = fgets ( buf, BUFSIZE, f); if(res ) { printf (" input (%p): %s\n", res, buf ); } else { printf (" fgets returned NULL \n"); } Formatted values: int fprintf(file *stream, const char *format,...); int fscanf(file *stream, const char *format,...); Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 20/38

printf() format conversions character argument type; convert to d, i signed decimal notation x unsigned hexadecimal notation (w/o leading 0x) u unsigned decimal notation c single character (converted to char) f double in decimal notation [-]mmm.dddd s string (char *) the conversion characters may be preceeded with arguments for minimum width and/or precision. E.g., %4.2f : min 4 chars wide, 2 decimal positions %.8x : print (at least) 8 digits, padding with leading zeroes... and much more, consult a language reference Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 21/38

snprintf() example int snprintf(char *buf, size_t n, const char *format,...); Similar functionality to StringBuilder in Java Writes (at most) n characters (incl. terminating null) to buf. The return value is the number of chars in the resulting formatted string. If the return value is larger than n, the output was truncated. Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 22/38

snprintf() example # define BUFSZ 80 int main () { char buf [ BUFSZ ]; int x = 17; float f = 4.2; } snprintf ( buf, BUFSZ, " adding %d and %f equals %f", x, f, x+f) ; printf (" buf : %s\n", buf ); Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 23/38

Serial port setup Open the port Set communication parameters Data rate ( baud rate ): bits per second Data bits: bits per character (normally 7 or 8) Parity: (odd/even/none) Stop bits Flow control Close the port Serial port programming : Serial port configuration Communication. Serial port programming 24/38

Opening and closing the device int open(const char *path, int flags) returns a file descriptor path is the device name (e.g., /dev/ttys0) flags is a bitwise-inclusive OR of flags, including exactly one of O_RDONLY O_WRONLY O_RDWR E.g., int fd = open(port, O_RDWR O_NOCTTY O_NDELAY); Open for reading and writing The port is not the controlling terminal for the program Open non-blocking. Also on some systems: ignore the DCD ("carrier detect") line (On most systems, DCD is ignored anyway, so blocking is fine if you want that.) int close(int fd) closes the file descriptor, freeing the underlying resource returns zero on success Serial port programming : Serial port configuration Communication. Serial port programming 25/38

Opening the port Error handling const char * device = "/ dev / ttys0 "; int fd; fd = open ( device, O_RDWR O_NOCTTY ); if (fd < 0) { perror ( device ); exit ( -1); } The standard function void perror(const char *s) prints a system error message (include <errno.h>) Serial port programming : Serial port configuration Communication. Serial port programming 26/38

Port configuration Serial port configuration is fairly low-level read a struct with flags and parameters change the struct write back the updated struct s t r u c t t e r m i o s o p t i o n s ; // a l l o c a t e s t r u c t t c g e t a t t r ( fd, &o p t i o n s ) ; // Get o p t i o n s f o r t h e p o r t c f s e t i s p e e d (& o p t i o n s, B2400 ) ; // Set t h e baud r a t e s to 2400 c f s e t o s p e e d (& o p t i o n s, B2400 ) ; o p t i o n s. c _ c f l a g = (CLOCAL CREAD ) ; // Enable t h e r e c e i v e r and // i g n o r e modem c o n t r o l l i n e s / add o t h e r c o n f i g u r a t i o n ( e. g., n e x t s l i d e ) h e r e b e f o r e w r i t i n g back o p t i o n s / t c s e t a t t r ( fd, TCSANOW, &o p t i o n s ) ; // Write new o p t i o n s Serial port programming : Serial port configuration Communication. Serial port programming 27/38

Remarks CREAD: Enable receiver CLOCAL: Ignore modem control lines (i.e., CD). If CLOCAL is off, open() will block until the carrier detect signal is asserted (electrically), unless the flag O_NONBLOCK is set. Note that or (as in flags = a b) means and (as in set (the bits set in) a and b in flags). Serial port programming : Serial port configuration Communication. Serial port programming 28/38

Configuring the port Control options: Bnnnnn : bit rate CS8 : character size PARENB : enable parity bit CSTOPB : stop bits (2 stop bits if set ) CRTSCTS : output hardware flow control ( only used if the cable has all necessary lines. ) CREAD : enable receiver CLOCAL : local connection, no modem or job contol Serial port programming : Serial port configuration Communication. Serial port programming 29/38

Configuring the port struct termios options ; cfsetispeed (& options, B1200 ); cfsetospeed (& options, B1200 ); options. c_cflag = CLOCAL CREAD ; options. c_cflag &= ~ CSIZE ; options. c_cflag &= ~ PARENB ; options. c_cflag &= ~ CSTOPB ; options. c_cflag = CS8 ; // 8N1 options. c_cflag &= ~ CRTSCTS ; // No CTS / RTS tcsetattr (fd, TCSANOW, & options ); Serial port programming : Serial port configuration Communication. Serial port programming 30/38

Configuring the port Some local options: ISIG : enable job control signals ( INTR, SUSP, QUIT,...) ICANON : Everything is stored into a buffer, and can be edited until a carriage return or line feed ECHO : Enable echoing of input characters Serial port programming : Serial port configuration Communication. Serial port programming 31/38

Configuring the port Some input and output options: ICRNL : map CR to NL ( otherwise a CR input on the other computer may not terminate input ) IXON : Enable software flow control ( outgoing ) IXOFF : Enable software flow control ( incoming ) INPCK : Enable parity check IGNPAR : Ignore parity errors PARMRK : Mark parity errors ISTRIP : Strip parity bits ONLCR : Map NL to CR NL in output. Serial port programming : Serial port configuration Communication. Serial port programming 32/38

Interfaces to I/O operations raw access using file descriptors ssize_t read (int fd, void * buf, size_t nbyte ); ssize_t write (int fd, const void * buf, size_t nbyte ); structured access using streams FILE * fdopen ( int fd, const char * mode ) ; int fclose( FILE *stream ); int fgetc ( FILE * stream ); char * fgets ( char *s, int size, FILE * stream ); int fprintf(file *stream, const char *format,...); Serial port programming : Serial port I/O Communication. Serial port programming 33/38

Conclusion There is a self-study programming lab on the serial port (soon) on the web page Hints: Use the raw access functions for simple cases Don t use canonical mode unless reading linewise Use fprintf for more advanced output Avoid using fscanf Serial port programming : Conclusion Communication. Serial port programming 34/38

Communication Summary during development and during operation easier debugging less hard-coded parameters less reprogramming required in the final lab project Design a simple protocol Don t be alarmed by the serial port programming Summary Communication. Serial port programming 35/38

Questions? Summary Communication. Serial port programming 36/38

Byte order (Endianness) The serial link sends a series of bytes (characters) For data types larger than 8 bits is the most significant byte sent first (big endian) or last (little endian) Byte order (in memory) is CPU specific Example: 1000 as a 16 bit integer (== 0x3E8) Big endian: 0x03, 0xE8 ( network, IP, Java) Little endian: 0xE8, 0x03 (CANopen, Intel) Conversion is done by mask & shift. Be careful with sign extension (use unsigned in C). The same applies to values in memory Byte order Communication. Serial port programming 37/38

Example: Little endian memory In a byte-addressed memory, byte order must be defined for larger values First byte means lowest address Example: *a = 0x0A0B0C0D; Byte order Communication. Serial port programming 38/38

Flow Control / Handshaking Flow control Avoiding buffer overflow Fast communication Small buffers Receiver can pause communication if it cannot keep up with the data flow Hardware signals Signalling protocol Handshaking to establish a connection Agreement on data rates, packet type numbers, sequence numbers, etc. (e.g., SYN-ACK) Flow control/handshaking Communication. Serial port programming 39/38

Flow Control / Handshaking (2) DTR/DSR Data Terminal Ready / Data Set Ready Used for startup (typically: connection established over a modem line DSR Can be jumpered for direct connections RTS/CTS: Hardware flow control Request To Send: Terminal has data to send Clear To Send: Receiver ready to receive XON/XOFF: Software flow control In band signalling, bad for binary data Flow control/handshaking Communication. Serial port programming 40/38