departamento de electrónica y automática - trabajo...

78
PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA Programación orientada a objetos Trabajo final Complementos de Informática Volney Torres Almendro Registro: 13744

Upload: others

Post on 30-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Programación orientada a objetos

Trabajo finalComplementos de Informática

Volney Torres Almendro Registro: 13744

Page 2: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Objetivos

Mediante POO adquirir información de día, hora, minuto, segundo y temperatura que entrega unsistema ad-hoc con interface al puerto serie.Permitir almacenar los datos en archivo.Permitir leer los datos de archivo.Permitir ordenar por los diferentes campos: hora de adquisición o temperatura.Visualizar los datos por pantalla.

Introducción

Para poder llevar a cabo los objetivos propuestos por la cátedra se propuso un desafío el cual consta de comunicar una computadora personal con un sistema ad-hoc con interface al puerto serie.

En el sistema ad-hoc se cargó una aplicación que envía un vector conformado por una quíntupla de valores día, hora, minuto, segundo y temperatura que son tomados cada 15 minutos durante10 días.

Esos valores son enviados por la puerta rs232 a la PC de escritorio donde los lee la aplicación que recibe y procesa los datos obtenidos.

Page 3: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Descripción de los componentes

Para el proyecto se utilizó una computadora con sistema Windows 7 con el compilador C++ Min GW bajo la interface IDE Eclipse Juno.

Mediante la interface RS232 (previo adaptador USB to RS232) se conectó a un sistema ad-hoc con interface al puerto serie.

Fig. 1: Sistema ad-hoc con interface a puerto serie.

Page 4: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Desarrollo del proyecto:

Trabajo final:Para resolver el proyecto se utilizó una clase para generar el objeto temperatura y una estructura para generar un objeto tipo tiempo.

Clase temperatura:

.

.

.class Temperatura {

// variables privadas private:

tiempo newTiempo;double newTemperatura;

public:Temperatura(); // constructor por defectovirtual ~Temperatura(); // destructorTemperatura(tiempo,double); // sobrecarga constructorTemperatura cons_carga(void); // sobrecarga constructor

friend ostream& operator << (ostream& fs,const Temperatura& temp){fs <<setw(2) <<temp.newTiempo.newDia <<"/"<<setw(2) << temp.newTiempo.newHora <<":"<<setw(2) << temp.newTiempo.newMinuto <<":"<<setw(2) << temp.newTiempo.newSegundo <<"-"<< temp.newTemperatura << endl;

return fs;} // sobrecarga operador <<

friend istream& operator >> (istream& fs,Temperatura& temp){char aux;fs >>temp.newTiempo.newDia >>aux >> temp.newTiempo.newHora >>aux >>temp.newTiempo.newMinuto >>aux >> temp.newTiempo.newSegundo >>aux >> temp.newTemperatura;

return fs;} // sobrecarga operador >>

//funciones de acceso a variables

double get_temperatura() const;tiempo get_tiempo() const;unsigned long int get_tiempo_lineal();void set_tiempo(tiempo&);void set_temperatura(double);

};

Page 5: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Descripción de la clase temperatura:

Consta de dos variables privadas tiempo newTiempo y double newTemperatura dondese almacena los valores de tiempo y temperatura, la primera en una estructura tipo tiempo y la temperatura con formato tipo double ya que se almacena valores con punto decimal. Dado que son variables privadas se implementaron métodos de acceso público a estas variables tales como get_tiempo(), get_temperatura(), set_tiempo(…), set_temperatura(…) etc.

En la parte pública se declaran los constructores, el constructor por defecto sin argumentos y otro constructor donde se pasan los valores de tiempo y temperatura.

Entre los métodos públicos se sobrecargan los operadores ” <<” y “ >> “ para re direccionar la entrada o salida y poder usar de forma transparente instrucciones tales como cin , cout , re direccionamiento a ficheros y puertas de salida tal como la rs232.

Estructura tiempo:

.

.

.struct tiempo{

int newDia;int newHora;int newMinuto;int newSegundo;void cargar();void mostrar();unsigned long int get_lineal();friend istringstream& operator >>(istringstream& fs, tiempo& tempo ){

char aux;fs >> tempo.newDia>>aux >> tempo.newHora >>aux >> tempo.newMinuto >>aux >> tempo.newSegundo ;return fs;

}friend ostringstream& operator << (ostringstream& os,const tiempo& tempo)

{os <<tempo.newDia <<"/"<< tempo.newHora <<":"<< tempo.newMinuto <<":"<< tempo.newSegundo <<" ";return(os);

}};

Page 6: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Descripción de la estructura tiempo:

Consta de 4 variables públicas newDia, newHora, newMinuto y newSegundo de tipo entero a su vez se implementaron dos métodos accesorios cargar() y mostrar() respectivamente para mostrar en pantalla y para cargar valores por consola, también se implementó un método para obtener el tiempo en segundos get_lineal() útil para hacer las operaciones booleanas a través del método sort.

También se sobrecargaron los operadores << y >> de entrada salida para usar de forma transparente cin , cout , ficheros y puertas de entrada salida.

La clase rs232class:

class rs232class {private:

HANDLE hPort;BOOL bRes;BYTE byte;BOOL timeout;DCB dcbPort; // Port

configurationCOMMTIMEOUTS commTimeouts; // Port

TimeoutsDWORD dwError; // Error code

public:// Open Serial portrs232class( char *psPort, // "COM1","COM2"

DWORD bBaudRate, // CBR_9600, CBR_19200. CBR_56000

BYTE bByteSize, // 7,8BYTE bParity, // NOPARITY,

EVENPARITY, ODDPARITYBYTE bStopBits, // ONESTOPBIT,

ONE5STOPBITS, TWOSTOPBITSDWORD ReadTimeout // Programmable Read

Timeout );

~rs232class(){CloseSerialPort(hPort);}

// Send a byteBOOL SerialSendByte(BYTE byte);// return TRUE: Send OK

// Receive a byteBOOL SerialReceiveByte(BYTE *pbyte, BOOL *pTimeout);// return TRUE & *pTimeout TRUE Send OK// return TRUE & *pTimeout FALSE Timeout// return FALSE Receive Error

// Close Serial Port

Page 7: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

BOOL CloseSerialPort(HANDLE hPort);};

Descripción de la clase rs232class

Se ve en la parte privada se declaran las variables que contienen los parámetros de seteo del puerto serie.

En la parte publica se observa el constructor donde se pasan los parámetros de seteo del puerto serie y el destructor llama al método CloseSerialPort() para cerrar el mismo y liberarlo para otras aplicaciones.

Entre los métodos públicos se implementaron SerialSendByte(..) y SerialReceiveByte(..)donde se envían y reciben los bytes a través de la puerta rs232.

La función Main():

La función consta de un menú principal donde ofrecen las diferentes opciones:

Fig. 9: Menú principal de la aplicación.

Page 8: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

1- Leer valores del kit kz80:La primera opción hace uso de la puerta rs232 para obtener los datos del kit z80

Fig. 10: Momento en que se reciben los valores enviados por el kit z80.

La subrutina de carga de valores se realizó usando la clase rs232class donde se crea un objeto llamado sesión con los parámetros de la puerta para comunicar.

Luego se envía un carácter “espacio” para notificar que se esperan los datos del kit para comenzar a guardarlos en memoria.

Se crean dos objetos uno Temperatura y otro tipo tiempo para almacenar los valores temporales capturados por la puerta.

Una vez cargados esos valores mediante la herramienta pushback son insertados en el arreglo de objetos llamado newdatos.

2- Mostrar valoresLa subrutina mostrar valores pasa en su argumento la dirección por referencia del arreglo de objetos temperatura.

Con la herramienta size() se calcula el tamaño del arreglo de objetos que son direccionados a través de su índice y enviados a la salida de pantalla directamente debido a que se implementó lasobrecarga del operador << en el objeto temperatura.

Page 9: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Fig. 11: se observa el listado de valores arrojado por la opción mostrar , se aprecia que va acompañado por el índice a la izquierda entre paréntesis y los datos son formateados a dos cifras separados el día por una barra derecha, la hora, min y seg por dos puntos y la temperatura por una barra horizontal.

3- Grabar valores en discoLa subrutina grabar_valores pasa los valores por referencia del arreglo de objetos asignados al nombre temp.

El funcionamiento es sencillo, se crea un objeto tipo ofstream llamado fichero, luego se captura elnombre de archivo y se pasa como parámetro, se determina el tamaño del arreglo con la herramienta size() y se van enviando los valores al fichero en forma transparente dado que se encuentra sobrecargado el operador <<.

4- Cargar valoresLa carga de valores se desarrolló de manera similar, se creó un objeto tipo ifstream llamado fichero, se creó un objeto tipo temperatura llamado temp que se usa para pasar los valores recibidos del fichero de forma transparente también por el uso de la sobrecarga del operador >>

Mientras eof sea falso se produce el bucle que inserta el objeto dentro del arreglo llamado NewDatos

5- Modificar datosPara modificar los datos se ingresa el número de fila a modificar y los datos a reemplazar luego a través de la herramienta erase() se borra el elemento, que luego con la herramienta insert se reemplaza el valor por el nuevo.

El código es el siguiente

temp.insert(temp.begin()+i,temporal.cons_carga());

Page 10: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

6- Borrar valorÍdem a opción anterior solo que se pide el número de fila a borrar y con la herramienta erase de borra el contenido apuntado por el subíndice.

temp.erase(temp.begin()+i);

7- Ordenar por temperatura

Fig. 12: listado usando ordenación ascendente aplicado a la hora, se observa que coincide con el ordenamiento inicial ascendente enviado por el kit z80.

Para realizar las ordenaciones se usa la herramienta sort donde se indica el comienzo y el fin del arreglo a ordenar y se pasa el parámetro booleano llamado ordenación hora que se resuelve en otra función aparte donde se hace la comparación y se devuelve el valor booleano al método.

Dado que el tiempo esta expresado en días, horas, minutos y segundos se hace la conversión a tiempo en segundos previo a la ordenación. Aun que puede utilizarse para ordenar campos específicos por ejemplo ordenar solo horas.

sort(temp.begin(),temp.end(),ordenacion_hora);

