Interfacing with Python

From Pinguino
Jump to: navigation, search

Example - USB

On Pinguino

/*
*/
void setup()
{
}

void loop()
{
  USB.send("hello", 5);
  delay(1000);
	
}

On Computer Side

#!/usr/bin/env python
#
import usb
busses = usb.busses()
# Search pinguino between all the usb devices
for bus in busses:
  devices = bus.devices
  for dev in devices:
    if dev.idVendor==0x04d8 and dev.idProduct==0xfeaa:
      pingu = dev
# Get a device handler for th usb device
dh = pingu.open()
# Set configuration 3 an interface 0
dh.setConfiguration(3)
dh.claimInterface(0)
# Read 5 bytes in Bulk mode, convert them to 
# a string and print it
while 1 == 1: 
  cadena = ""
  for i in dh.bulkRead(0x82, 5, 10000):
    cadena += chr(i)
  print cadena

Example - CDC

Using Pynguino, a Python package that provides an interface to the Pinguino development board.

On Pinguino

cdc_8bit.pde or cdc_32bit.pde

On Computer Side

#!/usr/bin/env python
#-*- coding: utf-8 -*-

#from pynguino.ptools import avalilable_ports
#print(avalilable_ports())

#CDC
from pynguino import PynguinoCDC
pinguino = PynguinoCDC(port=0, baudrate=9600)

#USB
#from pynguino.pusb import PynguinoUSB
#pinguino = PynguinoUSB(vboot="v2", timeout=1000)

pinguino.pinMode(6, "OUTPUT")

for i in range(10):
    pinguino.digitalWrite(6, "HIGH")
    pinguino.delay(100)
    pinguino.digitalWrite(6, "LOW")
    pinguino.delay(200)

pinguino.pinMode(0, "INPUT")
print("pin 06 digialRead: " + pinguino.digitalRead(0))

pinguino.pinMode(13, "INPUT")
print("pin 13 analogRead: " + pinguino.analogRead(13))


for i in range(100):
        print(pinguino.analogRead(13))
        pinguino.delay(100)

More details in: author's site (spanish)

Example - ds18b20

On Pinguino

/*
	Pinguino example to read ds18b20 1wire temperature sensor
	Result is sent on USB bus and can be read with temp18b20.py
	author		Régis Blanchot
	first release	14/09/2010
	last update	06/10/2010
	IDE		Pinguino b9.2 or sup.

	DS18B20 Connection
	------------------
	pin 1: GND
	pin 2: DQ (Data in/out) must be connected to the PIC
	pin 3: VDD (+5V)

	NB : 1-wire bus (DQ line) must have 4K7 pull-up resistor (connected to +5V)
*/

#define ONEWIREBUS	0	// 1-wire bus is on pin 0 (RB0), just change it to suit you 
#define RUNLED PORTAbits.RA4	// for visual debug purposes

void setup()
{
	//
	//	find all sensors on the bus and get their Rom Code
	//
	
	//DS18B20.find(ONEWIREBUS);
}

void loop()
{
	TEMPERATURE t;
	u8 temp[4];
	// if you want to read temperature from sensor #1 with max. resolution :
	// if (DS18B20.read(ONEWIREBUS, 1, RES12BIT, &t))
	// if you have only one sensor on the bus, just skip rom detection
	if (DS18B20.read(ONEWIREBUS, SKIPROM, RES12BIT, &t))
	{
		// send temperature on usb bus
		temp[0] = t.sign;		// t.sign is unsigned  char (1 byte)
		temp[1] = t.integer;		// t.integer  is unsigned  char (1 byte)
		temp[2] = high8(t.fraction);	// t.fraction is unsigned int (2 bytes)
		temp[3] = low8(t.fraction);
		USB.send(temp, 4);		// send 4-bit temp on usb bus
		RUNLED = RUNLED ^ 1;		// blinked led for visual debug
		delay(1000);			// wait for 1 sec. before next reading
	}
}


On Computer Side

#! /usr/bin/python
# -*- coding: utf-8 -*-

#-------------------------------------------------------------------------------
# File: temp18b20.py
#
# display time and temperature
# temperature is sent by pinguino device though usb bus
# 
# regis blanchot, september 2010
#
# rblanchot@gmail.com
#
#-------------------------------------------------------------------------------

