I'm trying to print the data that comes across the serial from an Arduino but I am unable to do so. My attempted code is this:
import serial
import time
s = serial.Serial('/dev/tty.usbmodemfd141',9600)
while 1:
if s.inWaiting():
val = s.readline(s.inWaiting())
print val
Yet after about 30 lines or so are spit out I get the following error message:
Traceback (most recent call last):
File "py_test.py", line 7, in <module>
val = s.readline(s.inWaiting())
File "build/bdist.macosx-10.8-intel/egg/serial/serialposix.py", line 460, in read
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I imagine I am using inWaiting incorrectly, but I do not see how to use it any other way.
Have you tried wrapping the readline in a try/except SerialException block? You could then just pass on the SerialException. It could be an issue with the serial driver reporting data in the receive buffer when there is not any, in which case your code will just keep running. Not a great fix, but it may lead you to the correct solution.
try:
s.read(s.inWaiting())
except serial.serialutil.SerialException:
pass # or maybe print s.inWaiting() to identify out how many chars the driver thinks there is
I believe you want to use function read(), not readline(). You are retrieving the number of characters in the buffer, they don't necessarily end with a new-line
Your loop becomes:
while 1:
if s.inWaiting():
val = s.read(s.inWaiting())
print val
if you want to simply print the data coming out of the serially connected device.you can
simply do it by using readline().
first open the port by using open() then you need to use the readline().
note:/dev/ttyUSB0 is a port number for linux and com0 is windows
here is the code
import serial
BAUDRATE = 115200
device_name = "ttyUSB0"
tty = device_name
s = serial.Serial("/dev/" + tty, baudrate=BAUDRATE)
s.open()
print s
try:
while True:
line = s.readline() //after this you can give the sleep time also as time.sleep(1) before that import time module.
print line
finally:
s.close()
Related
I wrote a program in Python-3.6.2 on Windows 10. I want get the CPU serial number.
Here is my code:
def getserial():
# Extract serial from cpuinfo file
cpuserial = "0000000000000000"
try:
f = open('/proc/cpuinfo','r')
for line in f:
if line[0:6]=='Serial':
cpuserial = line[10:26]
f.close()
except:
cpuserial = "ERROR000000000"
return cpuserial
print(getserial())
When I run the program, it prints: ERROR000000000.
How do I fix it?
Your code doesn't let any exception raised. So, you don't see the error: There is no '/proc/cpuinfo' file on Windows.
I have rewrite your code like that:
def getserial():
# Extract serial from cpuinfo file
with open('/proc/cpuinfo','r') as f:
for line in f:
if line[0:6] == 'Serial':
return line[10:26]
return "0000000000000000"
First, I have a with statement to use the file context manager: whenever an exception is raised or not, your file will be closed.
And I simplify the loop: if it found a "Serial" entry, it returns the value.
EDIT
If you have python with a version >= 2.6 you can simply use
import multiprocessing
multiprocessing.cpu_count()
http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
EDIT2
The best solution I found to get the "cpuinfo" is with the py-cpuinfo library.
import cpuinfo
info = cpuinfo.get_cpu_info()
print(info)
But, I think that "Serial" entry is not standard. I can't see it on classic systems.
I've been using code on my RPi2 to communicate to an RS485 Shield to drive various relays. I recently got a RPi3, and the code that has previously worked on the RPi2 has an error on the RPi3.
To begin with, I know that the uart (/dev/ttyAMA0) is "stolen" on the RPi3 for the bluetooth controller. Using this post, I reassigned the uart to the GPIO header so the RS485 shield should work as before. I give you this history, even though I suspect the problem is not with the hardware per se.
Here's the problem. When I execute the code below on the RPi3, I get an error:
Traceback (most recent call last):
File "serialtest.py", line 15, in <module>
if usart.is_open:
AttributeError: 'Serial' object has no attribute 'is_open'
Obviously, within the pySerial library, the serial object DOES have the 'is_open' attribute. Any suggestions on why this error is thrown? I haven't found any references to this specific error in web searches.
#!/usr/bin/env python
import serial
import time
import binascii
data = "55AA08060100024D5E77"
usart = serial.Serial ("/dev/ttyAMA0",19200)
usart.timeout = 2
message_bytes = data.decode("hex")
try:
usart.write(message_bytes)
#print usart.is_open # True for opened
if usart.is_open:
time.sleep(0.5)
size = usart.inWaiting()
if size:
data = usart.read(size)
print binascii.hexlify(data)
else:
print('no data')
else:
print('usart not open')
except IOError as e :
print("Failed to write to the port. ({})".format(e))
If you have an old version of pyserial on the Raspberry Pi, pyserial might not have the is_open, but isOpen() method instead. The isOpen() method was depricated in version 3.0 according to the documentation. You can check the pyserial version with serial.VERSION.
I trying to open two serial ports in Python with the following code:
for i in range(0, 2):
if platform.system() == "Darwin":
pos = 2+i
else:
pos = i
port = serial.Serial(current_ports[pos], BAUD_RATE, timeout=TIMEOUT)
time.sleep(1.516)
port.write('#')
time.sleep(1.516)
out = ''
print "Reading MAC Address...."
while port.inWaiting() > 0:
out += port.read(1)
print out
if out == '04:E9:E5:00:EC:51':
led_port = port
elif out == '04:E9:E5:01:0C:E0':
matrix_port = port
Sometimes the ports open successfully, sometimes they don't. When they don't, I get this error message:
Reading MAC Address....
Traceback (most recent call last):
File "animation.py", line 227, in <module>
main()
File "animation.py", line 208, in main
led_port, matrix_port = get_ports()
File
"/Users/collinschupman/Documents/FutureCities/MurmurWall/Onsite/Raspi/helper_functions.py", line 41, in get_ports
while port.inWaiting() > 0:
File "/Library/Python/2.7/site-packages/serial/serialposix.py", line 449, in inWaiting
s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
IOError: [Errno 6] Device not configured
As you can see, it gets to the inWaiting() call and then throws this error.
For a little reference, the code is sending a message to a couple Arduinos so they can be identified by their MAC addresses.
Is there anything blatantly incorrect I'm doing Python-side which would cause this setup to fail once and a while? I'd say this code works 50% of the time right now.
Thanks,
Collin
Is there a getty process running on the serial ports on the Arduinos? Or even on the serial port of the local machine which is connecting to the Arduinos? If so perhaps it is interfering and should be stopped. Here is a reference which may be relevant: http://codeandlife.com/2012/07/29/arduino-and-raspberry-pi-serial-communication/
I had similar problem and I fixed it with the following solution
$ sudo nano /etc/inittab
and go to the bottom of the file, you will see
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
or similar
simply add a # character to the beginning,now it looks like :
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
save the file and reboot
Hope this works
Reference:
http://www.hobbytronics.co.uk/raspberry-pi-serial-port
I'm trying to write a python script to read values from the arduino's serial port and write it to a file so I can log the data.
The arduino code is long and complicated, but I'm using Serial.println() to print an integer to the serial port (located at /dev/ttyACM0)
import sys
import serial
import getpass
import datetime
import instrumentDriver
"""location of the arduino"""
location = '/dev/ttyACM0'
"""Connect to the arduino"""
arduino = instrumentDriver.serialDevice(location)
"""Successfully connected!"""
filename = str(sys.argv[1])
dataFile = open(filename+'.dat','w')
"""The main loop -- data is taken here and written to file"""
while True:
try:
datum = arduino.read()
print datum
dataFile.write(datetime.datetime.now().strftime("%Y-%m-%d"))
dataFile.write('\t')
dataFile.write(datum)
dataFile.write('\n')
except:
dataFile.close()
break
The instrumentDriver.py is just a wrapper for pySerial:
class serialDevice:
def __init__(self,location):
self.device = location
self.port = serial.Serial(location,9600)
def write(self,command):
self.port.write(command)
def read(self):
return self.port.readline()
I've used this block of code years ago and it worked fine, but it seems to be failing right now and I'm not entirely sure why. I get a SyntaxError on line 45:
scottnla#computer-1 ~/Documents/sensorTest $ python readSerial.py file
File "readSerial.py", line 45
print datum
^
SyntaxError: invalid syntax
I've tried changing the print statement, but no matter what I'm printing, I get a syntax error -- I speculate that the problem may actually be with the arduino.read() line.
Any advice would be greatly appreciated!
There is still an indentation issue; rewritten as below, it should run:
import sys
import datetime
class serialDevice:
def __init__(self,location):
self.device = location
self.port = sys.stdin # changed to run on terminal
def write(self,command):
self.port.write(command)
def read(self):
return self.port.readline()
"""location of the arduino"""
location = '/dev/ttyACM0'
"""Connect to the arduino"""
arduino = serialDevice(location)
"""Successfully connected!"""
filename = str(sys.argv[1])
dataFile = open(filename+'.dat','w')
"""The main loop -- data is taken here and written to file"""
while True:
try:
"""retrieve the raw analog number from the arduino's ADC"""
datum = arduino.read()
"""write it to file, along with a timestamp"""
print datum
dataFile.write(datetime.datetime.now().strftime("%Y-%m-%d"))
dataFile.write('\t')
dataFile.write(datum)
dataFile.write('\n')
except KeyboardInterrupt:
"""this allows for the user to CTRL-C out of the loop, and closes/saves the file we're writing to."""
dataFile.close()
break
'Hello,
I'm kinda lost after several hours trying different things. I have included my code. I'm tring to get a 5 digit number to the arduino, but I get an error when trying to send a number range. I'm not a seasoned programmer, but I have quit a lot of experience with the arduino. I can receive from the Arduino with no problem.
A piece of the testcode:
import serial
import time
import struct
ser = serial.Serial(
port='COM15',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
time.sleep(3)
print("connected to: " + ser.portstr)
#this will store the line
bline = []
while True:
ser.write(10128)
time.sleep(1)
ser.write(10000)
time.sleep(1)
ser.close()
The Error:
connected to: COM15
Traceback (most recent call last):
File "C:/Users/Danny/Documents/arachnoid-0.5/testreceive.py", line 19, in <module>
ser.write(10128)
File "C:\Python33\lib\site-packages\serial\serialwin32.py", line 283, in write
data = to_bytes(data)
File "C:\Python33\lib\site-packages\serial\serialutil.py", line 75, in to_bytes
for item in seq:
TypeError: 'int' object is not iterable
>>>
Since serial communication is for bytes, you would need to convert the int to a byte string. In python 3 this would need to be encoded.
I believe this should do it:
ser.write(str(10128).encode())
You need to pass a string to write, not an int.
To get 5 digits always with leading zeros if necessary:
ser.write(str(100000 + 10128)[-5:])
The addition makes it a 6-digit number, and the [-5:] slices off the last 5 digits of the result. Of course that's the hacky way to do it, I keep forgetting how to use format to do it properly.
ser.write('{0:05d}'.format(10128))