Serial exception Arduino to Python error - python

I want to read data from Arduino and store in a text file in pc through serial port using pyserial whenever I try to execute the Python code it gives this message I tried many things but didn't work out.
Code:
import io
import serial
from datetime import datetime
from serial import SerialException
connected=False
outfile='C:\Users\Yassine\hello.txt'
ser = serial.Serial(port="COM12", baudrate=9600,timeout=None,bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), encoding='ascii', newline ='\r')
with open(outfile,'a') as f:
while ser.isOpen():
try:
datastring=ser.readline()
except serial.SerialException:
pass
print datastring
print datetime.now()
f.write(datetime.now().isoformat() +'\t'+ datastring +'\n' )
f.flush()
while not ser.isOpen():
pass
ser.close()

Check that COM12 is actually the Arduino by looking in device manager.
Or you can execute this in command line to get a list of available serial ports:
python -m serial.tools.list_ports
You may also have something else trying to access the Arduino serial port. Make sure the Serial Monitor in Arduino IDE is closed.

I want to open txt file read the last value of it & write it in other txt file,it's working but the reading value(arg) written to the next file jump the line which is not good for me i want it at the same line with other variables
with open(outfile,'a') as f:
with open (inputfile,'r') as f1:
arg =f1.readline() // that variable i read from the txt
print (arg )
f.write(datetime.now().strftime("%Y-%m-%d ; %H:%M:%S")+'\n'+valueRead+ '\n' +arg+ '\n') // the file i write to
f.flush()
f1.close()
f.close()
TTTs (this is my arg variable that i read from txt file this is what i get)
2017-05-12 ; 15:48:23 TTS (this is how i want it )
Thanks for helping guys

Related

Write the OBDII data to a .txt or .csv file in realtime

import obd
import time
import serial
obd.logger.setLevel(obd.logging.DEBUG)
connection = obd.Async( fast= False) #auto-connects to USB or RF port
#RPM
#rpm=connection.watch(obd.commands.RPM)
def new_rpm(r):
print("RPM:",r.value)
print("\t")
connection.watch(obd.commands.RPM, callback=new_rpm)
connection.start()
with open ('ObdData.txt', 'a') as f:
while open:
timestr = time.strftime("New Time : %d-%m-%y-%H-%-M-%S")
f.write('\n')
f.write (timestr)
f.write('\n')
f.write('\n')
#f.write(str(rpm))
#or
#f.write(f"SPEED:{r.value}")
f.write('\n')
#the callback now will be enabled for new values
time.sleep(30)
connection.stop()
I tried to take real time data from my car but i can't write this code don't write the data to my file. Am i doing something wrong calling the function??

Exception for Python ftplib in my program?

I wrote this program to draw data from a text file on a website's directory (of which is edited by the user on the site) but it seems to crash. A lot.
from sys import argv
import ftplib
import serial
from time import sleep
one = "0"
repeat = True
ser = serial.Serial("COM3", 9600)
while repeat == True:
path = 'public_html/'
filename = 'fileone.txt'
ftp = ftplib.FTP("*omitted*")
ftp.login("*omitted*", "*omitted*")
ftp.cwd(path)
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
ftp.quit()
txt = open(filename)
openup = txt.read()
ser.write(openup)
print(openup)
Does anyone know any kind of way to stop it from crashing? I was thinking of using an exception but I'm no Python expert. The program does what it's meant to do, by the way, and the address and login have been omitted for obvious reasons. Also if possible I ask for an exception to stop the program from crashing when it disconnects from the serial port.
Thanks in advance!
Two things:
You might want to put all the ftplib related code in a try-except block like so:
try:
#code related to ftplib
except Exception, e: #you can fill this in after you encounter the exception once
print str(e)
You seem to be opening the file but not closing it when you're done. This might also cause errors later. The best way to do this would be:
with open(filename, 'r') as txt:
openup = txt.read()
This way the file will be closed automatically once you're outside the 'with' block.

Opening a file in Python: bytes array converted to string?

