python bindings: python3 support
[libftdi] / examples / python / complete.py
... / ...
CommitLineData
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""Python example program.
5
6Complete program to demonstrate the usage
7of the swig generated python wrapper
8
9You need to build and install the wrapper first"""
10
11import os
12import ftdi1 as ftdi
13import time
14
15# initialize
16ftdic = ftdi.new()
17if ftdic == 0:
18 print( 'new failed: %d', ret )
19 os._exit( 1 )
20
21# list all devices
22ret, devlist = ftdi.usb_find_all( ftdic, 0x0403, 0x6001 )
23if ret < 0:
24 print( 'ftdi_usb_find_all failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
25 os._exit( 1 )
26print( 'Number of FTDI devices found: %d\n' % ret )
27curnode = devlist
28i = 0
29while( curnode != None ):
30 ret, manufacturer, description, serial = ftdi.usb_get_strings( ftdic, curnode.dev )
31 if ret < 0:
32 print( 'ftdi_usb_get_strings failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
33 os._exit( 1 )
34 print( 'Device #%d: manufacturer="%s" description="%s" serial="%s"\n' % ( i, manufacturer, description, serial ) )
35 curnode = curnode.next
36 i += 1
37
38# open usb
39ret = ftdi.usb_open( ftdic, 0x0403, 0x6001 )
40if ret < 0:
41 print( 'unable to open ftdi device: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
42 os._exit( 1 )
43
44
45# bitbang
46ret = ftdi.set_bitmode( ftdic, 0xff, ftdi.BITMODE_BITBANG )
47if ret < 0:
48 print( 'Cannot enable bitbang' )
49 os._exit( 1 )
50print( 'turning everything on' )
51ftdi.write_data( ftdic, chr(0xff), 1 )
52time.sleep( 1 )
53print( 'turning everything off\n' )
54ftdi.write_data( ftdic, chr(0x00), 1 )
55time.sleep( 1 )
56for i in range( 8 ):
57 val = 2**i
58 print( 'enabling bit #%d (0x%02x)' % (i, val) )
59 ftdi.write_data( ftdic, chr(val), 1 )
60 time.sleep ( 1 )
61ftdi.disable_bitbang( ftdic )
62print( '\n' )
63
64
65# read pins
66ret, pins = ftdi.read_pins( ftdic )
67print( 'pins:\n' )
68if ( ret == 0 ):
69 print( '%02x' % ord( pins[0] ) )
70print( '\n' )
71
72
73# read chip id
74ret, chipid = ftdi.read_chipid( ftdic )
75print( 'FDTI chip id: %X\n' % chipid )
76
77
78# read eeprom
79eeprom_addr = 1
80ret, eeprom_val = ftdi.read_eeprom_location( ftdic, eeprom_addr )
81if (ret==0):
82 print( 'eeprom @ %d: 0x%04x\n' % ( eeprom_addr, eeprom_val ) )
83
84print( 'complete eeprom:' )
85ret = ftdi.read_eeprom( ftdic )
86size = 128
87ret, eeprom = ftdi.get_eeprom_buf ( ftdic, size )
88if ( ret == 0 ):
89 for i in range( size ):
90 print( '%02x' % ord( eeprom[i] ) )
91 if ( i % 8 == 7 ):
92 print( '\n' )
93
94# close usb
95ret = ftdi.usb_close( ftdic )
96if ret < 0:
97 print( 'unable to close ftdi device: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
98 os._exit( 1 )
99ftdi.free( ftdic )