OakRidgejet OakRidgejet - 17 days ago 8
C Question

Arduino, Raspberry Pi, and HTML page

Currently I have an Arduino hooked up to a Raspberry Pi. The Arduino controls a water level detection circuit in service to an automatic pet water bowl. The program on the Arduino has several "serial.println()" statements to update the user on the status of the water bowl, filling or full. I have the Arduino connected to the Raspberry Pi via USB. The small python program on the Pi that captures the serial data from the Arduino is as follows:

import serial

ser = serial.Serial('/dev/ttyUSB0',9600)
file = open('index.html', 'a+')
message1 = """<html>
<head><meta http-equiv="refresh" content="1"/></head>
<body><p>"""
message2 = """</p></body>
</html>"""

while 1:
line=ser.readline()
messagefinal1 = message1 + line + message2
print(line)
file.write(messagefinal1)
file.close()


As you can see it captures the serial data coming over USB, creates and html page, and inserts the data into the page. I am using a service called "dataplicity" (https://www.dataplicity.com), more specifically their "Wormhole" tool (https://docs.dataplicity.com/docs/host-a-website-from-your-pi), to view that html file over the web at a link that the wormhole tool generates. The problem I am having is this:

Traceback (most recent call last):
File "commprog.py", line 15, in <module>
file.write(messagefinal1)
ValueError: I/O operation on closed file


I want to continuously update the html page with the status of the water bowl (it is constantly printing its status). However once I close the page using "file.close()" I can't access it again, presumably because the wormhole service is accessing it. If I don't include .close() I have to end the process manually using ctrl c. Is there a way I can continuously update the html file?

Answer

After the first iteration of your while loop, you close the file and never open it again for editing. When you try to append to a file that is closed, you get an error. You could instead move the open statement inside your loop like so:

while 1:
    line=ser.readline()
    messagefinal1 = message1 + line + message2
    print(line)
    file = open('index.html', 'a+')
    file.write(messagefinal1)
    file.close()