I have a text file with data such as
b'\x00\x09\x00\xfe'
This was piped into a text file from a TCP socket stream. Call this text file 'stream.txt'. I opened this file with the following code:
f = open("stream.txt", "rb")
bytes_read = f.read()
When I open this file within another Python script, I get a '\' for each '\' in the original file. On top of this, I cannot access the bytes array as such, since it appears to have become a string. That is, 'bytes_read' is now
'b"\\x00\\x09\\x00\\xfe"'
How can I recover this string as a bytes array?
The client code I used to capture this data is the following script:
from socket import *
clientsock = socket(AF_INET, SOCK_STREAM)
clientsock.connect(('1.2.3.4', 2000)) # Open the TCP socket
clientsock.sendall(b'myCommand') # Send a command to the server
data = clientsock.recv(16) # Wait for the response
print(data) # For piping to 'stream.txt'
clientsock.close()
As the data was printed to the terminal, I redirected it to a file:
$ python3 client.py > stream.txt
My goal is to bypass the redirect into text file and pipe directly into a plotter... But first I wanted to get this to work.
Was able to solve this by writing directly to a file. So rather than using 'print(data)', and redirecting to a file, I tried this:
file = open("rawData", "wb")
...
file.write(data)
...
file.close()
Was able to process "rawData" as expected.

send string between python script

I want to send 'hello world' to a script in python already running in ubuntu.
The script that's always running is this one (part of it):
print("$ echo 'foobar' > {0}".format(get_ttyname()))
print("$ echo 'foobar' > /proc/{0}/fd/0".format(os.getpid()))
sys.stdin.readline()
it throws the pid of the running process so I can send stuff by console with:
echo 'hello script!' > /proc/PID/fd/0
It will print it in the console! but I can't send \x15 or EOF or anything to break sys.stdin.readline() and do some other stuff in my script, for example:
def f(e):
print 'we already read:',s
while True:
s = sys.stdin.readline()
print 'we break the readline'
f(s)
.....blablabla some other stuff, and then we return to the top of the while to keep reading...
Does anyone know how to do it? The script that send the string will not always be running, but the script that receives the info will be always running.
PROBLEM SOLVED!
Thank's to Rafael this is the solution:
Reader:
import os
import sys
path = "/tmp/my_program.fifo"
try:
os.mkfifo(path)
except OSError:
pass
fifo = open(path, "r")
while True:
for line in fifo:
linea = line
print "Received: " + linea,
fifo.close()
if linea =='quit':
break
fifo = open(path, "r")
Sender:
# -*- coding: utf-8 -*-
import os
path = "/tmp/my_program.fifo"
fifo = open(path, "w")
fifo.write("Hello Wordl!!\n")
fifo.close()
Since you obviously don't have a problem with being limited to a Unix system, you can use named pipes to communicate with the program. Very unix-y way to work.
Python provides the os.mkfifo function to ease creating named pipes; otherwise they work just like files.
Write to a text file that is read by the already running program. The two can interact via this file. For example, these two programs simultaneously read and write to an initially empty text file.
already.py
# executed 1st
import time
while True:
text = open('file.txt').read()
print 'File contents: ' + text
time.sleep(5)
program.py
# executed 2nd
import time
while True:
text = open('file.txt', 'a')
text.write(raw_input('Enter data: '))
text.close()
time.sleep(5)

dpkt throws NeedData on valid pcap

I have this python code:
import sys
import dpkt
f = file("pcaop.Pcap")
pcap = dpkt.pcap.Reader(f)
i = 0
for ts, buf in pcap:
print "Ya"
dpkt throws NeedData on the 52nd packet. The same one every time - I've checked packet 52 and it is the same as everyone else on wireshark.
What causes this?
Solution is provided here: Python stops reading file using read
I had the same problem when dpkt.pcap was working fine under Linux but failed instantly when run in Windows.
The problem is that when a file is opened in text mode open("filename", "r") the file is read until EOF is encountered. Thus, open("filename", "rb")

Categories

Resources