jueves, 31 de diciembre de 2015

Crear componente hal usando la librería MAX31855

Para poder seguir con este tutorial se recomienda leer Librería MAX31855.

El siguiente tutorial explica como crear componentes para poder cargarlos en la configuración .hal.

Crear archivo.

nano hal_temp_max31855

#!/usr/bin/python
# encoding: utf-8
"""
Temperature.py
Created by Leonardo Noguera on 2015-12-19.
"""

from drivers.MAX31855 import MAX31855

import argparse
import time
import sys

import hal        
        

def parseHandleDevice(spi_bus):
    if spi_bus != 'SPI0' and spi_bus != 'SPI1':
        print(("wrong SPI"))
        sys.exit(1)
    if spi_bus == 'SPI0':
        bus = MAX31855.SPI0
    else:
        bus = MAX31855.SPI1
    return bus

parser = argparse.ArgumentParser(description='HAL component to read MAX31855 Temperature values')
parser.add_argument('-n', '--name', help='HAL component name', required=True)
parser.add_argument('-b', '--spi_bus', help='SPI bus id', default="SPI1")
parser.add_argument('-num', '--num_devices', help='Max 2 MAX31855', default=1)
parser.add_argument('-i', '--interval', help='SPI update interval', default=0.3)
parser.add_argument('-d', '--delay', help='Delay before the SPI should be updated', default=0.0)
args = parser.parse_args()

updateInterval = float(args.interval)
delayInterval = float(args.delay)
error = True
watchdog = True

bus = parseHandleDevice(args.spi_bus)

if (int(args.num_devices) == 1):
    cs = 0
elif (int(args.num_devices) == 2):
    cs = 1
else:
    print("Only two Max31855 are supported")
    sys.exit(1)     

thermocouple = MAX31855(bus=int(bus),spi_cs=int(cs))

# Initialize HAL
h = hal.component(args.name)
halThermocouple = h.newpin("Temp.meas", hal.HAL_FLOAT, hal.HAL_OUT)
halTemperatureSet =  h.newpin("Temp.set", hal.HAL_FLOAT, hal.HAL_IN)
halTempPinActive = h.newpin("Temp.set.done", hal.HAL_BIT, hal.HAL_OUT)
halErrorRead = h.newpin("error", hal.HAL_BIT, hal.HAL_OUT)
halNoErrorRead = h.newpin("no-error", hal.HAL_BIT, hal.HAL_OUT)
halWatchdogRead = h.newpin("watchdog", hal.HAL_BIT, hal.HAL_OUT)
h.ready()

halErrorRead.value = error
halNoErrorRead.value = not error
halWatchdogRead.value = watchdog

try:
    time.sleep(delayInterval)
    while (True):
        try:
            if (error):                
                error = False
              
            temp = thermocouple.readTempC()
            if (temp == None):
                try:
                    # The MAX31855 reported an error, print it:
                    if thermocouple.error == thermocouple.SHORT_TO_GND:
                        print "Thermocouple shorted to GND"
                        

                    elif thermocouple.error == thermocouple.SHORT_TO_VCC:
                        print "Thermocouple shorted to VCC"
                        
                except:
                    if thermocouple.error == thermocouple.OPEN_CIRCUIT:
                        print "Thermocouple not connected"

                    print(("exiting HAL component " + args.name))
                    h.exit()
            else: 
                halThermocouple.value = float("{:0.2f}".format(temp))
            
                if (halThermocouple.value >= halTemperatureSet.value):
                    halTempPinActive.value = 1
                else: halTempPinActive.value = 0
         
        except IOError as e:
            error = True 
            thermocouple.close()
          
        halErrorRead.value = error
        halNoErrorRead.value = not error
        watchdog = not watchdog
        halWatchdogRead.value = watchdog
        time.sleep(updateInterval)

except:
    print(("exiting HAL component " + args.name))
    h.exit()

Lo que hace el siguiente archivo es importar la librería MAX31855, verificar que SPI se quiere usar, por defecto SPI1. Lo que sigue son los argumentos que se pueden usar, siendo obligatorio dar un nombre para el componente.

Usando num = 1 o num = 2, se puede leer un MAX31855 enviando un cero a cs y con una compuerta NOT se obtiene acceso a un segundo MAX31855 mandando un 1 y la compueta NOT convirtiendola en un 0 para que se habilite el segundo MAX31855. Soporta un máximo de 4 MAX31855 usando SPI0 y SPI1. Si se necesitará de más MAX31855 se debería cambiar la librería para que se simule por software la lectura de SPI y habilitar la seleccion del chip (cs) con cualquier GPIO. Ver como ejemplo Adafruit MAX31855.

En el siguiente paso se crea las señales hal que se encargarán de leer la temperatura, adquirir el valor de temperatura proporcionado por "código g" y determinar si la temperatura que se esta leyendo ha sobrepasado la temperatura enviada para seguir con el código G. Esto se explicará en el proximo tutorial al hablar de código G remapeado y uso de PID.

Por último se lee la temperatura y en el caso de no estar conectada la termocupla o este a circuitada GND o VCC se imprimirá lo que retorne, excepto la temperatura que se gaurdará en la variable "halThermocouple.value".

Para entender mejor lo que se ha realizado, se recomienda leer los componentes hal de las librerías de Machinekit. Hal user components.

El código de arriba se lo guardará con el nombre de hal_temp_max31855, luego se le dará permisos de ejecución y finalmente se lo copiará a /usr/bin para poder usarlo con Machinekit.

sudo chmod +x hal_temp_max31855 
sudo cp hal_temp_max31855 /usr/bin

Probar componente hal_temp_max31855.

En mi caso se cargará el componente de la siguiente manera:

loadusr -Wn Extruder0 hal_temp_max31855 -n Extruder0 -b SPI0 -num 1 -i 0.3

Donde loadusr indicá que cargará un componente creado, -Wn se usará para identificar al componente con un nombre, hal_temp_max31855 será el componente que se cargara con -n que es el nombre que se le dará, -b para escoger que se quiere trabajar con SPI0 o SPI1, -num 1 para mandar un cero a cs, -i para dar un tiempo de actualización 300ms.

Como requisito para que funcione es neceserio que se haya Habilitado SPI0 o SPI1 (device tree overlay).

Para probar componentes o archivos se puede usar el ejecutable "halrun" en el terminal

halrun
loadusr -Wn Extruder0 hal_temp_max31855 -n Extruder0 -b SPI0 -num 1 -i 0.3
show pin

Cada vez que se de la orden de show pin se verán los cambios de temperatura.













No hay comentarios.:

Publicar un comentario