bool ordenacion_hora(Temperatura temp1,Temperatura temp2){

return (temp1.get_tiempo_lineal()<temp2.get_tiempo_lineal()); // ordenacion ascendente

}

8- Ordenación por temperaturaIdem anterior solo que en este caso se usó el criterio booleano :

bool ordenacion_temp(Temperatura temp1,Temperatura temp2){

return temp1.get_temperatura()<temp2.get_temperatura(); // ordenacion ascendente

Page 11: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

}

Fig. 13: Listado usando ordenación ascendente con el criterio booleano afectado a la temperatura, se observa que la temperatura crece al incrementarse las filas.

Conclusión:Con el uso de la programación orientada a objetos despierta una nueva forma de pensar en el programador, produciendo código más legible y natural.

Con el uso de las librerías para manipulación de arreglos de objetos se simplifica muchísimo la tarea del programador.

También con este trabajo se aprendió a manipular y utilizar librerías de código encapsulado por otros programadores como es el caso de la librería rs232class., la utilización de stream de datos, elformateo de salida a pantalla y la entrada a consola entre otras cosas más.

Page 12: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Anexo

Kit z80.La placa principal del kit consta de un microprocesador z80 64k de memoria RAM estática

y 32k de memoria ROM.

En el arranque inicial la memoria ROM se ubica en la dirección de memoria 0000h hasta 7fffh. A partir de la memoria 8000h hasta fffh se ubica la memoria RAM.

Durante el reset el programa en ROM se copia en la dirección f800h y deshabilitando el bloque ROM y activando el bloque RAM dejando 64k de RAM llanos para correr aplicaciones CP/M.

El programa BIOS queda residente en direcciones altas de memoria f800 que es el encargado de re direccionar los servicios de entrada salida hacia la puerta rs232 por lo que los programas CP/M trabajan en forma trasparente sin tener que hacer cambios en el software.

Para hacer la carga de aplicaciones en el kit se desarrolló un programa cargador “sender” que envía el archivo (.com) de CP/M en formato Intel hex por la puerta rs232 y lo carga en la dirección 0100h del kit.

Programa cargado en el sistema ad-hoc

Se desarrolló un programa escrito en C que simula el envío de datos recolectados durante 10 días de una estación que almacena valores de temperatura.

El mismo fue compilado usando un compilador de c para generar aplicaciones CP/M de la empresa Hi Tech software distribuye gratuitamente un programa limitado (hasta 2000 líneas de código c).

Page 13: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Lamentablemente debido a las limitaciones del compilador hi tech no se pudo usar las herramientas ofrecidas por la POO para desarrollar este pequeño programa.

Fig.6: momento en que se carga la aplicación en el kit z80.

Fig 7: En la figura se ve la aplicación corriendo en el kit z80 donde muestra el día, la hora, los minutos, segundos y la temperatura con un digito decimal.

Page 14: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Código fuente trabajo final

/* * main.h * * Created on: 05/07/2013 * Author: volney */

#ifndef MAIN_H_#define MAIN_H_

#include <unistd.h>#include <iostream>#include <fstream>#include <cstring>#include <vector>#include <stdlib.h>#include <windows.h>#include <algorithm>#include <iomanip>#include "temperatura.h"#include "rs232class.h"

using namespace std;

void mostrar_valores(const vector<Temperatura> &);void grabar_valores(const vector<Temperatura> &);void fcarga_valores(vector<Temperatura> &);void modif_valor(vector<Temperatura> &);void borrar_valor(vector<Temperatura> &);void hord_valor(vector<Temperatura> &);void tord_valor(vector<Temperatura> &);void cargar_valores(vector<Temperatura> &);

bool ordenacion_temp(Temperatura,Temperatura);bool ordenacion_hora(Temperatura,Temperatura);

Page 15: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Main.cc

#endif /* MAIN_H_ */

/* * main.cc * * Created on: 26/06/2013 * Author: volney */#include "main.h"

int main(void){vector<Temperatura> datos;int numero;do{

cout<<"\t\t\t Menu:"<<endl;cout<<"\t 1- Leer valores del kit kz80"<<endl;cout<<"\t 2- Mostrar valores "<<endl;cout<<"\t 3- Grabar valores en disco"<<endl;cout<<"\t 4- Cargar valores de disco"<<endl;cout<<"\t 5- modificar datos por consola"<<endl;cout<<"\t 6- Borrar datos"<<endl;cout<<"\t 7- Ordenar por hora"<<endl;cout<<"\t 8- Ordenar por temperatura"<<endl;cout<<"\t 9- Salir"<<endl;cout<<"\t Ingrese opcion :";

cin>> numero;switch(numero){

case 1:cargar_valores(datos);break;

case 2:mostrar_valores(datos);break;

case 3:grabar_valores(datos);break;

case 4:fcarga_valores(datos);break;

case 5:modif_valor(datos);break;

case 6:borrar_valor(datos);

Page 16: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

break;case 7:

hord_valor(datos);break;

case 8:tord_valor(datos);break;

}

}while(numero != 9);cout <<"\n\n\t\t -El programa termino normalmente.."<<endl;return 0;

}

void cargar_valores(vector<Temperatura> &newdatos){char cadena[100];int i;char puerta[5];float tmp;BOOL timeout;BOOL bRes;BYTE byte;cout <<"\n\t-Ingrese puerta COM:";cin >> puerta;rs232class sesion(puerta,CBR_9600,8,NOPARITY,TWOSTOPBITS,5000);sesion.SerialSendByte(0x33);Temperatura newtemperatura;tiempo tempo;i=0;do{

bRes=sesion.SerialReceiveByte(&byte,&timeout);if (timeout){

break;} else {if(byte==0x0a)

{newtemperatura.set_tiempo(tempo);newtemperatura.set_temperatura((double)tmp);cout<<newtemperatura;newdatos.push_back(newtemperatura);while(i>0){

cadena[i--]=0x00;}}

cadena[i++]=byte;sscanf(cadena,"%d,%d,%d,%d,

%f",&tempo.newDia,&tempo.newHora,&tempo.newMinuto,&tempo.newSegundo,&tmp);

Page 17: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

} }while(bRes);

}

void mostrar_valores(const vector<Temperatura> &temp){unsigned long int max=temp.size();for(unsigned long int i=0;i<max;i++){

cout <<i<<") - ";cout.fill('0');cout << temp[i];

}}

void grabar_valores(const vector<Temperatura> &temp){ofstream fichero;char nombre_fichero[200];cout<<"\n\t -Ingrese nombre fichero:";cin >>nombre_fichero;fichero.open(nombre_fichero);long int max=temp.size();for(long int i=0;i<max;i++){

fichero << temp[i];}fichero.close();

}void fcarga_valores(vector<Temperatura> &newDatos){

ifstream fichero;char nombre_fichero[200];cout<<"\n\t -Ingrese nombre fichero:";cin >>nombre_fichero;fichero.open(nombre_fichero);if(!fichero.good())

{cerr << "Error: No puede abrirse archivo " << nombre_fichero << endl;return;}

Temperatura temp;while(!fichero.eof())

{fichero >> temp;newDatos.push_back(temp);}

fichero.close();}

Page 18: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

void modif_valor(vector<Temperatura> &temp){int i;Temperatura temporal;cout<<"\n\t -Ingrese fila a modificar :";cin >> i;temp.erase(temp.begin()+i);temp.insert(temp.begin()+i,temporal.cons_carga());

}

void borrar_valor(vector<Temperatura> &temp){long int i;cout<<"\n\t -Ingrese fila a modificar :";cin >> i;temp.erase(temp.begin()+i);

}void hord_valor(vector<Temperatura> &temp){

sort(temp.begin(),temp.end(),ordenacion_hora);mostrar_valores(temp);

}

void tord_valor(vector<Temperatura> &temp){sort(temp.begin(),temp.end(),ordenacion_temp);mostrar_valores(temp);

}

bool ordenacion_temp(Temperatura temp1,Temperatura temp2){

return temp1.get_temperatura()<temp2.get_temperatura(); // ordenacion descendente}

bool ordenacion_hora(Temperatura temp1,Temperatura temp2){

return (temp1.get_tiempo_lineal()<temp2.get_tiempo_lineal()); // ordenacion descendente}

Rs232class.h

/*

Page 19: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

* rs232class.h * * Created on: 03/07/2013 * Author: volney */#include <windows.h>#include <iostream>#ifndef rs232_INCLUDED#define rs232_INCLUDED

class rs232class {private:

HANDLE hPort;BOOL bRes;BYTE byte;BOOL timeout;DCB dcbPort; // Port

configurationCOMMTIMEOUTS commTimeouts; // Port TimeoutsDWORD dwError; // Error

code

public:// Open Serial portrs232class( char *psPort, // "COM1","COM2"

DWORD bBaudRate, // CBR_9600, CBR_19200. CBR_56000

BYTE bByteSize, // 7,8BYTE bParity, // NOPARITY, EVENPARITY,

ODDPARITYBYTE bStopBits, // ONESTOPBIT,

ONE5STOPBITS, TWOSTOPBITSDWORD ReadTimeout // Programmable Read

Timeout );

~rs232class(){CloseSerialPort(hPort);}

// Send a byteBOOL SerialSendByte(BYTE byte);// return TRUE: Send OK

// Receive a byteBOOL SerialReceiveByte(BYTE *pbyte, BOOL *pTimeout);// return TRUE & *pTimeout TRUE Send OK// return TRUE & *pTimeout FALSE Timeout// return FALSE Receive Error

Page 20: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

// Close Serial PortBOOL CloseSerialPort(HANDLE hPort);

};#endif

Rs232class.cpp

/* * rs232class.cpp * * Created on: 03/07/2013 * Author: volney */

#include "rs232class.h"using namespace std;

rs232class::rs232class( char *psPort, // "COM1","COM2"DWORD dwBaudRate, // CBR_9600, CBR_19200.

CBR_56000BYTE bByteSize, // 7,8BYTE bParity, // NOPARITY, EVENPARITY,

ODDPARITYBYTE bStopBits, // ONESTOPBIT,

ONE5STOPBITS, TWOSTOPBITSDWORD Timeout // Timeout

){

// Open Serial PorthPort=CreateFile(

psPort, // pointer to name of the file

GENERIC_READ | GENERIC_WRITE, // access (read-write) mode

0, // share mode: 0 the object cannot be share

NULL, // pointer to security attributes: NULL the handle cannot be inherited

OPEN_EXISTING, // how to create: Comx exist

Page 21: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

0, // file/port attributes

NULL); // handle to file/port with attributes to copy

// If the function fails, the return value

//isINVALID_HANDLE_VALUE

if ( hPort == INVALID_HANDLE_VALUE ) {dwError = GetLastError (); // Flush error code

}

// Set Port Configuration

// Delete DCB configurationFillMemory(&dcbPort, sizeof(dcbPort), 0);dcbPort.DCBlength = sizeof(dcbPort);

// Current DCB in use for the communications portGetCommState (hPort, &dcbPort);

// Update DCB with new parametersdcbPort.BaudRate = dwBaudRate;dcbPort.ByteSize = bByteSize;dcbPort.Parity = bParity;dcbPort.StopBits = bStopBits;

// Fixed parameters (Disable XON-XOFF and modem handshake)dcbPort.fBinary = TRUE; // Binary mode; no EOF checkdcbPort.fParity = TRUE; // Enable parity checkingdcbPort.fOutxCtsFlow = FALSE; // No CTS output flow controldcbPort.fOutxDsrFlow = FALSE; // No DSR output flow controldcbPort.fDtrControl = DTR_CONTROL_ENABLE;

// DTR flow control type

// Raises the DTR line when the device is opened

dcbPort.fDsrSensitivity = FALSE; // DSR sensitivitydcbPort.fTXContinueOnXoff = TRUE; // XOFF continues TxdcbPort.fOutX = FALSE; // No XON/XOFF out flow controldcbPort.fInX = FALSE; // No XON/XOFF in flow controldcbPort.fErrorChar = FALSE; // Disable error replacementdcbPort.fNull = FALSE; // Disable null strippingdcbPort.fRtsControl = RTS_CONTROL_ENABLE;

// RTS flow control

Page 22: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

// Raises the RTS line when the device is opened

dcbPort.fAbortOnError = FALSE; // Do not abort reads/writes on//

error// Set new configurationif (!SetCommState (hPort, &dcbPort)) {

dwError = GetLastError (); // Flush error codeCloseSerialPort(hPort);hPort = INVALID_HANDLE_VALUE;

}

// Set Port Timeouts// Timeouts preparation MORE INFORMATION IN WIN32 API: COMMTIMEOUTScommTimeouts.ReadIntervalTimeout = 0; // Specifies the maximum

time, in milliseconds, allowed to elapse between the arrival

// of two characters on the communications line

// A value of zero indicates that interval time-outs are not used.commTimeouts.ReadTotalTimeoutMultiplier = 50; // Specifies the multiplier, in

milliseconds, used to calculate

// the total time-out period for read operations.

// For each read operation, this value is multiplied

// by the requested number of bytes to be read.commTimeouts.ReadTotalTimeoutConstant = Timeout;// Specifies the constant, in

milliseconds, used to calculate the total

// time-out period for read operations

//commTimeouts.WriteTotalTimeoutMultiplier = 10; // Specifies the multiplier, in

milliseconds, used to calculate the

// total time-out period for write operations.

// For each write operation, this value is multiplied

// by the number of bytes to be written.commTimeouts.WriteTotalTimeoutConstant = 1000; // Specifies the constant, in

milliseconds, used to calculate the total time-out period

// for write operations

Page 23: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

// See de win32 api for more information// Set Timeoutsif (!SetCommTimeouts (hPort, &commTimeouts)) {

dwError = GetLastError (); // Flush error codeCloseSerialPort(hPort);hPort = INVALID_HANDLE_VALUE;

}

}

