viernes, 24 de enero de 2014

Instalando Tiva C Launchpad en Ubuntu GNU/Linux

Con motivo de curso ofrecido en la plataforma www.edx.org llamado Embedded Systems - Shape The World (https://www.edx.org/course/utaustinx/utaustinx-ut-6-01x-embedded-systems-1172), he adquirido el Tiva C Launchpad de TI. Pero como usarlo en Linux, ya que es el SO que más uso.

Toolchain

Primero añadimos el PPA del toolchain, para ellos abrimos una terminal y ejecutamos los siguientes comandos.

sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded
sudo apt-get update
sudo apt-get install gcc-arm-none-eabi


lm4flash

Instalamos los siguientes paquetes:

sudo apt-get install flex bison libgmp3-dev libmpfr-dev libncurses5-dev libmpc-dev autoconf texinfo build-essential libftdi-dev git libusb-1.0-0-dev


Clonamos el repositorio del lm4tools:

git clone https://github.com/utzig/lm4tools.git
cd lm4tools/lm4flash/
make
sudo cp lm4flash /usr/bin/


Añadimos una nueva regla udev para darle acceso al Tiva C Launchpad a los usuarios normales.

$ cat /etc/udev/rules.d/99-tivac.rules
ATTR{idVendor}=="15ba", ATTR{idProduct}=="0004", GROUP="plugdev", MODE="0660" # Olimex Ltd. OpenOCD JTAG TINY
ATTR{idVendor}=="067b", ATTR{idProduct}=="2303", GROUP="plugdev", MODE="0660" # Prolific Technology, Inc. PL2303 Serial Port
ATTR{idVendor}=="10c4", ATTR{idProduct}=="ea60", GROUP="plugdev", MODE="0660" # USB Serial
ATTR{idVendor}=="1cbe", ATTR{idProduct}=="00fd", GROUP="plugdev", MODE="0660" # TI TivaC/Stellaris Launchpad

sudo udevadm control --reload-rules

Tiva C Ware

Descargamos SW-EK-TM4C123GXL-1.0.exe de http://www.ti.com/tool/sw-ek-tm4c123gxl. Si no tienen cuenta se va a tener que crear para poder descargarlo.

Ya descargado procedemos a descomprimirlo con unzip y lo compilamos

unzip SW-EK-TM4C123GXL-1.0.exe
make

Si todo ha ido bien podremos subir alguno de los ejemplos en nuestra tarjeta de desarrollo

$ lm4flash examples/boards/ek-tm4c123gxl/blinky/gcc/blinky.bin


lunes, 26 de diciembre de 2011

Simulación BPSK en python/numpy/matplotlib

Una pequeña prueba



import numpy as np
from scipy.special import erfc
#from scipy import weave
#from scipy.weave import converters
import matplotlib.pyplot as plt
from time import time

N = 5000000
ip = np.random.rand(1,N)>0.5;
s = 2*ip-1
t = time()
n = 1.0/np.sqrt(2.0)*(np.random.randn(1,N)+1j*np.random.randn(1,N))
print(time()-t)
Eb_N0_dB = np.arange(-3.0,11.0,1.0) #-3 a 10 dB
errors = []
terrors = []
for EbN0 in Eb_N0_dB:
t = time()
y = s+10**(-EbN0/20.0)*n
ipHat = y.real>0
err = float((ip != ipHat).sum())/N
errors.append(err)
terrors.append(0.5*erfc(np.sqrt(10**(EbN0/10.0))))
print("time = %s, EbN0 = %s, ber = %s"%(time()-t,EbN0,err))
plt.semilogy(Eb_N0_dB,errors,'-o')
plt.semilogy(Eb_N0_dB,terrors,':v')
plt.legend(('simulation','theory'),'upper right',shadow=True,fancybox=True)
plt.title('Bit Error Rate for BPSK')
plt.xlabel(r'$\frac{Eb}{N0}$, dB')
plt.ylabel('Bit Error Rate')
plt.grid(True)
plt.show()



viernes, 29 de julio de 2011

Una prueba de code2html

code2html es una aplicación destinada a convertir tu código en html para poder publicarlo.

$ code2html -h
Code2Html, version 0.9.1, Jan 2002, peter@palfrader.org
Usage: code2html [options] [input_file [output_file]]

Convert a program source to syntax highlighted HTML,
or any other format for wich rules are defined.

-l, --language-mode set language mode
--fallback LANG fallback language mode
-v, --verbose prints progress information to STDER
-n, --linenumbers print out the source code with line numbers
-P, --prefix optional prefix to use for linenumber anchors
-N, --linknumbers linenumbers will link to themselves
-t, --replace-tabs[=TABSTOP-WIDTH]
replace with spaces
-L, --language-file=LANGUAGE-FILE
specify an alternate file for definitions
-m, --modes print all available modes
-h, --help print this message
-V, --version print version
-c, --content-type prints a Content-Type header
-o, --output-format selects the output-format
-H, --no-header don't use the template
--template=FILE override template
-T, --title set title

-w, --linewidth max characters per line
-b, --linebreakprefix prefix of the new lines

see the man-page code2html for further help


$ code2html -m
Defined modes: ada, ada95, awk, c, c++, cc, cpp, cxx, gpasm, groff, html, java, javascript, js, lisp, m4, make, makefile, pas, pascal, patch, perl, plain, pov, povray, python, ruby, sh, shellscript, sql.
Defined outputformats: html, html-dark, html-fntlck, html-light, html-nobg, html-nocolor, html-simple.

ejemplos:

code2html pex.py -H
import xlrd
import
xlwt
from
xlutils.copy import copy

class
xls(xlwt.Workbook):
def __init__(self, encoding='ascii', style_compression=0):
xlwt.Workbook.__init__(self,encoding, style_compression)

def add_sheet2(self,worksheet):
if
isinstance(worksheet,xlwt.Worksheet):
self._Workbook__worksheet_idx_from_name[worksheet.name.lower()] = len(self._Workbook__worksheets)
self._Workbook__worksheets.append(worksheet)
else
:
raise
Exception("invalid worksheet")

file_name = 'tb_wbdh13.xls'
rb = xlrd.open_workbook(file_name,formatting_info=True)

print
rb
print
rb.name_and_scope_map
print
rb.name_map
print
rb.name_obj_list
print
"____________________________________"
for
name in rb.name_obj_list:
print
name
print
name.name
print
name.raw_formula
print
name.result.text
print
name.scope

sheet = rb.sheet_by_index(0)
print
sheet.colinfo_map
print
sheet.rowinfo_map
print
sheet.col_label_ranges
print
sheet.row_label_ranges
print
sheet.cell(1,3).xf_index
print
sheet.colinfo_map[0].xf_index
print
dir(sheet)
#print xlrd.dump(file_name)
wb = copy(rb)
ws = wb.get_sheet(0)
doc = xls()
doc.add_sheet("CLK_PROCESS_0")
doc.add_sheet("CLK_PROCESS_1")
doc.add_sheet("CLK_PROCESS_bak")

doc.add_sheet2(ws)
doc.save('out.xls')


code2html -n pex.py -H
 1 import xlrd
2 import
xlwt
3 from
xlutils.copy import copy
4
5 class
xls(xlwt.Workbook):
6 def __init__(self, encoding='ascii', style_compression=0):
7
xlwt.Workbook.__init__(self,encoding, style_compression)
8
9 def add_sheet2(self,worksheet):
10
if
isinstance(worksheet,xlwt.Worksheet):
11
self._Workbook__worksheet_idx_from_name[worksheet.name.lower()] = len(self._Workbook__worksheets)
12
self._Workbook__worksheets.append(worksheet)
13 else
:
14 raise
Exception("invalid worksheet")
15
16
file_name = 'tb_wbdh13.xls'
17
rb = xlrd.open_workbook(file_name,formatting_info=True)
18
19 print
rb
20 print
rb.name_and_scope_map
21 print
rb.name_map
22 print
rb.name_obj_list
23 print
"____________________________________"
24 for
name in rb.name_obj_list:
25 print
name
26 print
name.name
27 print
name.raw_formula
28 print
name.result.text
29 print
name.scope
30
31
sheet = rb.sheet_by_index(0)
32 print
sheet.colinfo_map
33 print
sheet.rowinfo_map
34 print
sheet.col_label_ranges
35 print
sheet.row_label_ranges
36 print
sheet.cell(1,3).xf_index
37 print
sheet.colinfo_map[0].xf_index
38 print
dir(sheet)
39
#print xlrd.dump(file_name)
40
wb = copy(rb)
41
ws = wb.get_sheet(0)
42
doc = xls()
43
doc.add_sheet("CLK_PROCESS_0")
44
doc.add_sheet("CLK_PROCESS_1")
45
doc.add_sheet("CLK_PROCESS_bak")
46
47
doc.add_sheet2(ws)
48
doc.save('out.xls')


code2html -o html-nocolors -H prex.py
import xlrd
import xlwt
from xlutils.copy import copy

class xls(xlwt.Workbook):
def __init__(self, encoding='ascii', style_compression=0):
xlwt.Workbook.__init__(self,encoding, style_compression)

def add_sheet2(self,worksheet):
if isinstance(worksheet,xlwt.Worksheet):
self._Workbook__worksheet_idx_from_name[worksheet.name.lower()] = len(self._Workbook__worksheets)
self._Workbook__worksheets.append(worksheet)
else:
raise Exception("invalid worksheet")

file_name = 'tb_wbdh13.xls'
rb = xlrd.open_workbook(file_name,formatting_info=True)

print rb
print rb.name_and_scope_map
print rb.name_map
print rb.name_obj_list
print "____________________________________"
for name in rb.name_obj_list:
print name
print name.name
print name.raw_formula
print name.result.text
print name.scope

sheet = rb.sheet_by_index(0)
print sheet.colinfo_map
print sheet.rowinfo_map
print sheet.col_label_ranges
print sheet.row_label_ranges
print sheet.cell(1,3).xf_index
print sheet.colinfo_map[0].xf_index
print dir(sheet)
#print xlrd.dump(file_name)
wb = copy(rb)
ws = wb.get_sheet(0)
doc = xls()
doc.add_sheet("CLK_PROCESS_0")
doc.add_sheet("CLK_PROCESS_1")
doc.add_sheet("CLK_PROCESS_bak")

doc.add_sheet2(ws)
doc.save('out.xls')

domingo, 24 de julio de 2011

[Python] Descargando desde rapidshare usando la api

Sólo por probar como funciona la api de rapidshare que se encuentra documentada en http://images.rapidshare.com/apidoc.txt
#!/usr/bin/env python

import sys
import urllib2
import urllib
import time
url =  "http://rapidshare.com/#!download|958tl|40"
url += "20022538|NarutoKizunaDriveSaveData.rar|222|"
url += "R~3187F38923AB1D7B76BF6D2C55ADDCEE"
print url #link de prueba
url_api = "http://api.rapidshare.com/cgi-bin/rsapi.cgi"

status_file = {0:'File not found',
1:'File OK',
3:'Server down',
4:'File marked as illegal',
5:'Direct download'
}

headers = {'User-Agent':'Firefox Mozilla 7.0'}

class opener(urllib.FancyURLopener):
version = headers['User-Agent']

def check_files(link):
#Aquí vamos a verficar que el link sea válido
#?sub=checkfiles_v1&filenames=?&files=?
try:
file_id, file_name = link.rsplit('/')[3].split('|')[2:4]
except:
print("No rapidshare link")
sys.exit(1)

params = {'filenames':file_name,
'files':file_id,
}
params_string = urllib.urlencode(params)
check_link = "%s?sub=checkfiles_v1&%s"%(url_api,params_string)
request = urllib2.Request(url=check_link, headers=headers)
conn = urllib2.urlopen(request)
file_id, file_name,size,serverid,status,short_host,fmd5 = conn.read().split(',')
print("check_files -----------------|\n")
print(status_file[int(status)])
if status == '1':
print("File ID: %s\nFile Name: %s\nsize: %s bytes"%(file_id,file_name,size))
print("Server ID: %s\nShort host: %s\nmd5_hex: %s"%(serverid,short_host,fmd5))
return file_id,file_name,size,serverid,fmd5
else:
print('Aborting download')
sys.exit(1)


def get_download_auth(file_id,file_name):
#Para usuarios con cuentas gratuitas obtenemos primero el la autorización de descarga
# y el tiempo de espera para descargar
#?sub=download_v1&filname=?&fileid=?
params = {'filename':file_name,
'fileid':file_id
}
params_string = urllib.urlencode(params)
link = "%s?sub=download_v1&%s"%(url_api,params_string)
request = urllib2.Request(url=link, headers=headers)
conn = urllib2.urlopen(request)
key, value = conn.read().split(':')
if key == "ERROR":
print("Error:%s"%value)
sys.exit(1)
host, dlauth, countdown, fmd5 = value.split(',')
print("get_download_auth ---------------|\n")
print(link)
print("\nHost: %s\ndlauth: %s\ncountdown: %s seconds"%(host,dlauth,countdown))
return host, dlauth, countdown, fmd5

def download_file(file_id,file_name,host,dlauth, countdown, fmd5):
#Descargamos el archivo
params = {'fileid':file_id,
'filename':file_name,
'dlauth':dlauth
}
params_string = urllib.urlencode(params)
download_link = "http://%s/cgi-bin/rsapi.cgi?sub=download_v1&%s"%(host,
params_string)
time.spleep(int(countdown))
print("download_file --------------|\n")
print(download_link)
download_opener = opener()
filename, headers = download_opener.retrieve(download_link, file_name)
print('Download Completed')
print("File Name: %s"%filename)
print("Headers: %s"%headers)

if __name__== '__main__':
file_id,file_name,size,serverid,fmd5 = check_files(url)
host,dlauth,countdown,fmd5 = get_download_auth(file_id,file_name)
download_file(file_id,file_name,host,dlauth,countdown, fmd5)

Salida

http://rapidshare.com/#!download|958tl|4020022538|NarutoKizunaDriveSaveData.rar|222|R~3187F38923AB1D7B76BF6D2C55ADDCEE
check_files -----------------|

File OK
File ID: 4020022538
File Name: NarutoKizunaDriveSaveData.rar
size: 222575 bytes
Server ID: 958
Short host: tg
md5_hex: 41C7C90CDA303BDBBF90A053130255F6

get_download_auth ---------------|

http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=download_v1&fileid=4020022538&filename=NarutoKizunaDriveSaveData.rar

Host: rs958tl2.rapidshare.com
dlauth: 189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC28EFEAE1F4FAE96472AFC73963140F1485706FC8FCE1E931D4ADB4A3B0AD3F5A4E505C6225F0C4F70DB7CA37B9D9E35886189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC283F2A732A85F08C6E98E793B05368EB42
countdown: 0 seconds
download_file --------------|

http://rs958tl2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download_v1&filename=NarutoKizunaDriveSaveData.rar&dlauth=189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC28EFEAE1F4FAE96472AFC73963140F1485706FC8FCE1E931D4ADB4A3B0AD3F5A4E505C6225F0C4F70DB7CA37B9D9E35886189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC283F2A732A85F08C6E98E793B05368EB42&fileid=4020022538
Download Completed
File Name: NarutoKizunaDriveSaveData.rar
Headers: Date: Sun, 24 Jul 2011 19:50:00 GMT
Connection: close
Content-Type: application/octet-stream
Accept-Ranges: bytes
Content-Disposition: Attachment; filename=NarutoKizunaDriveSaveData.rar
Content-Length: 222575


Es un ejemplo sencillo y nada elaborado, que no pretende ser de uso diario, para eso tenemos plowshare (http://code.google.com/p/plowshare/).

jueves, 14 de julio de 2011

[Python] manejando parámetros con optparser

import sys
from optparse import make_option,OptionParser


def opciones(argv):
usage = "usage: %prog [options] Archivo"
usage +="\nManejo de parametros desde la linea de comandos"

option_list = (
make_option("-o","--opcion_1",action='store', dest='opcion_1', default ="", help="Opcion 1"),
make_option("-p","--pi",action='store', type="float", dest='pi', default = 3.1416, help="Constante Pi"),
make_option("-v",action='store_true', dest='verbose', default = True),
make_option("-q",action='store_false', dest='verbose'),
)

parser = OptionParser(prog = argv[0],
usage=usage,
option_list = option_list
)

options, args = parser.parse_args(argv[1:])

if argv[1:] == []:
parser.print_help()
elif argv[1] in ('-h','--help'):
parser.print_help()
elif args == []:
parser.print_help()
else:
print(options.opcion_1)
print(options.pi)
print(options.verbose)
print(args[0])
if __name__ == "__main__":
opciones(sys.argv[:])



ej.


$ python options.py
Usage: options.py [options] Archivo
Manejo de parametros desde la linea de comandos

Options:
-o OPCION_1, --opcion_1=OPCION_1
Opcion 1
-p PI, --pi=PI Constante Pi
-v
-q
-h, --help show this help message and exit

martes, 20 de abril de 2010

nvidiactl

Después de actualizar a kubuntu 10.04 Beta 2 y reinstalar los drivers de la tarjeta nvidia como usuario normal perdí la aceleración 3D.

cuando le daba

glxinfo | grep render

me salia una línea que rezaba así

NVIDIA: could not open the device file /dev/nvidiactl (Permission denied).


solución:

Agregamos a nuestro usuario al grupo de video:

¿Porque?

si hacemos un ls -l al dispositivo veremos

ls -l /dev/nvidiactl
crw-rw---- 1 root video 195, 255 2010-04-20 08:02 /dev/nvidiactl


El dispositivo pertenece a root y al grupo de video

Si vemos el contenido de /etc/group veremos que nuestor usuario no pertenece a ese grupo

cat /etc/group | grep video
video:x:44:


Editamos el archivo para agregarnos y que quede algo como

cat /etc/group | grep video
video:x:44:usuario


Cerramos la sesión actual, nos logeamos de nuevo y ya tendremos la aceleración perdida:

glxinfo | grep render
direct rendering: Yes
OpenGL renderer string: GeForce Go 6150/PCI/SSE2
GL_NVX_conditional_render, GL_SGIS_generate_mipmap, GL_SGIS_texture_lod,


glxgears
Running synchronized to the vertical refresh. The framerate should be
approximately the same as the monitor refresh rate.
7866 frames in 5.0 seconds
9066 frames in 5.0 seconds
9059 frames in 5.0 seconds

martes, 23 de febrero de 2010

webcam como camara IP en Linux (debian, ubutu)

Primero tenemos que tener instalado los siguientes paquetes, y tener configurado un servidor web (puede ser apache o cualquier otro)

sudo apt-get install webcam lib4l-0

No se crea ningún archivo de configuración por lo cual no creamos en nuestro home, o si vamos a usar la ruta principal del servidor web (/var/www) creamos el archivo webcam.conf dentro de /etc

vim .webcamrc (o con el editor de texto que uses)
vim /etc/webcam.conf (como root o anteponiendo sudo, en caso de pertenecer a los sudoers)

El archivo va contener algo como lo que se muestra enseguida

[ftp]
host = localhost
user = nobody
pass = xxxxxx
dir = /home/usuario/public_html
file = webcam.jpg
tmp = imageup.jpg
local = 1

[grab]
device = /dev/video0
width = 320
height = 240
text = "Webcam %Y-%m-%d %H:%M:%S"
delay = 0
input =sonixj
quality = 75
trigger = 180
fg_red = 255
fg_green = 255
fg_blue = 255
rotate = 2

Como mi webcam pone de cabeza las capturas, con rotate = 2 lo arreglo (1=90 grados 2= 180, etc.)

¿Como saber cual es el nombre de la webcam(input = nombrewebcam)? con v4l-info (dese la terminal)

$ v4l-info

Las partes que nos interesan es la que nos dice el nombre de la camara (sonixj) y la altura y el ancho máximo

inputs
VIDIOC_ENUMINPUT(0)
index : 0
name : "sonixj" <---Este es el valor de input =sonixj type : CAMERA audioset : 0 tuner : 0 std : 0x0 [] status : 0x0 []

y
### video4linux device info [/dev/video0] ###
general info
VIDIOCGCAP
name : "USB camera"
type : 0x1 [CAPTURE]
channels : 1
audios : 0
maxwidth : 640
maxheight : 480
minwidth : 48
minheight : 32


Ahora si lo probamos con

@anaconda-server:~$ webcam
reading config file: /home/usuario/.webcamrc
can't get rgb24 data

Ops! ¿Qué hace ese rgb24 data? si nunca lo mandé llamar.

Solución:

Se me ocurrió que se podría asociar con el LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so webcam, por lo que es la misma solución que para algunas webcam es necesaria para poderlas usar con skype

https://wiki.ubuntu.com/SkypeWebCams

$ LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so webcam
reading config file: /home/usuario/.webcamrc
video4linux webcam v1.5 - (c) 1998-2002 Gerd Knorr
grabber config:
size 320x240 [none]
input sonixj, norm (null), jpeg quality 75
rotate=2, top=0, left=0, bottom=240, right=320
write config [ftp]:
local transfer /home/usuario/public_html/imageup.jpg => /home/usuario/public_html/webcam.jpg
compare: max=50,avg=4
compare: max=255,avg=78
compare: max=8,avg=0
compare: max=24,avg=0
compare: max=17,avg=0
compare: max=33,avg=0
compare: max=29,avg=0
compare: max=35,avg=0
compare: max=34,avg=0
compare: max=42,avg=0
compare: max=39,avg=0
compare: max=46,avg=0
compare: max=52,avg=0

Ya sólo queda ver el resultado en la web, mover la camara y recargar el navedador para ver los resultados. Para probar su funcionamiento utilicé la siguiente página web.

<html>
<head>
<title>WebCam</title>
<meta http-equiv="REFRESH" content="1"></meta>
</head>
<body>
<img src="webcam.jpg"></img>
</body>
</html>


Recargo la página cada segundo.



webcam a 320x240



webcam a 640x480