import usb		# requires pyusb available at https://sourceforge.net/projects/pyusb/files/
import sys
import time
import Tkinter		# requires python-tk (apt-get install python-tk)
from Tkinter import *

curtime = ''
curtemp = ''
timeline = ''
templine = ''

#-------------------------------------------------------------------------------
# Program window 
#-------------------------------------------------------------------------------

class Window:

	def __init__(self,root):
		self.root = root 
		self.canvas = Tkinter.Canvas(self.root)
		self.canvas.pack()
		self.canvas.config(background='black')
		self.canvas.config(width=400)
		self.canvas.config(height=200)

#-------------------------------------------------------------------------------
# Pinguino Class by Marin Purgar (marin.purgar@gmail.com)
#-------------------------------------------------------------------------------

class Pinguino():

	VENDOR = 0x04D8
	PRODUCT = 0xFEAA
	CONFIGURATION = 3
	INTERFACE = 0
	ENDPOINT_IN = 0x82
	ENDPOINT_OUT = 0x01

	device = None
	handle = None

	def __init__(self,):
		for bus in usb.busses():
			for dev in bus.devices:
				if dev.idVendor == self.VENDOR and dev.idProduct == self.PRODUCT:
					self.device = dev
		return None

	def open(self):
		if not self.device:
			print >> sys.stderr, "Unable to find device!"
			return None
		try:
			self.handle = self.device.open()
			self.handle.setConfiguration(self.CONFIGURATION)
			self.handle.claimInterface(self.INTERFACE)
		except usb.USBError, err:
			print >> sys.stderr, err
			self.handle = None
		return self.handle

	def close(self):
		try:
			self.handle.releaseInterface()
		except Exception, err:
			print >> sys.stderr, err
		self.handle, self.device = None, None

	def read(self, length, timeout = 0):
		return self.handle.bulkRead(self.ENDPOINT_IN, length, timeout)

	def write(self, buffer, timeout = 0):
		return self.handle.bulkWrite(self.ENDPOINT_OUT, buffer, timeout)

#-------------------------------------------------------------------------------
# update
#-------------------------------------------------------------------------------

def update():
	INTERVAL = 100
	global curtime
	global curtemp
	global timeline
	global templine
	deg = unichr(176).encode("utf-8")
	t = ''

	# get temperature
	try:
		t = pinguino.read(4, INTERVAL)
	except usb.USBError as err:
		pass
	if len(t) > 0:
		#print 't =',t	# debug
		if t[0] == 1:
			sign = '-'
		else:
			sign = ''
		newtemp = '%s%d%s%d%s%s' % (sign,t[1], '.', t[2]*256+t[3], deg, 'C')
		if newtemp != curtemp:
			curtemp = newtemp
			if templine:
				Temp18b20.canvas.delete(templine)			
			templine = Temp18b20.canvas.create_text(200, 150, text=curtemp, font=("Helvetica", "48", "bold"), fill='red')

	# get time
	newtime = time.strftime('%H:%M:%S')
	if newtime != curtime:
		curtime = newtime
		if timeline:
			Temp18b20.canvas.delete(timeline)			
		timeline = Temp18b20.canvas.create_text(200, 050, text=curtime, font=("Helvetica", "24", "bold"), fill='red')

	# recall every 500ms
	Temp18b20.canvas.after(INTERVAL, update)

#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------

if __name__ == "__main__":
	root = Tkinter.Tk()
	root.title('Temp18B20')
	Temp18b20 = Window(root)
	pinguino = Pinguino()
	if pinguino.open() == None:
		print >> sys.stderr, "Unable to open Pinguino device!"
		sys.exit()
	update()
	root.mainloop()
	pinguino.close()


Example - Graph analog signal with Matplotlib

On Pinguino

cdc_8bit.pde