BOOL rs232class::SerialSendByte(BYTE byte){BOOL bRes;DWORD dwNumBytesWritten=0;

bRes=WriteFile(hPort, //

handle to file or serial port to write to&byte, //

pointer to data to write to file1,

// number of bytes to write&dwNumBytesWritten, // pointer

to number of bytes writtenNULL //

NULL);

if ((!bRes)||(dwNumBytesWritten!=1)){dwError = GetLastError (); // Flush error code

}return bRes;

}

BOOL rs232class::SerialReceiveByte(BYTE *pbyte,BOOL *pTimeout){BOOL bRes;DWORD lpNumberOfBytesRead=0;

*pTimeout=FALSE;bRes=ReadFile( hPort, // handle of file or

serial port to readpbyte, //

address of buffer that receives data1,

// number of bytes to read

Page 24: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

&lpNumberOfBytesRead, // address of number of bytes read

NULL // NULL

);

if (!bRes) {dwError = GetLastError (); // Flush error code

}if ((bRes)&&(lpNumberOfBytesRead==0)){

*pTimeout = TRUE;}return bRes;

}

BOOL rs232class::CloseSerialPort(HANDLE hPort){BOOL bRes;

bRes=CloseHandle(hPort);if (!bRes) {

dwError = GetLastError (); // Flush error code}return bRes;

}

Temperatura.h

/* * temperatura.h * * Created on: 26/06/2013 * Author: volney */

#include <iostream>#include <vector>#include <fstream>#include <sstream>#include <iomanip>#include "tiempo.h"

using namespace std;

#ifndef TEMPERATURA_H_

Page 25: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

#define TEMPERATURA_H_

class Temperatura {

private:tiempo newTiempo;double newTemperatura;

public:Temperatura();virtual ~Temperatura();// sobrecarga constructorTemperatura(tiempo,double);Temperatura cons_carga(void);friend ostream& operator << (ostream& fs,const Temperatura& temp){

fs <<setw(2) <<temp.newTiempo.newDia <<"/"<<setw(2) << temp.newTiempo.newHora <<":"<<setw(2) << temp.newTiempo.newMinuto <<":"<<setw(2) << temp.newTiempo.newSegundo <<"-"<< temp.newTemperatura << endl;

return fs;

}

friend istream& operator >> (istream& fs,Temperatura& temp){char aux;fs >>temp.newTiempo.newDia >>aux >> temp.newTiempo.newHora >>aux

>> temp.newTiempo.newMinuto >>aux >> temp.newTiempo.newSegundo >>aux >> temp.newTemperatura;

return fs;

}

//funciones de acceso a variables

double get_temperatura() const;tiempo get_tiempo() const;unsigned long int get_tiempo_lineal();void set_tiempo(tiempo&);void set_temperatura(double);

};

#endif /* TEMPERATURA_H_ */

Temperatura.cpp

Page 26: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/* * temperatura.cpp * * Created on: 26/06/2013 * Author: volney */

#include "temperatura.h"#include "tiempo.h"#include <vector>using namespace std;Temperatura::Temperatura() {

// TODO Auto-generated constructor stubnewTiempo.newDia=0;newTiempo.newHora=0;newTiempo.newMinuto=0;newTiempo.newSegundo=0;newTemperatura=0;}

Temperatura::~Temperatura() {// TODO Auto-generated destructor stub

}

Temperatura::Temperatura(tiempo tempo, double temperatura){

newTiempo=tempo;newTemperatura=temperatura;

}

tiempo Temperatura::get_tiempo() const{

return (newTiempo);}

double Temperatura::get_temperatura() const{return(newTemperatura);

}

void Temperatura::set_tiempo(tiempo& tempo){

newTiempo=tempo;

}

void Temperatura::set_temperatura(double temperatura){newTemperatura=temperatura;

Page 27: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

}

unsigned long int Temperatura::get_tiempo_lineal() {

return newTiempo.get_lineal();

}

Temperatura Temperatura::cons_carga(void){char auxChar;double tmp;tiempo t2;Temperatura t1;cout << "\n\n\t\t -ingrese <dia/hora:minuto:segundo-temperatura>";cin >> t2.newDia

>>auxChar>>t2.newHora>>auxChar>>t2.newMinuto>>auxChar>>t2.newSegundo>>auxChar>>tmp;

t1.newTiempo=t2;t1.newTemperatura=(double)tmp;return t1;

}

Tiempo.h

/* * tiempo.h * * Created on: 02/07/2013 * Author: volney */

#ifndef TIEMPO_H_#define TIEMPO_H_#include <sstream>#include <iostream>using namespace std;

struct tiempo{int newDia;int newHora;int newMinuto;int newSegundo;void cargar();void mostrar();unsigned long int get_lineal();

Page 28: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

friend istringstream& operator >>(istringstream& fs, tiempo& tempo ){char aux;fs >> tempo.newDia>>aux >> tempo.newHora >>aux >> tempo.newMinuto

>>aux >> tempo.newSegundo ;return fs;

}friend ostringstream& operator << (ostringstream& os,const tiempo& tempo){

os <<tempo.newDia <<"/"<< tempo.newHora <<":"<< tempo.newMinuto <<":"<< tempo.newSegundo <<" ";

return(os);}

};

#endif /* TIEMPO_H_ */

Tiempo.cpp

/* * tiempo.cpp * * Created on: 05/07/2013 * Author: volney */#include "tiempo.h"

unsigned long int tiempo::get_lineal(){

return (newSegundo+(newMinuto*60)+(newHora*3600)+(newDia*86400));

}

Page 29: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

Código fuente sender

#include <stdlib.h>//#include <stdio.h>#include <unistd.h>#include "rs232.h"#include <iostream>#include <fstream>#include "intelhexclass.h"#include <windows.h>using namespace std;#define maxchar 4096int sendbasic( char *nombre,int);int sendintel( char *nombre,int);void usage(){

exit (EXIT_FAILURE);}int main(int argc, char **argv)

{int status=0,port_comm;if (argc==4)

{port_comm=atoi(argv[3]);if (strcmp (argv[2],"--bas") == 0)

status= sendbasic(argv[1],port_comm);if (strcmp (argv[2],"--com") == 0)

status= sendintel(argv[1],port_comm);return (status);}else

{cout << "Debe ingresar: \n nombre_archivo \n '--basic' para enviar codigo basic \n '--com' para enviar ejecutable C/PM\n n <1...9>(windows) o <0....10> (linux) puertos com" << endl;}

return(0);}

int sendbasic(char *nombre,int port_comm) {

unsigned char rbuf[maxchar];char buf[maxchar];FILE *f = fopen(nombre, "r");if (f==NULL)

{ perror ("Error"); return -1;}

rs232class sesion(port_comm,9600);

sesion.disableDTR();sesion.disableRTS();while(fgets((char *)buf,maxchar,f)!= NULL)

{

Page 30: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

sesion << buf;sesion >> rbuf;cout << buf;usleep(500);

}usleep(100000);

fclose(f);return (0);

}

