larryaus
Posts: 1
Joined: Mon Aug 25, 2014 5:52 am

IOError: [Errno 24] Too many open files:

Mon Aug 25, 2014 6:01 am

I have an issue reading the voltage from an MCP3002 (analogue to digital converter).
I have listed below the code, where I need to read every 1/10 of a second and display the reading. After approximately 1000 reads, the code crashed with the comment
"IOError: [Errno 24] Too many open files: "
I believe this is something to do with the read() staying open and not closing after each read. I would be appreciative if someone could advise how to correct this issue.

Thanks

Code: Select all

#!/usr/bin/python2.7

from __future__ import division
import spidev
import time
import random

def bitstring(n):
    s = bin(n)[2:]
    return '0'*(8-len(s)) + s
def read(adc_channel=0, spi_channel=0):
    conn = spidev.SpiDev(0, spi_channel)
    conn.max_speed_hz = 1200000 # 1.2 MHz
    cmd = 128
    if adc_channel:
        cmd += 32
    reply_bytes = conn.xfer2([cmd, 0])
    reply_bitstring = ''.join(bitstring(n) for n in reply_bytes)
    reply = reply_bitstring[5:15]
    return int(reply, 2) / 2**10
   
WL = 1
      
while WL > 0:
      
    P1 = read()
    print P1
    time.sleep(0.11)
    P2 = read()
    print P2
    time.sleep(0.11)
    P3 = read()
    print P3
    time.sleep(0.11)
    P4 = read()
    print P4
    time.sleep(0.11)
    P5 = read()
    print P5
    time.sleep(0.11)
    P6 = read()
    print P6
    time.sleep(0.11)
    P7 = read()
    print P7
    time.sleep(0.11)
    P8 = read()
    print P8
    time.sleep(0.11)
    P9 = read()
    print P9
    time.sleep(0.11)
    P10 = read()
    print P10

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: IOError: [Errno 24] Too many open files:

Tue Aug 26, 2014 2:14 pm

You could try creating the 'conn' object just once (outside your while loop) and then simply pass it in as an extra parameter to your read() function...
Either that, or make sure that the 'conn' object gets properly close()d before leaving the read() function.

Return to “Python”