On Computer Side

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#       ---------------------------------------------------------------------
#	File:AnalogReadSerialMatplotlib.py
#       Pinguino example to graph analog signal read on pin 13 of the pinguino
#	with the matplotlib library through serial communication using the 
#	pynguino communication library and CDC_8bit.pde from yeison cardona 
#	to be seen in AnalogReadSerialMatplotlib.py
#
#	author			Angel Urquia 
#	email			urquia22@gmail.com
#       date			21/12/2017
#	-----------------------------------------------------------------------
#	will need
#	-----------------------------------------------------------------------
#	1)cdc_8bit.pde
#	2)Pynguino
#	3)Matplotlib
#	----------------------------------------------------------------------

import numpy as np                             # importamos librerias necesarias // import necessary libraries
import matplotlib.pyplot as plt		      
from collections import deque
from pynguino import PynguinoCDC               # importamos Pynguino CDC de libreria pynguino // import Pynguino CDC from pynguino library

pinguino = PynguinoCDC()		       # iniciamos comunicacion via serial  // start communication via serial with pinguino
Leer = 13             			       # asignamos a la variable Leer = 13   //                          
pinguino.pinMode(Leer, "INPUT")		       # pin 13 como entrada // pin 13 as input	
	       				       
onda = deque([0]*10 , maxlen=10)               # asignamos a onda = deque con longitud máxima  "10" // onda = deque with maximum length "10"
y = pinguino.analogRead(Leer, float)           # y = lectura analogica en el pin 13 // assign to variable y = analog reading on pin 13

fig, ax = plt.subplots()                       # creamos la figura  // create the figure                   
linea, = ax.plot(onda)			       # dibujamos la figura // draw the figure

while True:
    x = np.linspace(0, 10, 100)                # 100 valores espaciados uniformemente de 0 a 10 // 100 values ​​evenly spaced from 0 to 10
    y = (pinguino.analogRead(Leer, float))/40  # valor de la lectura analogica /40  // value of the analog reading / 40
    onda.append(y)                             # agregamos "y" a onda //  add "y" to onda 
    linea.set_ydata(onda)                      # actualiza data de "y" // update data from "y"
    ax.set_ylim(-10, 40)		       # fija limites de "y" // fixed limits of "y"
    plt.pause(0.001)                           # pausa la graficacion y almacena valores // Pause the graphing and store values
plt.show()  				       # Mustrar la grafica // Show the graph

More details in: author's repository

Example - Controlling led lights

On Pinguino

cdc_8bit.pde