int sendintel( char *nombre,int port_comm) {

ifstream file;intelhex buffer;

file.open(nombre,ios::in | ios::binary);if(!file.good())

{ std::cerr << "Error: No puede abrirse archivo " << nombre <<

std::endl; return (-1); }buffer.begin();buffer.jumpTo(256);while (!file.eof()) { buffer.insertData(file.get()); } file.close(); ofstream sfile; sfile.open("temp.hex"); buffer.jumpTo(256); sfile << buffer; sfile.close(); unsigned char buf[maxchar],rbuf[maxchar]; rs232class sesion(port_comm,9600);

FILE *f = fopen("temp.hex", "r"); if (f==NULL) { perror ("Error"); return -1; }

sesion.disableDTR(); sesion.disableRTS(); sesion.SendByte(0x43); usleep(100000); sesion >> rbuf; usleep(100000); cout << rbuf << endl;

while(fgets((char *)buf,maxchar,f)!= NULL)

Page 31: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

{ sesion << buf;

cout << buf; } sesion >> rbuf; usleep(100000); sesion.SendByte(0x65); sesion >> rbuf; cout << rbuf; usleep(100000); sesion.SendByte(0x30); sesion.SendByte(0x31); sesion.SendByte(0x30); sesion.SendByte(0x30); usleep(100000); sesion >> rbuf; cout << rbuf; //sesion.~rs232class(); fclose(f); return(0);

}

Intelhexclass.h

/******************************************************************************* * intelhexclass - class definitions * * * * A class to handle the encoding and decoding of an Intel HEX format file as * * generated by many tool chains for embedded processors and microcontrollers. * * * * This class is constructed based upon the definition given in the document * * 'Hexadecimal Object File Format Specification', Revision A, January 6, 1988, * * © 1998 Intel Corporation * *------------------------------------------------------------------------------* * class intelhex * * Member Functions: * * * *******************************************************************************/ /******************************************************************************* * * CIRCULAR BUFFER MODULE * *******************************************************************************/ /******************************************************************************/ /******************************************************************************* * * INTEL HEX CLASS MODULE

Page 32: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

* *******************************************************************************/ #ifndef INTELHEXCLASS_MODULE_PRESENT__ #define INTELHEXCLASS_MODULE_PRESENT__ /******************************************************************************* * INCLUDE FILES *******************************************************************************/ #include <iostream> #include <map> #include <list>// #include "intelhexclass.cpp" /******************************************************************************* * EXTERNS *******************************************************************************/ /******************************************************************************* * DEFAULT CONFIGURATION *******************************************************************************/ /******************************************************************************* * DEFINES *******************************************************************************/ using namespace std; /******************************************************************************/ class intelhex { /**********************************************************************/ friend ostream& operator<<(ostream& dataOut, intelhex& ihLocal); /**********************************************************************/ friend istream& operator>>(istream& dataIn, intelhex& ihLocal); private: /**********************************************************************/ map<unsigned long, unsigned char> ihContent; /**********************************************************************/ map<unsigned long, unsigned char>::iterator ihIterator; /**********************************************************************/ pair<map<unsigned long, unsigned char>::iterator,bool> ihReturn;

Page 33: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/**********************************************************************/ unsigned long segmentBaseAddress; /**********************************************************************/ struct { unsigned short csRegister; unsigned short ipRegister; bool exists; } startSegmentAddress; /**********************************************************************/ struct { unsigned long eipRegister; bool exists; } startLinearAddress; /**********************************************************************/ struct { list<string> ihWarnings; unsigned long noOfWarnings; } msgWarning; /**********************************************************************/ struct { list<string> ihErrors; unsigned long noOfErrors; } msgError; /**********************************************************************/ bool foundEof; /**********************************************************************/ bool verbose; /**********************************************************************/ bool segmentAddressMode; /*********************************************************************** * \brief Converts a 2 char string to its HEX value. * * Converts a two byte string to its equivalent value in hexadecimal * * \param value - a two character, valid ASCII representation of * a hexadecimal value * * \retval 'value' valid - 8-bit value

Page 34: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

* \retval 'value' invalid - 0x00 and calls addWarning() * * \note * This function will post a warning message using the warning handling * system addWarning() if: * -# The string contains anything other that exactly two characters * -# The string contains anything other than the characters 0-9, a-f * and A-F * * \sa * ulToHexString(), ucToHexString(), ulToString() ***********************************************************************/ unsigned char stringToHex(string value); /*********************************************************************** * \brief Converts an unsigned long to a string in HEX format. * * Takes the received paramter and converts it into its equivalent value * represented in ASCII and formatted in hexadecimal. Return value is an * 8 character long string, prefaced with '0's where necessary. * * \param value - a value between 0x0000000 and 0xFFFFFFFF * * \retval - 8-character long string * * \note * Alpha characters are capitalised. * * \sa * stringToHex(), ucToHexString(), ulToString() ***********************************************************************/ string ulToHexString(unsigned long value); /**********************************************************************/ string ucToHexString(unsigned char value); /**********************************************************************/ string ulToString(unsigned long value); /**********************************************************************/ void decodeDataRecord(unsigned char recordLength, unsigned long loadOffset, string::const_iterator data); /**********************************************************************/ void addWarning(string warningMessage); /**********************************************************************/

Page 35: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

void addError(string errorMessage); public: /**********************************************************************/ intelhex() { /* Initialise the segment base address to zero */ segmentBaseAddress = 0; /* Clear content of register variables used with the 'Start Segment' * and 'Start Linear' address records */ startSegmentAddress.ipRegister = 0; startSegmentAddress.csRegister = 0; startSegmentAddress.exists = false; startLinearAddress.eipRegister = 0; startLinearAddress.exists = false; /* Set up error and warning handling variables */ msgWarning.noOfWarnings = 0; msgError.noOfErrors = 0; /* Note that the EOF record has not been found yet */ foundEof = false; /* Set verbose mode to off */ verbose = false; /* Set segment address mode to false (default) */ segmentAddressMode = false; } /**********************************************************************/ ~intelhex() { /* Currently nothing */ } /**********************************************************************/ intelhex(const intelhex &ihSource) { /* Initialise the segment base address */ segmentBaseAddress = ihSource.segmentBaseAddress; /* Initialise content of register variables used with the 'Start Segment' * and 'Start Linear' address records */ startSegmentAddress.ipRegister = ihSource.startSegmentAddress.ipRegister; startSegmentAddress.csRegister = ihSource.startSegmentAddress.csRegister; startSegmentAddress.exists = ihSource.startSegmentAddress.exists; startLinearAddress.eipRegister = ihSource.startLinearAddress.eipRegister; startLinearAddress.exists = ihSource.startLinearAddress.exists; /* Set up error and warning handling variables */ msgWarning.noOfWarnings = ihSource.msgWarning.noOfWarnings; msgWarning.ihWarnings = ihSource.msgWarning.ihWarnings; msgError.noOfErrors = ihSource.msgError.noOfErrors;

Page 36: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

msgError.ihErrors = ihSource.msgError.ihErrors; /* Note that the EOF record has not been found yet */ foundEof = ihSource.foundEof; /* Set verbose mode to off */ verbose = ihSource.verbose; /* Set segment address mode to false (default) */ segmentAddressMode = ihSource.segmentAddressMode; /* Copy HEX file content variables */ ihContent = ihSource.ihContent; ihIterator = ihSource.ihIterator; } /**********************************************************************/ intelhex& operator= (const intelhex &ihSource) { /* Check that we are not trying to assign ourself to ourself */ /* i.e. are the source/destination addresses the same like */ /* myData = myData; */ if (this == &ihSource) return *this; /* Initialise the segment base address */ segmentBaseAddress = ihSource.segmentBaseAddress; /* Initialise content of register variables used with the 'Start Segment' * and 'Start Linear' address records */ startSegmentAddress.ipRegister = ihSource.startSegmentAddress.ipRegister; startSegmentAddress.csRegister = ihSource.startSegmentAddress.csRegister; startSegmentAddress.exists = ihSource.startSegmentAddress.exists; startLinearAddress.eipRegister = ihSource.startLinearAddress.eipRegister; startLinearAddress.exists = ihSource.startLinearAddress.exists; /* Set up error and warning handling variables */ msgWarning.noOfWarnings = ihSource.msgWarning.noOfWarnings; msgWarning.ihWarnings = ihSource.msgWarning.ihWarnings; msgError.noOfErrors = ihSource.msgError.noOfErrors; msgError.ihErrors = ihSource.msgError.ihErrors; /* Note that the EOF record has not been found yet */ foundEof = ihSource.foundEof; /* Set verbose mode to off */ verbose = ihSource.verbose; /* Set segment address mode to false (default) */ segmentAddressMode = ihSource.segmentAddressMode; /* Copy HEX file content variables */ ihContent = ihSource.ihContent; ihIterator = ihSource.ihIterator; return *this; }

Page 37: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/**********************************************************************/ void begin() { if (ihContent.size() != 0) { map<unsigned long, unsigned char>::iterator it; it = ihContent.begin(); segmentBaseAddress = (*it).first; } } /**********************************************************************/ void end() { if (ihContent.size() != 0) { map<unsigned long, unsigned char>::reverse_iterator rit; rit = ihContent.rbegin(); segmentBaseAddress = (*rit).first; } } /**********************************************************************/ void jumpTo(unsigned long address) { segmentBaseAddress = address; } /**********************************************************************/ unsigned long currentAddress() { return segmentBaseAddress; } /**********************************************************************/ bool startAddress(unsigned long * address) { if (ihContent.size() != 0) { map<unsigned long, unsigned char>::iterator it; it = ihContent.begin(); *address = (*it).first; return true; } return false; }

