Difference between revisions of "Сериен порт"

From Ilianko
Line 3: Line 3:
  
 
== Променливи ==
 
== Променливи ==
 +
Разгледайте различните [[C типове данни int, char, float, array, string, struct|типове данни в C]].
 +
 
Преобразуване на буква в двоичен код
 
Преобразуване на буква в двоичен код
  

Revision as of 19:32, 22 March 2011

Цел на упражнението

Преговор типове данни, оператори. Достъп до сериен порт.

Променливи

Разгледайте различните типове данни в C.

Преобразуване на буква в двоичен код

#include <stdio.h>   /* Standard input/output definitions */

#define TESTD 'a'

int main(void)
{
  int z=128, y = 0;
  char a = TESTD;
  char b[8] = "00000000";
        
  for ( y=0;  y < 8;  ++y)
  {
    b[7-y] = ((a & z) == z) ? '0' : '1';
        /* a = 0 0 1 0 1 0 0 0
           AND
           z = 0 0 0 0 1 0 0 0
           ===================
           r = 0 0 0 0 1 0 0 0 = z */ 
    z = z >> 1; // <=> z >>= 1  - преместване с един бит
  }
    
  printf("%s \n", b); 
  return 0;
}

Проверка по четност

Инсталация GTKTerm

:~$ sudo apt-get install gtkterm

Комуникация през терминал и сериен порт

Комуникация през C, POSIX и сериен порт


#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 */

#define PORTNAME  "/dev/ttyS0"

int main(void)
{
    int fd; // File descriptor for the port 
    struct termios options; // Serial port settings
	
	
    fd = open( PORTNAME, O_RDWR | O_NOCTTY | O_NONBLOCK);
	
    if (fd == -1)//Could not open the port.
	perror("open_port: Unable to open port");
    else 
       fcntl(fd, F_SETFL, 0);
	
    tcgetattr(fd, &options);
    cfsetispeed(&options, B2400);
    cfsetospeed(&options, B2400);
    
    options.c_cflag |= ( CREAD);
    options.c_cflag |= ( CLOCAL);
    options.c_cflag &= ( ~CSTOPB);
        
    tcsetattr(fd,TCSANOW, &options);

    write(fd, "a \n", 3); \\write to serial port
           
    return 0;
}

Разглеждане на сигнал на сериен порт

Самостоятелна подготовка

Да се напише програма, която изпраща символите от клавиатурата към серийния порт