On Computer Side

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""/*	---------------------------------------------------------------------
	File:PinguiLed.py
        Pinguino example to control the activation and deactivation of three 
	pins of the pinguino board 18f4550, through an interface developed in 
	python with the tkinter library, by means of serial communication 
	using the pynguino communication library CDC_8bit.pde to be seen in 
	PinguiLed.py

	Ejemplo de Pinguino para controlar la activación y desactivación de 
	tres pines de la tarjeta pingüino  18f4550, a través de una interfaz
	desarrollada en python con la biblioteca tkinter, mediante 
	comunicación serial usando la biblioteca de comunicación pynguino 
	CDC_8bit.pde para ser visto en PinguiLed.py


	author			Angel Urquia 
	email			urquia22@gmail.com
        date                    02/01/2018
	-----------------------------------------------------------------------
	will need
	-----------------------------------------------------------------------
	1)cdc_8bit.pde
	2)Pynguino
	3)Board Pinguno 18f4550
	4)Three led diodes
	----------------------------------------------------------------------*/"""
from pynguino import PynguinoCDC 
from Tkinter import *     			#Import libraries // Importamos Librerias 
pinguino = PynguinoCDC()			#This would be our pinguino board // Esta seria nuestra tarjeta pinguino 

pinguino.pinMode(5, "OUTPUT")                   #Pins as output // Pines como salida pines
pinguino.pinMode(6, "OUTPUT")
pinguino.pinMode(7, "OUTPUT")

ven = Tk() 					#It is the main window // Tk() Es la ventana principal
ven.title('Por: Angel Urquia')

# Frame for the circles // Marco para los circulos
P = Frame(ven, width=500, height = 500)
P.grid(row=1, column=0, padx=0, pady=5)

#Canvas draw frame content for Led1 // Contenido del marco de dibujo de lienzo para Led1
marco = Canvas(P, width=50, height=50, bg='gray')
marco.grid(row=1, column=0, padx=0, pady=0)

#Canvas draw frame content for Led2 // Contenido del marco de dibujo de lienzo para Led2
marco2 = Canvas(P, width=50, height=50, bg='gray')
marco2.grid(row=1, column=1, padx=0, pady=0)

#Canvas draw frame content for Led3 // Contenido del marco de dibujo de lienzo para Led3
marco3 = Canvas(P, width=50, height=50, bg='gray')
marco3.grid(row=1, column=2, padx=0, pady=0)

#Frame for the background image // Marco para la imagen de fondo
tabla = Frame(ven, width=260, height = 200)
tabla.grid(row=0, column=0, padx=0, pady=0)

# background image // imagen fondo
img = PhotoImage(file="/home/angel/Imágenes/pinguino.gif") 
marco1 = Canvas(tabla, width=258, height=195, bg='blue')
marco1.grid(row=0, column=0, padx=5, pady=5)

# led 1 on
def led_on ():
	led = marco.create_oval(3, 3, 48, 48, width=4, fill="red",dash=(5,))
	pinguino.digitalWrite(6, "HIGH")

# led 1 off
def led_off ():
	led = marco.create_oval(3, 3, 48, 48, width=4, fill="white",dash=(5,))
	pinguino.digitalWrite(6, "LOW")

# led 2 on
def led_on2 ():
	led2 = marco2.create_oval(3, 3, 48, 48, width=4, fill="red",dash=(5,))
	pinguino.digitalWrite(7, "HIGH")
# led 2 off
def led_off2 ():
	led2 = marco2.create_oval(3, 3, 48, 48, width=4, fill="white",dash=(5,))
	pinguino.digitalWrite(7, "LOW")

# led 3 on
def led_on3 ():
	led3 = marco3.create_oval(3, 3, 48, 48, width=4, fill="red",dash=(5,))
	pinguino.digitalWrite(5, "HIGH")
# led 3 off
def led_off3 ():
	led3 = marco3.create_oval(3, 3, 48, 48, width=4, fill="white",dash=(5,))
	pinguino.digitalWrite(5, "LOW")

# Frame for text // Marco para texto 
P1 = Frame(ven, width=50, height = 100)
P1.grid(row=5, column=0, padx=0, pady=5)
texto = Label(P1, text="Interfaz de Control Pinguino")
texto.grid(row=5, column=0, padx=10, pady=2)

# Two actions the same button // Dos acciones el mismo boton
# Action button1 // Accion boton1
def toggle():
        
    if      boton1.config('text')[-1] == 'Encender':
            boton1.config(text='Apagar')
	    boton1.config(bg='red')
	    led_on ()

    else:
            boton1.config(text='Encender')
	    boton1.config(bg='green')
	    led_off()

# Action button2 // Accion boton2
def toggle2():
        
    if      boton2.config('text')[-1] == 'Encender':
            boton2.config(text='Apagar')
	    boton2.config(bg='red')
	    led_on2 ()

    else:
            boton2.config(text='Encender')
	    boton2.config(bg='green')
	    led_off2()


# Action button3 // Accion boton3
def toggle3():
        
    if      boton3.config('text')[-1] == 'Encender':
            boton3.config(text='Apagar')
	    boton3.config(bg='red')
	    led_on3 ()

    else:
            boton3.config(text='Encender')
	    boton3.config(bg='green')
	    led_off3()

# Main // Pincipal
marco1.create_image(130, 98, image=img)
led_off()
led_off2()
led_off3()

# create button1 // crear boton1
boton1 = Button(text="Encender", width=6, command=toggle,bg='green', fg='white', bd=10, font="times", activebackground='white', activeforeground='black')
boton1.grid(row=2, column=0, padx=0, pady=5)

# create button2 // crear boton2
boton2 = Button(text="Encender", width=6, command=toggle2,bg='green', fg='white', bd=10, font="times", activebackground='white', activeforeground='black')
boton2.grid(row=3, column=0, padx=0, pady=5)

# create button3 // crear boton3
boton3 = Button(text="Encender", width=6, command=toggle3,bg='green', fg='white', bd=10, font="times", activebackground='white', activeforeground='black')
boton3.grid(row=4, column=0, padx=0, pady=5)

ven.config(bg="blue") # background color // color de fondo
ven.mainloop()

More details in: author's repository