Page 38: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/**********************************************************************/ bool endAddress(unsigned long * address) { if (ihContent.size() != 0) { map<unsigned long, unsigned char>::reverse_iterator rit; rit = ihContent.rbegin(); *address = (*rit).first; return true; } return false; } bool getData(unsigned char * data); bool getData(unsigned char * data, unsigned long address); /**********************************************************************/ bool insertData(unsigned char data) { ihReturn=ihContent.insert(pair<int,unsigned char>(segmentBaseAddress++, data)); return true; } bool insertData(unsigned char data, unsigned long address); void overwriteData(unsigned char data); void overwriteData(unsigned char data, unsigned long address); bool blankFill(unsigned char data); bool blankFill(unsigned char * const data, unsigned long sizeOfData); void blankFill(unsigned char * const data, unsigned long sizeOfData, unsigned long endAddress); bool blankFillRandom(); void blankFillRandom(unsigned long endAddress); bool blankFillAddressLowByte(); void blankFillAddressLowByte(unsigned long endAddress); /**********************************************************************/ unsigned long getNoWarnings() {

Page 39: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

return msgWarning.noOfWarnings; } /**********************************************************************/ unsigned long getNoErrors() { return msgError.noOfErrors; } /**********************************************************************/ bool popNextWarning(string& warning) { if (msgWarning.noOfWarnings > 0) { warning = msgWarning.ihWarnings.front(); msgWarning.ihWarnings.pop_front(); msgWarning.noOfWarnings = msgWarning.ihWarnings.size(); return true; } else { return false; } } /**********************************************************************/ bool popNextError(string& error) { if (msgError.noOfErrors > 0) { error = msgError.ihErrors.front(); msgError.ihErrors.pop_front(); msgError.noOfErrors = msgError.ihErrors.size(); return true; } else { return false; } } /**********************************************************************/

Page 40: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

bool getStartSegmentAddress(unsigned short * ipRegister, unsigned short * csRegister) { if (startSegmentAddress.exists == true) { *ipRegister = startSegmentAddress.ipRegister; *csRegister = startSegmentAddress.csRegister; } return startSegmentAddress.exists; } /**********************************************************************/ bool getStartLinearAddress(unsigned long * eipRegister) { if (startLinearAddress.exists == true) { *eipRegister = startLinearAddress.eipRegister; } return startLinearAddress.exists; } /**********************************************************************/ void setStartSegmentAddress(unsigned short ipRegister, unsigned short csRegister) { startSegmentAddress.ipRegister = ipRegister; startSegmentAddress.csRegister = csRegister; startSegmentAddress.exists = true; } /**********************************************************************/ void setStartLinearAddress(unsigned long eipRegister) { startLinearAddress.eipRegister = eipRegister; startLinearAddress.exists = true; } /**********************************************************************/ void segmentAddressingOn() { segmentAddressMode = true; } /**********************************************************************/ void linearAddressingOn() {

Page 41: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

segmentAddressMode = false; } /**********************************************************************/ void verboseOn() { verbose = true; } /**********************************************************************/ void verboseOff() { verbose = false; } }; #endif

Intelhexclass.cpp

/******************************************************************************* * * INTEL HEX FILE CLASS MODULE * *******************************************************************************/ /******************************************************************************/ #include <iostream> #include <string> #include <vector> #include <cstdio> #include "intelhexclass.h" using namespace std; /******************************************************************************/ enum intelhexRecordType { DATA_RECORD, END_OF_FILE_RECORD, EXTENDED_SEGMENT_ADDRESS, START_SEGMENT_ADDRESS, EXTENDED_LINEAR_ADDRESS, START_LINEAR_ADDRESS, NO_OF_RECORD_TYPES };

Page 42: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/******************************************************************************* * Converts a 2 char string to its HEX value *******************************************************************************/ unsigned char intelhex::stringToHex(string value) { unsigned char returnValue = 0; string::iterator valueIterator; if(value.length() == 2) { valueIterator = value.begin(); for (int x=0; x < 2; x++) { /* Shift result variable 4 bits to the left */ returnValue <<= 4; if (*valueIterator >= '0' && *valueIterator <= '9') { returnValue += static_cast<unsigned char>(*valueIterator - '0'); } else if (*valueIterator >= 'A' && *valueIterator <= 'F') { returnValue += static_cast<unsigned char>(*valueIterator - 'A' + 10); } else if (*valueIterator >= 'a' && *valueIterator <= 'f') { returnValue += static_cast<unsigned char>(*valueIterator - 'a' + 10); } else { /* Error occured - non-HEX value found */ string message; message = "Can't convert byte 0x" + value + " @ 0x" + ulToHexString(segmentBaseAddress) + " to hex."; addError(message); returnValue = 0; } /* Iterate to next char in the string */ ++valueIterator; }

Page 43: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

} else { /* Error occured - more or less than two nibbles in the string */ string message; message = value + " @ 0x" + ulToHexString(segmentBaseAddress) + " isn't an 8-bit value."; addError(message); } return returnValue; } /******************************************************************************* * Converts an unsigned long to a string in HEX format *******************************************************************************/ string intelhex::ulToHexString(unsigned long value) { string returnString; char localString[50]; returnString.erase(); snprintf(localString, 49, "%08lX", value); returnString.insert(0, localString); return returnString; } /******************************************************************************* * Converts an unsigned long to a string in DEC format *******************************************************************************/ string intelhex::ulToString(unsigned long value) { string returnString; char localString[50]; returnString.erase(); snprintf(localString, 49, "%lu", value); returnString.insert(0, localString); return returnString; }

Page 44: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/******************************************************************************* * Converts an unsigned char to a string in HEX format *******************************************************************************/ string intelhex::ucToHexString(unsigned char value) { string returnString; char localString[50]; returnString.erase(); snprintf(localString, 49, "%02X", value); returnString.insert(0, localString); return returnString; } /******************************************************************************* * Adds a warning to the list of warning messages *******************************************************************************/ void intelhex::addWarning(string warningMessage) { string localMessage; /* Build the message and push the warning message onto the list */ localMessage += ulToString(msgWarning.noOfWarnings + 1) + " Warning: " + warningMessage; msgWarning.ihWarnings.push_back(localMessage); /* Update the number of warning messages */ msgWarning.noOfWarnings = msgWarning.ihWarnings.size(); } /******************************************************************************* * Adds an error to the list of error messages *******************************************************************************/ void intelhex::addError(string errorMessage) { string localMessage; /* Build the message and push the error message onto the list */ localMessage += ulToString(msgError.noOfErrors + 1) + " Error: " + errorMessage; msgError.ihErrors.push_back(localMessage);

Page 45: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/* Update the number of error messages */ msgError.noOfErrors = msgError.ihErrors.size(); } /******************************************************************************* * Decodes a data record read in from a file *******************************************************************************/ void intelhex::decodeDataRecord(unsigned char recordLength, unsigned long loadOffset, string::const_iterator data) { /* Variable to store a byte of the record as a two char string */ string sByteRead; /* Variable to store the byte of the record as an u.char */ unsigned char byteRead; /* Calculate new SBA by clearing the low four bytes and then adding the */ /* current loadOffset for this line of Intel HEX data */ segmentBaseAddress &= ~(0xFFFFUL); segmentBaseAddress += loadOffset; for (unsigned char x = 0; x < recordLength; x ++) { sByteRead.erase(); sByteRead = *data; data++; sByteRead += *data; data++; byteRead = stringToHex(sByteRead); ihReturn=ihContent.insert( pair<int,unsigned char>(segmentBaseAddress, byteRead)); if (ihReturn.second==false) { /* If this address already contains the byte we are trying to */ /* write, this is only a warning */ if (ihReturn.first->second == byteRead) { string message; message = "Location 0x" + ulToHexString(segmentBaseAddress) + " already contains data 0x" + sByteRead; addWarning(message);

Page 46: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

} /* Otherwise this is an error */ else { string message; message = "Couldn't add 0x" + sByteRead + " @ 0x" + ulToHexString(segmentBaseAddress) + "; already contains 0x" + ucToHexString(ihReturn.first->second); addError(message); } } /* Increment the segment base address */ ++segmentBaseAddress; } } /******************************************************************************* * Input Stream for Intel HEX File Decoding (friend function) *******************************************************************************/ istream& operator>>(istream& dataIn, intelhex& ihLocal) { // Create a string to store lines of Intel Hex info string ihLine; /* Create a string to store a single byte of Intel HEX info */ string ihByte; // Create an iterator for this variable string::iterator ihLineIterator; // Create a line counter unsigned long lineCounter = 0; // Variable to hold a single byte (two chars) of data unsigned char byteRead; // Variable to calculate the checksum for each line unsigned char intelHexChecksum; // Variable to hold the record length unsigned char recordLength; // Variable to hold the load offset unsigned long loadOffset; // Variables to hold the record type intelhexRecordType recordType; do { /* Clear the string before this next round */ ihLine.erase();

Page 47: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/* Clear the checksum before processing this line */ intelHexChecksum = 0; /* Get a line of data */ dataIn >> ihLine; /* If the line contained some data, process it */ if (ihLine.length() > 0) { /* Increment line counter */ lineCounter++; /* Set string iterator to start of string */ ihLineIterator = ihLine.begin(); /* Check that we have a ':' record mark at the beginning */ if (*ihLineIterator != ':') { /* Add some warning code here */ string message; message = "Line without record mark ':' found @ line " + ihLocal.ulToString(lineCounter); ihLocal.addWarning(message); } else { /* Remove the record mark from the string as we don't need it */ /* anymore */ ihLine.erase(ihLineIterator); } /* Run through the whole line to check the checksum */ for (ihLineIterator = ihLine.begin(); ihLineIterator != ihLine.end(); /* Nothing - really! */ ) { /* Convert the line in pair of chars (making a single byte) */ /* into single bytes, and then add to the checksum variable. */ /* By adding all the bytes in a line together *including* the */ /* checksum byte, we should get a result of '0' at the end. */ /* If not, there is a checksum error */ ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator;

Page 48: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/* Just in case there are an odd number of chars in the */ /* just check we didn't reach the end of the string early */ if (ihLineIterator != ihLine.end()) { ihByte += *ihLineIterator; ++ihLineIterator; byteRead = ihLocal.stringToHex(ihByte); intelHexChecksum += byteRead; } else { string message; message = "Odd number of characters in line " + ihLocal.ulToString(lineCounter); ihLocal.addError(message); } } /* Make sure the checksum was ok */ if (intelHexChecksum == 0) { /* Reset iterator back to beginning of the line so we can now */ /* decode it */ ihLineIterator = ihLine.begin(); /* Clear all the variables associated with decoding a line of */ /* Intel HEX code. */ recordLength = 0; loadOffset = 0; /* Get the record length */ ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; recordLength = ihLocal.stringToHex(ihByte); /* Get the load offset (2 bytes) */ ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator;

Page 49: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

loadOffset = static_cast<unsigned long>(ihLocal.stringToHex(ihByte)); loadOffset <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; loadOffset += static_cast<unsigned long>(ihLocal.stringToHex(ihByte)); /* Get the record type */ ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; recordType = static_cast<intelhexRecordType>(ihLocal.stringToHex(ihByte)); /* Decode the INFO or DATA portion of the record */ switch (recordType) { case DATA_RECORD: ihLocal.decodeDataRecord(recordLength, loadOffset, ihLineIterator); if (ihLocal.verbose == true) { cout << "Data Record begining @ 0x" << ihLocal.ulToHexString(loadOffset) << endl; } break; case END_OF_FILE_RECORD: /* Check that the EOF record wasn't already found. If */ /* it was, generate appropriate error */ if (ihLocal.foundEof == false) { ihLocal.foundEof = true; } else { string message; message = "Additional End Of File record @ line " + ihLocal.ulToString(lineCounter) + " found.";

Page 50: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

ihLocal.addError(message); } /* Generate error if there were */ if (ihLocal.verbose == true) { cout << "End of File" << endl; } break; case EXTENDED_SEGMENT_ADDRESS: /* Make sure we have 2 bytes of data */ if (recordLength == 2) { /* Extract the two bytes of the ESA */ unsigned long extSegAddress = 0; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; extSegAddress = static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); extSegAddress <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; extSegAddress += static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); /* ESA is bits 4-19 of the segment base address */ /* (SBA), so shift left 4 bits */ extSegAddress <<= 4; /* Update the SBA */ ihLocal.segmentBaseAddress = extSegAddress; } else { /* Note the error */ string message; message = "Extended Segment Address @ line " + ihLocal.ulToString(lineCounter) + " not 2 bytes as required.";

Page 51: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

ihLocal.addError(message); } if (ihLocal.verbose == true) { cout << "Ext. Seg. Address found: 0x" << ihLocal.ulToHexString(ihLocal.segmentBaseAddress) << endl; } break; case START_SEGMENT_ADDRESS: /* Make sure we have 4 bytes of data, and that no */ /* Start Segment Address has been found to date */ if (recordLength == 4 && ihLocal.startSegmentAddress.exists == false) { /* Note that the Start Segment Address has been */ /* found. */ ihLocal.startSegmentAddress.exists = true; /* Clear the two registers, just in case */ ihLocal.startSegmentAddress.csRegister = 0; ihLocal.startSegmentAddress.ipRegister = 0; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startSegmentAddress.csRegister = static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); ihLocal.startSegmentAddress.csRegister <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startSegmentAddress.csRegister += static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startSegmentAddress.ipRegister =

Page 52: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); ihLocal.startSegmentAddress.ipRegister <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startSegmentAddress.ipRegister += static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); } /* Note an error if the start seg. address already */ /* exists */ else if (ihLocal.startSegmentAddress.exists == true) { string message; message = "Start Segment Address record appears again @ line " + ihLocal.ulToString(lineCounter) + "; repeated record ignored."; ihLocal.addError(message); } /* Note an error if the start lin. address already */ /* exists as they should be mutually exclusive */ if (ihLocal.startLinearAddress.exists == true) { string message; message = "Start Segment Address record found @ line " + ihLocal.ulToString(lineCounter) + " but Start Linear Address already exists."; ihLocal.addError(message); } /* Note an error if the record lenght is not 4 as */ /* expected */ if (recordLength != 4) { string message; message = "Start Segment Address @ line " + ihLocal.ulToString(lineCounter) + " not 4 bytes as required."; ihLocal.addError(message); }

