Please help me find problem in this code:
import serial
ser=serial.Serial("/dev/ttyACM0",9600)
ser.baudrate=9600
ser1=serial.Serial("/dev/ttyUSB0",9600)
ser1.baudrate=9600
ser2=serial.Serial("/dev/ttyUSB1",9600)
ser2.baudrate=9600
while True:
read_ser=ser.readline()
read_ser1=ser1.readline()
read_ser1=ser2.readline()
print(read_ser)
print(read_ser1)
print(read_ser2)
I expect that it will show me message from connected Arduino. Arduino send it when I apply card to RFID reader. But, it send only from first ser
This code works as I expected
import serial
ser=serial.Serial("/dev/ttyACM0",9600,timeout=1)
ser.baudrate=9600
ser1=serial.Serial("/dev/ttyUSB0",9600,timeout=1)
ser1.baudrate=9600
ser2=serial.Serial("/dev/ttyUSB1",9600,timeout=1)
ser2.baudrate=9600
while True: # Run forever
read_ser=ser.readline()
if (read_ser != ""):
print(read_ser)
read_ser1=ser1.readline()
if (read_ser1 != ""):
print(read_ser1)
read_ser2=ser2.readline()
if (read_ser2 != ""):
print(read_ser2)
Thank you #jasonharper
Related
I am trying to make a program which constantly reads data being sent from device using serial port to computer. In addition to this whenever I enter something it is sent to device.(My main aim is to make a serial terminal emulator).
I wrote following program but it waits for any input and does not constantly read data and display on screen sent by device as thought:
ser1 = serial.Serial(com_name_to_use, auto_baud, timeout=0, write_timeout=0)
while True:
try:
# Writing Section
inp_str1 = input() # + "\n"
str1 = inp_str1.encode(encoding="ascii")
ser1.write(str1)
time.sleep(0.03)
# Reading Section
bf = ser1.readline()
print(str(bf, encoding="utf-8"), end="")
except Exception as err1:
pass
Kindly, tell how to fix it.
I am trying to capture my temperature sensor reading from Arduino Uno, turn on AC if temperature is high or off and then send temperature to Raspberry Pi and write to a log file.
My Python code in Raspberry Pi to capture event and log to a file.
import time
import datetime
import serial
now = datetime.datetime.now()
month=time.strftime("%Y_%m")
#f= open(month+".txt","w+")
f=open("temperature.log","w+")
ser = serial.Serial('/dev/ttyACM0', 9600) # enable the serial port
print 'before while'
while 1: # execute the loop forever
val=ser.readline()
# read the serial data sent by the UNO
f.write(now.strftime("%Y-%m-%d %H:%M"))
# print the serial data sent by UNO
f.write(' -> ')
f.write(val)
f.close()
I can get the temperature value (sometimes it's a mess 16707), but most importantly it does not write to the log file.
Where am I missing? Do I have to include another library in the Python code?
You are closing the log file at the end of each loop. It should run once, but after the file is closed, it won't write again until you open it. Just put f.close() after the while loop. Or as a better practice:
ser = serial.Serial('/dev/ttyACM0', 9600)
with open("temperature.log", "w+") as f:
print 'before while'
while 1:
val = ser.readline()
f.write(now.strftime("%Y-%m-%d %H:%M"))
f.write(' -> ')
f.write(val)
This will close the file automatically once the code inside the with statement is finished.
I am trying to communicate an Arduino using python. I was able to connect it using the serial module. This is the code:
import serial
while True:
print "Opening port"
arduinoData = serial.Serial("com7", 9600)
print "The port is open"
while (arduinoData.inWaiting()==0): #I wait for data
print "There is no data"
print "Reading data"
arduinoString = arduinoData.readline()
print arduinoString
It seems that is hanging when I want to read the data, in the line that says arduinoString = arduino.readline().
What could be the problem?
instead using the while loop inside of the main while loop you can use an if else statement. Also, to read the data you can use the read function with arduinoData.inWaiting() as the paramater like this : arduinoData.read(arduinoData.inWaiting()). I hope this code will help you:
arduinoData = serial.Serial("com7", 9600)
while True:
if arduinoData.inWaiting() > 0: # check if there is data available
print "Reading data"
arduinoString = arduinoData.read(arduinoData.inWaiting()) '''read and decode data'''
print arduinoString
else:
print "There is no data"
The structure of your code is strange. I had a similar issue by creating the Serial object in a function without making it global. Maybe you should put this line outside the loop :
arduinoData = serial.Serial("com7", 9600)
Also, your initialization seems a bit light. I usually use more parameters but it depends of your hardware.
ser = serial.Serial(
port = 'com4', \
baudrate = 19200, \
parity=serial.PARITY_NONE, \
stopbits=serial.STOPBITS_ONE, \
bytesize = serial.EIGHTBITS, \
timeout = 0.25)
A workaround for your readline() issue coud be using the read() function instead and checking if it contains data.
Hope it will help !
Alright, you are getting the AttributeError: 'Serial' object has no attribute 'ser' error because in reality ser does not exist in the arduinoData object. It's my fault because I was thinking of the class that I created in my program containing ser which is just the another serial object. To fix this just replace arduinoData.ser with arduinoData
To add on, you should probably declare arduinoData outside of the while loop. you should do this because every time the you create a serial object it takes time to connect to the Arduino. For this, your program might not be able to read the data.
I hope this answer will help you.
I have a small python example I got off another website. I am trying to understand how to read from serial using it.
I am sending a message from a FRDM K64f board over serial and the python program reads this but returns a strange values, below is an example of one of them:
YVkJ�ZC
My python code:
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
This is my code for the board:
int main(){
Serial pc(USBTX, USBRX);
pc.baud(9600);
while(1){
char c = pc.getc();
if((c == 'w')) {
pc.printf("Hello");
}
}
}
The exact return I get is this:
Enter your commands below.
Insert "exit" to leave the application.
>> w
>>YVkJ�ZC
>>
Managed to solve this.
My declaration of serial didn't seem to be working properly.
Went back to pyserial documentation and declaring my serial like below and using readline() solved the problem.
ser = serial.Serial('/dev/ttyACM0')
I have the following program of python which displays serial data in the command prompt.
#!python
import time
import cgi
from serial import Serial
import subprocess
ser = Serial('COM4', 115200, timeout=1)
print("connected to: " + ser.portstr)
while True:
# Read a line and convert it from b'xxx\r\n' to xxx
line = ser.readline().decode('utf-8')[:-2]
if line: # If it isn't a blank line
print(line)
if line == '520':
subprocess.call(["xte", "key Up"])
elif line == '620':
subprocess.call(["xte", "key Down"])
elif line == '110':
break
ser.close()
This program is running perfect. The data is being constantly displayed in the console. Basically it is displaying the distance from a ping sensor I want to display the data in the web page http://localhost/distance.html. How will I do it? Displaying only the last data will be fine. Thanks for all the suggestions
Write the data to a file. Serve that file with a webserver like for example Apache.