Im trying to write a script that will constantly listen to a serial device and write everything to a file. But its not writing anything to the file. What am I doing wrong?
import serial
import time
i = 0
ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)
while True:
readOut = ser.readline().decode('ascii')
file = open("output.txt","w")
file.write(readOut)
file.close()
You're opening it as w each time, which erases the content. Change to:
import serial
import time
i = 0
ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)
while True:
readOut = ser.readline().decode('ascii')
file = open("output.txt","a")
file.write(readOut)
file.close()
Related
I am trying to develop gui with wxpython by using serial port. But I need to use serial port resource concurrency for saving data all times and plotting graphics. For this, I used wx.Timer but couldnt succeed on it. The below code just sample:
import serial
ser = serial.Serial('COM9',9600)
def update(self, event):
global ser
timerId = event.GetId()
if timerId == TIMER_ID1:
print("hello")
for line in ser:
print(line)
print("world")
else:
x=[]
x1=[]
x2=[]
y=[]
y1=[]
y2=[]
i=0
#fig = plt.figure()
def sV_sat(i):
for line in ser:
data=line.split(b",")
if data[0] == b"$GPGSV":
print("c")
sView_GP = data[3]
sNumber_GP = data[4]
i=i+1
x.append(i)
#x=[i]
y.append(float(sView_GP))
ax.set_title("GPS")
ax1.set_title("GPS-GLO")
ax1.set_ylim(0,20)
ax.bar(i,y,color='green') #only GPS #option 2
ax1.plot(x,y,'g') #GPS ve ...
#time.sleep(0.1)
ani8 = animation.FuncAnimation(fig,sV_sat)
plt.legend()
#pyplot.show()
plt.show()
print (time.ctime())
The above code gave me graphics but it couldn't give print(line):(9th line)
print("hello")
for line in ser:
print(line)
print("world")
Just print: hello and world with graphics
hello
world
The second serial line(line 21) give me graphics. Thats ok. Why first one(line 8) is skipped? Any helps will be appreciated. Thanks a lot.
Just reading the documentation for pySerial suggests that you have to read the serial port.
i.e.
Open named port at “19200,8,N,1”, 1s timeout:
>>> import serial
>>> with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser:
... x = ser.read() # read one byte
... s = ser.read(10) # read up to ten bytes (timeout)
... line = ser.readline() # read a '\n' terminated line
Open port at “38400,8,E,1”, non blocking HW handshaking:
>>> import serial
>>> ser = serial.Serial('COM3', 38400, timeout=0,
... parity=serial.PARITY_EVEN, rtscts=1)
>>> s = ser.read(100) # read up to one hundred bytes
... # or as much is in the buffer
In this script I am taking the temperature from a DHT11 sensor and parsing the data that another script can read. Everything works except for writing the file to another pc using the path I placed in the f = open part of the script below. Everything works great except that the file doesn't get written or saved.
Any Help?
#!/usr/bin/env python
# encoding: utf-8
import sys
import time
import dht11
import RPi.GPIO as GPIO
#define GPIO 14 as DHT11 data pin
Temp_sensor=14
def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
instance = dht11.DHT11(pin = Temp_sensor)
while True:
#get DHT11 sensor value
result = instance.read()
temp = '{:.0f}'.format(result.temperature * 1.8 + 32)+"°"
# The path to send the txt file to and save is /10.1.1.28/c$/Temperature_RETR/kvoa_temp.txt
if result.is_valid():
print temp
f = open('\\10.1.1.28\c$\Temperature_RETR\new_temp.txt','w')
#f = open('/home/pi/Desktop/new_temp.txt','w')
y = temp
z = str(y)
f.write(z)
f.close()
time.sleep(60) # 60 second delay
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
I'm trying to collect serial data from a device, timestamp and export it to a .csv file.
The following program writes date and time to csv but not the data returned from the device module:
import time
import csv
import fio2
def Csv_creator():
my_file = open('test_csv.csv', 'w+')
with my_file:
new_file = csv.writer(my_file)
def Timestamp():
date_now = time.strftime('%d/%m/%y')
time_now = time.strftime('%H:%M:%S')
return [date_now,time_now]
def Write_loop():
Csv_creator()
fio2.Initialize()
with open('test_csv.csv', 'a') as f:
csv_file = csv.writer(f)
for num in range(0,20):
[date_now,time_now] = Timestamp()
fio2_data = fio2.Reader()
print(fio2_data)
csv_file.writerow([date_now,time_now,fio2_data])
Write_loop()
The device module is as shown below. It returns the data and I'm able to print it. The only problem is not being able to write it on to the csv file.
import serial
ser = serial.Serial("COM4",
baudrate=2400,
bytesize=serial.EIGHTBITS,
parity =serial.PARITY_ODD)
def Initialize():
global ser
try:
ser.isOpen()
print("\n Serial is open")
except:
print ("Error: serial Not Open")
def Reader():
global ser
if (ser.isOpen()):
try:
x = ser.readline().decode()
x = (x)
return x
except:
return "unable to print"
else:
return "cannot open serial port"
I figured it out. I had to remove some garbage letters that were associated with the decimal values. First, I change the received data to string and replaced the garbage letters. Here's how I changed it:
[date_now,time_now] = Timestamp()
fio2_data = str(fio2.Reader()).replace("\r\n","")
fio2_data = fio2_data.replace("\x000","")
write_list = [date_now,time_now,fio2_data]
I am using 2 XBee pro S1, I want to read the packets received by the co-ordinator on my PC , it is enabled with API_2 and all other connections are done properly, I can see the packets with XCTU, I am using the python xbee library , but it gives no output :
The Code :
import serial.tools.list_ports
from xbee import XBee
import serial
ports = list(serial.tools.list_ports.comports())
for p in ports: #print the list of ports
print p
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0'+hv
hv = '0x' + hv
lst.append(hv)
def decodeReceivedFrame(data):
source_addr_long = toHex(data['source_addr_long'])
source_addr = toHex(data['source_addr'])
id = data['id']
samples = data['samples']
options = toHex(data['options'])
return [source_addr_long, source_addr, id, samples]
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
ser = serial.Serial(PORT, BAUD_RATE)
print "Serial ports initialised...."
xbee = XBee(ser,escaped=True)
print "XBee object created"
while True:
try:
response = xbee.wait_read_frame()
sleep(0.5)
decodedData = decodeReceivedFrame(response)
print decodedData
print "data decoded"
except KeyboardInterrupt:
break
ser.close()
The port number and baudrate are connect, I change it to the appropriate portnumber every time I replug the coordinator to my PC.
My output looks like :
Serial ports initialised....
XBee object created
It stays like that and gives no output, even if I see the RX led blinking.
Below is the code written with only pyserial :
import serial
from time import sleep
port = '/dev/ttyUSB0'
baud = 9600
ser = serial.Serial(port, baud)
data = ""
while True:
try:
while ser.in_waiting:
sleep(1)
data = ser.read()
print data
except KeyboardInterrupt:
break
ser.close()
It gives the following output.
Could someone kindly help.
Are you sure you have the correct serial port and baud rate? Does the xbee package support API mode 2? It might only work with API mode 1.
Does that package have methods for accessing the raw byte stream instead of trying to read frames? Can you configure it to throw exceptions on parsing errors?
I would start with just printing response until you see that you're receiving data. And why include the sleep() call in that loop?
I'm not sure what you're trying to accomplish in toHex() but you might want to look at the Python method struct.unpack() or replace all of the work you do on hv with '0x%02X' % ord(ch).
First of all I am a complete noobie when it comes to python. Actually I started reading about it this morning when I needed to use it, so sorry if the code is a disaster.
I'd like to get this done:
A communication via serial between two devices. The device where the python program is running has to be listening for some data being sent by the other device and storing it in a file. But every 30 seconds of received data it has to send a command to the other device to tell it to stop sending and begin a scan that takes 10 seconds.
This is the code I've written. It's printing continuously Opening connection..
from serial import Serial
from threading import Timer
import time
MOVE_TIME = 30.0
SCAN_TIME = 10.0
DEVICE_ADDRESS = '/dev/ttyACM0'
BAUD_RATE = 9600
while True:
try:
print("Opening connection...")
ser = Serial(DEVICE_ADDRESS, BAUD_RATE
break
except SerialException:
print("No device attached")
def scan():
print("Scanning...")
timeout = time.time() + SCAN_TIME
while True:
#Some code I haven't thought of yet
if time.time() > timeout:
ser.write(b'r') #command to start
break
def send_stop_command():
print("Sending stop command")
ser.write(b's') #command to stop
scan()
t = Timer(MOVE_TIME + SCAN_TIME, send_stop_command)
t.start()
filename = time.strftime("%d-%m-%Y_%H:%M:%S") + ".txt"
while True:
data = ser.readline()
try:
with open(filename, "ab") as outfile:
outfile.write(data)
outfile.close()
except IOError:
print("Data could not be written")