Page 53: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

if (ihLocal.verbose == true) { cout << "Start Seg. Address - CS 0x" << ihLocal.ulToHexString(ihLocal.startSegmentAddress.csRegister) << " IP 0x" << ihLocal.ulToHexString(ihLocal.startSegmentAddress.ipRegister) << endl; } break; case EXTENDED_LINEAR_ADDRESS: /* Make sure we have 2 bytes of data */ if (recordLength == 2) { /* Extract the two bytes of the ELA */ unsigned long extLinAddress = 0; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; extLinAddress = static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); extLinAddress <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; extLinAddress += static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); /* ELA is bits 16-31 of the segment base address */ /* (SBA), so shift left 16 bits */ extLinAddress <<= 16; /* Update the SBA */ ihLocal.segmentBaseAddress = extLinAddress; } else { /* Note the error */ //cout << "Error in Ext. Lin. Address" << endl; string message; message = "Extended Linear Address @ line " +

Page 54: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

ihLocal.ulToString(lineCounter) + " not 2 bytes as required."; ihLocal.addError(message); } if (ihLocal.verbose == true) { cout << "Ext. Lin. Address 0x" << ihLocal.ulToHexString(ihLocal.segmentBaseAddress) << endl; } break; case START_LINEAR_ADDRESS: /* Make sure we have 4 bytes of data */ if (recordLength == 4 && ihLocal.startLinearAddress.exists == false) { /* Extract the four bytes of the SLA */ ihLocal.startLinearAddress.eipRegister = 0; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startLinearAddress.eipRegister = static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); ihLocal.startLinearAddress.eipRegister <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startLinearAddress.eipRegister += static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); ihLocal.startLinearAddress.eipRegister <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startLinearAddress.eipRegister += static_cast<unsigned long> (ihLocal.stringToHex(ihByte));

Page 55: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

ihLocal.startLinearAddress.eipRegister <<= 8; ihByte.erase(); ihByte = *ihLineIterator; ++ihLineIterator; ihByte += *ihLineIterator; ++ihLineIterator; ihLocal.startLinearAddress.eipRegister += static_cast<unsigned long> (ihLocal.stringToHex(ihByte)); } /* Note an error if the start seg. address already */ /* exists */ else if (ihLocal.startLinearAddress.exists == true) { string message; message = "Start Linear Address record appears again @ line " + ihLocal.ulToString(lineCounter) + "; repeated record ignored."; ihLocal.addError(message); } /* Note an error if the start seg. address already */ /* exists as they should be mutually exclusive */ if (ihLocal.startSegmentAddress.exists == true) { string message; message = "Start Linear Address record found @ line " + ihLocal.ulToString(lineCounter) + " but Start Segment Address already exists."; ihLocal.addError(message); } /* Note an error if the record lenght is not 4 as */ /* expected */ if (recordLength != 4) { string message; message = "Start Linear Address @ line " + ihLocal.ulToString(lineCounter) + " not 4 bytes as required."; ihLocal.addError(message); } if (ihLocal.verbose == true) {

Page 56: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

cout << "Start Lin. Address - EIP 0x" << ihLocal.ulToHexString(ihLocal.startLinearAddress.eipRegister) << endl; } break; default: /* Handle the error here */ if (ihLocal.verbose == true) { cout << "Unknown Record @ line " << ihLocal.ulToString(lineCounter) << endl; } string message; message = "Unknown Intel HEX record @ line " + ihLocal.ulToString(lineCounter); ihLocal.addError(message); break; } } else { /* Note that the checksum contained an error */ string message; message = "Checksum error @ line " + ihLocal.ulToString(lineCounter) + "; calculated 0x" + ihLocal.ucToHexString(intelHexChecksum - byteRead) + " expected 0x" + ihLocal.ucToHexString(byteRead); ihLocal.addError(message); } } } while (ihLine.length() > 0); if (ihLocal.verbose == true) { cout << "File contained " << lineCounter << " lines." << endl; } return(dataIn);

Page 57: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

} /******************************************************************************* * Output Stream for Intel HEX File Encoding (friend function) *******************************************************************************/ ostream& operator<<(ostream& dataOut, intelhex& ihLocal) { /* Stores the address offset needed by the linear/segment address records */ unsigned long addressOffset; /* Iterator into the ihContent - where the addresses & data are stored */ map<const unsigned long, unsigned char>::iterator ihIterator; /* Holds string that represents next record to be written */ string thisRecord; /* Checksum calculation variable */ unsigned char checksum; thisRecord.clear(); /* Check that there is some content to encode */ if (ihLocal.ihContent.size() > 0) { /* Calculate the Linear/Segment address */ ihIterator = ihLocal.ihContent.begin(); addressOffset = (*ihIterator).first; checksum = 0; /* Construct the first record to define the segment base address */ if (ihLocal.segmentAddressMode == false) { unsigned char dataByte; addressOffset >>= 16; thisRecord = ":02000004"; checksum = 0x02 + 0x04; dataByte = static_cast<unsigned char>(addressOffset & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((addressOffset >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); } else {

Page 58: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

unsigned char dataByte; addressOffset >>= 4; thisRecord = ":02000002"; checksum = 0x02 + 0x02; dataByte = static_cast<unsigned char>(addressOffset & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((addressOffset >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); } /* Output the record */ dataOut << thisRecord << endl; /* Now loop through all the available data and insert into file */ /* with maximum 16 bytes per line, and making sure to keep the */ /* segment base address up to date */ vector<unsigned char> recordData; unsigned long previousAddress; unsigned long currentAddress; unsigned long loadOffset; while(ihIterator != ihLocal.ihContent.end()) { /* Check to see if we need to start a new linear/segment section */ loadOffset = (*ihIterator).first; /* If we are using the linear mode... */ if (ihLocal.segmentAddressMode == false) { if ((loadOffset >> 16) != addressOffset) { unsigned char dataByte; thisRecord.clear(); checksum = 0; addressOffset = loadOffset; addressOffset >>= 16; thisRecord = ":02000004";

Page 59: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

checksum = 0x02 + 0x04; dataByte = static_cast<unsigned char>(addressOffset & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((addressOffset >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); /* Output the record */ dataOut << thisRecord << endl; } } /* ...otherwise assume segment mode */ else { if ((loadOffset >> 4) != addressOffset) { unsigned char dataByte; thisRecord.clear(); checksum = 0; addressOffset = loadOffset; addressOffset >>= 4; thisRecord = ":02000002"; checksum = 0x02 + 0x02; dataByte = static_cast<unsigned char>(addressOffset & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((addressOffset >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); /* Output the record */ dataOut << thisRecord << endl; } } /* Prepare for encoding next data record */

Page 60: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

thisRecord.clear(); checksum = 0; recordData.clear(); /* We need to check where the data actually starts, but only the */ /* bottom 16-bits; the other bits are in the segment/linear */ /* address record */ loadOffset = (*ihIterator).first & 0xFFFF; /* Loop through and collect up to 16 bytes of data */ for (int x = 0; x < 16; x++) { currentAddress = (*ihIterator).first & 0xFFFF; recordData.push_back((*ihIterator).second); ihIterator++; /* Check that we haven't run out of data */ if (ihIterator == ihLocal.ihContent.end()) { break; } /* Check that the next address is consecutive */ previousAddress = currentAddress; currentAddress = (*ihIterator).first & 0xFFFF; if (currentAddress != (previousAddress + 1)) { break; } /* If we got here we have a consecutive address and can keep */ /* building up the data portion of the data record */ } /* Now we should have some data to encode; check first */ if (recordData.size() > 0) { vector<unsigned char>::iterator itData; unsigned char dataByte; /* Start building data record */ thisRecord = ":"; /* Start with the RECLEN record length */ dataByte = static_cast<unsigned char>(recordData.size()); thisRecord += ihLocal.ucToHexString(dataByte);

Page 61: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

checksum += dataByte; /* Then the LOAD OFFSET */ dataByte = static_cast<unsigned char>((loadOffset >> 8) & 0xFF); thisRecord += ihLocal.ucToHexString(dataByte); checksum += dataByte; dataByte = static_cast<unsigned char>(loadOffset & 0xFF); thisRecord += ihLocal.ucToHexString(dataByte); checksum += dataByte; /* Then the RECTYP record type (no need to add to checksum - */ /* value is zero '00' */ thisRecord += "00"; /* Now we add the data */ for (itData = recordData.begin(); itData != recordData.end(); itData ++) { dataByte = (*itData); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); } /* Last bit - add the checksum */ thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); /* Now write the record */ dataOut << thisRecord << endl; } } } /* If there is a segment start address, output the data */ if (ihLocal.startSegmentAddress.exists == true) { unsigned char dataByte; thisRecord.clear(); checksum = 0; thisRecord = ":04000003"; checksum = 0x04 + 0x03; dataByte = static_cast<unsigned char>((ihLocal.startSegmentAddress.csRegister >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>(ihLocal.startSegmentAddress.csRegister & 0xFF);

Page 62: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((ihLocal.startSegmentAddress.ipRegister >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>(ihLocal.startSegmentAddress.ipRegister & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); /* Last bit - add the checksum */ thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); /* Now write the record */ dataOut << thisRecord << endl; } /* If there is a linear start address, output the data */ if (ihLocal.startLinearAddress.exists == true) { unsigned char dataByte; thisRecord.clear(); checksum = 0; thisRecord = ":04000005"; checksum = 0x04 + 0x05; dataByte = static_cast<unsigned char>((ihLocal.startLinearAddress.eipRegister >> 24) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((ihLocal.startLinearAddress.eipRegister >> 16) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>((ihLocal.startLinearAddress.eipRegister >> 8) & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte); dataByte = static_cast<unsigned char>(ihLocal.startLinearAddress.eipRegister & 0xFF); checksum += dataByte; thisRecord += ihLocal.ucToHexString(dataByte);

Page 63: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/* Last bit - add the checksum */ thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); /* Now write the record */ dataOut << thisRecord << endl; } /* Whatever happened, we can always output the EOF record */ dataOut << ":00000001FF" << endl; return (dataOut); } /******************************************************************************* * * INTEL HEX FILE CLASS MODULE END * *******************************************************************************/

Rs232.h

/****************************************************************************** Author: Teunis van Beelen** Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Teunis van Beelen** [email protected]****************************************************************************** This program is free software; you can redistribute it and/or modify* it under the terms of the GNU General Public License as published by* the Free Software Foundation version 2 of the License.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the* GNU General Public License for more details.** You should have received a copy of the GNU General Public License along* with this program; if not, write to the Free Software Foundation, Inc.,* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*****************************************************************************

Page 64: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

* This version of GPL is at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt*****************************************************************************/

/* last revision: February 1, 2013 */

/* For more info and how to use this libray, visit: http://www.teuniz.net/RS-232/ */

#ifndef rs232_INCLUDED#define rs232_INCLUDED

#ifdef __linux__

#include <termios.h>#include <sys/ioctl.h>#include <unistd.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#include <limits.h>

#else

#include <windows.h>

#endif

/******************************************************************************* * * * rs232 class modulo * * Volney Torres Almendro * *******************************************************************************/using namespace std;

class rs232class {public:

/**********************************************************************/

Page 65: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

void operator<<(unsigned char *dato){

cputs((const char *)dato);

} void operator<<(char *dato){

_cputs((const char *)dato);

}

/**********************************************************************/void operator>>(unsigned char *buf){

Status = PollComport(buf);

}

/**********************************************************************/rs232class(int puerto, int baudios){

Size = 4095;Puerto = puerto;Baudios = baudios;Status = OpenComport();

}~rs232class(){

CloseComport();}

/**********************************************************************/void bufSize(int buf){

if(buf>4096)Size=4096;elseSize=buf;

}int SendByte(unsigned char );int _SendByte(unsigned char );int SendBuf(unsigned char *);void cputs(const char *);void _cputs(const char *);int IsCTSEnabled();int IsDSREnabled();void enableDTR();void disableDTR();void enableRTS();void disableRTS();

private:

Page 66: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

int Status; // Estado del puertoint Puerto; // Puerto numeroint Baudios; // Velocidadint Size ;// medida del buffer

int OpenComport();void CloseComport();int PollComport(unsigned char *);

};

#endif

Rs232.cpp

/****************************************************************************** Author: Teunis van Beelen** Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Teunis van Beelen** [email protected]****************************************************************************** This program is free software; you can redistribute it and/or modify* it under the terms of the GNU General Public License as published by* the Free Software Foundation version 2 of the License.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the* GNU General Public License for more details.** You should have received a copy of the GNU General Public License along* with this program; if not, write to the Free Software Foundation, Inc.,* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.****************************************************************************** This version of GPL is at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt*****************************************************************************/

/* last revision: February 1, 2013 */

Page 67: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

/* For more info and how to use this libray, visit: http://www.teuniz.net/RS-232/ */

#include "rs232.h"#include <unistd.h>#include <iostream>

using namespace std;

#ifdef __linux__ /* Linux */

int Cport[30], error;

struct termios new_port_settings, old_port_settings[30];

char comports[30][16]={"/dev/ttyS0","/dev/ttyS1","/dev/ttyS2","/dev/ttyS3","/dev/ttyS4","/dev/ttyS5", "/dev/ttyS6","/dev/ttyS7","/dev/ttyS8","/dev/ttyS9","/dev/ttyS10","/dev/ttyS11", "/dev/ttyS12","/dev/ttyS13","/dev/ttyS14","/dev/ttyS15","/dev/ttyUSB0", "/dev/ttyUSB1","/dev/ttyUSB2","/dev/ttyUSB3","/dev/ttyUSB4","/dev/ttyUSB5", "/dev/ttyAMA0","/dev/ttyAMA1","/dev/ttyACM0","/dev/ttyACM1", "/dev/rfcomm0","/dev/rfcomm1","/dev/ircomm0","/dev/ircomm1"};

int rs232class::OpenComport(){ int baudr, status;

if((Puerto>29)||(Puerto<0)) { cout <<"illegal comport number\n"<<endl; return(1); }

switch(Baudios) { case 50 : baudr = B50; break; case 75 : baudr = B75; break; case 110 : baudr = B110; break; case 134 : baudr = B134;

Page 68: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

break; case 150 : baudr = B150; break; case 200 : baudr = B200; break; case 300 : baudr = B300; break; case 600 : baudr = B600; break; case 1200 : baudr = B1200; break; case 1800 : baudr = B1800; break; case 2400 : baudr = B2400; break; case 4800 : baudr = B4800; break; case 9600 : baudr = B9600; break; case 19200 : baudr = B19200; break; case 38400 : baudr = B38400; break; case 57600 : baudr = B57600; break; case 115200 : baudr = B115200; break; case 230400 : baudr = B230400; break; case 460800 : baudr = B460800; break; case 500000 : baudr = B500000; break; case 576000 : baudr = B576000; break; case 921600 : baudr = B921600; break; case 1000000 : baudr = B1000000; break; default : cout <<"illegal baudios"<<endl; return(1); break; }

Cport[Puerto] = open(comports[Puerto], O_RDWR | O_NOCTTY | O_NDELAY); if(Cport[Puerto]==-1) { perror("unable to open comport ");

Page 69: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

return(1); }

error = tcgetattr(Cport[Puerto], old_port_settings + Puerto); if(error==-1) { close(Cport[Puerto]); perror("unable to read portsettings "); return(1); } memset(&new_port_settings, 0, sizeof(new_port_settings)); /* clear the new struct */

new_port_settings.c_cflag = baudr | CS8 | CLOCAL | CREAD; new_port_settings.c_iflag = IGNPAR; new_port_settings.c_oflag = 0; new_port_settings.c_lflag = 0; new_port_settings.c_cc[VMIN] = 0; /* block untill n bytes are received */ new_port_settings.c_cc[VTIME] = 0; /* block untill a timer expires (n * 100 mSec.) */ error = tcsetattr(Cport[Puerto], TCSANOW, &new_port_settings); if(error==-1) { close(Cport[Puerto]); perror("unable to adjust portsettings "); return(1); }

if(ioctl(Cport[Puerto], TIOCMGET, &status) == -1) { perror("unable to get portstatus"); return(1); }

status |= TIOCM_DTR; /* turn on DTR */ status |= TIOCM_RTS; /* turn on RTS */

if(ioctl(Cport[Puerto], TIOCMSET, &status) == -1) { perror("unable to set portstatus"); return(1); }

return(0);}

int rs232class::PollComport(unsigned char *buf){ int n;

Page 70: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

#ifndef __STRICT_ANSI__ /* __STRICT_ANSI__ is defined when the -ansi option is usedfor gcc */ if(Size>SSIZE_MAX) Size = (int)SSIZE_MAX; /* SSIZE_MAX is defined in limits.h */#else if(Size>4096) Size = 4096;#endif

n = read(Cport[Puerto], buf, Size);

return(n);}

int rs232class::_SendByte( unsigned char byte){ int n; unsigned long int i; n = write(Cport[Puerto], &byte, 1); for(i=0;i<=80000;i++)

{i=i+i-i;} if(n<0) return(1);

return(0);}

int rs232class::SendByte( unsigned char byte){ int n; unsigned long int i; n = write(Cport[Puerto], &byte, 1); for(i=0;i<=2600000;i++)

{i=i+i-i;} if(n<0) return(1);

return(0);}

int rs232class::SendBuf( unsigned char *buf){ return(write(Cport[Puerto], buf, Size));}

void rs232class::CloseComport(){ int status;

Page 71: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

if(ioctl(Cport[Puerto], TIOCMGET, &status) == -1) { perror("unable to get portstatus"); }

status &= ~TIOCM_DTR; /* turn off DTR */ status &= ~TIOCM_RTS; /* turn off RTS */

if(ioctl(Cport[Puerto], TIOCMSET, &status) == -1) { perror("unable to set portstatus"); }

close(Cport[Puerto]); tcsetattr(Cport[Puerto], TCSANOW, old_port_settings + Puerto);}

/*Constant DescriptionTIOCM_LE DSR (data set ready/line enable)TIOCM_DTR DTR (data terminal ready)TIOCM_RTS RTS (request to send)TIOCM_ST Secondary TXD (transmit)TIOCM_SR Secondary RXD (receive)TIOCM_CTS CTS (clear to send)TIOCM_CAR DCD (data carrier detect)TIOCM_CD Synonym for TIOCM_CARTIOCM_RNG RNG (ring)TIOCM_RI Synonym for TIOCM_RNGTIOCM_DSR DSR (data set ready)*/

int rs232class::IsCTSEnabled(){ int status;

ioctl(Cport[Puerto], TIOCMGET, &status);

if(status&TIOCM_CTS) return(1); else return(0);}

int rs232class::IsDSREnabled(){ int status;

ioctl(Cport[Puerto], TIOCMGET, &status);

Page 72: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

if(status&TIOCM_DSR) return(1); else return(0);}

void rs232class::enableDTR(){ int status;

if(ioctl(Cport[Puerto], TIOCMGET, &status) == -1) { perror("unable to get portstatus"); }

status |= TIOCM_DTR; /* turn on DTR */

if(ioctl(Cport[Puerto], TIOCMSET, &status) == -1) { perror("unable to set portstatus"); }}

void rs232class::disableDTR(){ int status;

if(ioctl(Cport[Puerto], TIOCMGET, &status) == -1) { perror("unable to get portstatus"); }

status &= ~TIOCM_DTR; /* turn off DTR */

if(ioctl(Cport[Puerto], TIOCMSET, &status) == -1) { perror("unable to set portstatus"); }}

void rs232class::enableRTS(){ int status;

if(ioctl(Cport[Puerto], TIOCMGET, &status) == -1) { perror("unable to get portstatus"); }

Page 73: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

status |= TIOCM_RTS; /* turn on RTS */

if(ioctl(Cport[Puerto], TIOCMSET, &status) == -1) { perror("unable to set portstatus"); }}

void rs232class::disableRTS(){ int status;

if(ioctl(Cport[Puerto], TIOCMGET, &status) == -1) { perror("unable to get portstatus"); }

status &= ~TIOCM_RTS; /* turn off RTS */

if(ioctl(Cport[Puerto], TIOCMSET, &status) == -1) { perror("unable to set portstatus"); }}

#else /* windows */

#include <windows.h>HANDLE Cport[16];

char comports[16][10]={"\\\\.\\COM1", "\\\\.\\COM2", "\\\\.\\COM3", "\\\\.\\COM4", "\\\\.\\COM5", "\\\\.\\COM6", "\\\\.\\COM7", "\\\\.\\COM8", "\\\\.\\COM9", "\\\\.\\COM10", "\\\\.\\COM11", "\\\\.\\COM12", "\\\\.\\COM13", "\\\\.\\COM14", "\\\\.\\COM15", "\\\\.\\COM16"};

char baudr[64];

int rs232class::OpenComport(){ if((Puerto>15)||(Puerto<0)) { cout << "illegal comport number\n" << endl; return(-1); }

Page 74: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

switch(Baudios) { case 110 : strcpy(baudr, "baud=110 data=8 parity=N stop=1 dtr=on rts=on"); break; case 300 : strcpy(baudr, "baud=300 data=8 parity=N stop=1 dtr=on rts=on"); break; case 600 : strcpy(baudr, "baud=600 data=8 parity=N stop=1 dtr=on rts=on"); break; case 1200 : strcpy(baudr, "baud=1200 data=8 parity=N stop=1 dtr=on rts=on"); break; case 2400 : strcpy(baudr, "baud=2400 data=8 parity=N stop=1 dtr=on rts=on"); break; case 4800 : strcpy(baudr, "baud=4800 data=8 parity=N stop=1 dtr=on rts=on"); break; case 9600 : strcpy(baudr, "baud=9600 data=8 parity=N stop=1 dtr=on rts=on"); break; case 19200 : strcpy(baudr, "baud=19200 data=8 parity=N stop=1 dtr=on rts=on"); break; case 38400 : strcpy(baudr, "baud=38400 data=8 parity=N stop=1 dtr=on rts=on"); break; case 57600 : strcpy(baudr, "baud=57600 data=8 parity=N stop=1 dtr=on rts=on"); break; case 115200 : strcpy(baudr, "baud=115200 data=8 parity=N stop=1 dtr=on rts=on"); break; case 128000 : strcpy(baudr, "baud=128000 data=8 parity=N stop=1 dtr=on rts=on"); break; case 256000 : strcpy(baudr, "baud=256000 data=8 parity=N stop=1 dtr=on rts=on"); break; case 500000 : strcpy(baudr, "baud=500000 data=8 parity=N stop=1 dtr=on rts=on"); break; case 1000000 : strcpy(baudr, "baud=1000000 data=8 parity=N stop=1 dtr=on rts=on"); break; default : cout <<"invalid Baudios\n"<<endl; return(1); break; }

Cport[Puerto] = CreateFileA(comports[Puerto-1], GENERIC_READ|GENERIC_WRITE, 0, /* no share */ NULL, /* no security */ OPEN_EXISTING, 0, /* no threads */ NULL); /* no templates */

if(Cport[Puerto]==INVALID_HANDLE_VALUE) { cout << "unable to open comport\n"<< endl;

Page 75: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

return(-1); }

DCB port_settings; memset(&port_settings, 0, sizeof(port_settings)); /* clear the new struct */ port_settings.DCBlength = sizeof(port_settings);

if(!BuildCommDCBA(baudr, &port_settings)) { cout <<"unable to set comport dcb settings\n"<< endl; CloseHandle(Cport[Puerto]); return(-1); }

if(!SetCommState(Cport[Puerto], &port_settings)) { cout<<"unable to set comport cfg settings"<<endl; CloseHandle(Cport[Puerto]); return(-1); }

COMMTIMEOUTS Cptimeouts;

Cptimeouts.ReadIntervalTimeout = MAXDWORD; Cptimeouts.ReadTotalTimeoutMultiplier = 0; Cptimeouts.ReadTotalTimeoutConstant = 0; Cptimeouts.WriteTotalTimeoutMultiplier = 10; Cptimeouts.WriteTotalTimeoutConstant = 10;

if(!SetCommTimeouts(Cport[Puerto], &Cptimeouts)) { cout <<"unable to set comport time-out settings\n"<< endl; CloseHandle(Cport[Puerto]); return(1); }

return(0);}

int rs232class::PollComport(unsigned char *buf){ int n;

/* added the void pointer cast, otherwise gcc will complain about *//* "warning: dereferencing type-punned pointer will break strict aliasing rules" */

ReadFile(Cport[Puerto], buf, Size, (LPDWORD)((void *)&n), NULL);

Page 76: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

return(n);}

int rs232class::SendByte(unsigned char byte){ int n;

WriteFile(Cport[Puerto], &byte, 1, (LPDWORD)((void *)&n), NULL); if(n<0) return(1);

return(0);}

int rs232class::_SendByte(unsigned char byte){ int n;

WriteFile(Cport[Puerto], &byte, 1, (LPDWORD)((void *)&n), NULL); if(n<0) return(1);

return(0);}

int rs232class::SendBuf(unsigned char *buf){ int n;

if(WriteFile(Cport[Puerto], buf, Size, (LPDWORD)((void *)&n), NULL)) { return(n); }

return(-1);}

void rs232class::CloseComport(){ CloseHandle(Cport[Puerto]);}

int rs232class::IsCTSEnabled(){ int status;

Page 77: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

GetCommModemStatus(Cport[Puerto], (LPDWORD)((void *)&status));

if(status&MS_CTS_ON) return(1); else return(0);}

int rs232class::IsDSREnabled(){ int status;

GetCommModemStatus(Cport[Puerto], (LPDWORD)((void *)&status));

if(status&MS_DSR_ON) return(1); else return(0);}

void rs232class::enableDTR(){ EscapeCommFunction(Cport[Puerto], SETDTR);}

void rs232class::disableDTR(){ EscapeCommFunction(Cport[Puerto], CLRDTR);}

void rs232class::enableRTS(){ EscapeCommFunction(Cport[Puerto], SETRTS);}

void rs232class::disableRTS(){ EscapeCommFunction(Cport[Puerto], CLRRTS);}

#endif

void rs232class::cputs(const char *text) /* sends a string to serial port */{ while(*text != 0x0a)

Page 78: Departamento de Electrónica y Automática - Trabajo finaldea.unsj.edu.ar/compinfo/archivosProyectos/Proyecto... · 2017-07-31 · PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

PROYECTO FINAL DE CATEDRA COMPLEMENTOS DE INFORMATCA

{_SendByte(*(text++)); }

SendByte(0x0d);}

void rs232class::_cputs(const char *text) /* sends a string to serial port */{ while(*text != 0x0a)

{SendByte(*(text++)); usleep(5000); }

SendByte(0x0d); usleep(500000);}