ValueError: invalid literal for float() - python

I am trying to read lightware rangefinder SF11 through serial but using Raspberry, and I am not familiar with Python, but I tried this:
import time
import serial
print('Code is Running.')
# Make a connection to the com port.
serialPortName = '/dev/ttyUSB0'
serialPortBaudRate = 115200
port = serial.Serial(serialPortName, serialPortBaudRate, timeout=0.1)
port.write('www\r\n')
port.readline() # Read and ignore any unintended responses
port.write('?\r\n') # Get the product information
productInfo = port.readline()
print('Product information: ' + productInfo)
while True:
port.write('LD\r\n') # reading distance (First return, default filtering)
distanceStr = port.readline()
distanceCM = float(distanceStr) * 100 # Convert the distance string into a number
print(distanceCM)
time.sleep(0.05) # Wait for 50ms before the next reading
When I run the code it's turn this:
Traceback (most recent call last):
File "range.py", line 25, in <module>
distanceCM = float(distanceStr) * 100 # Convert the distance string into a number
ValueError: invalid literal for float(): 1.72 m 0.086 V

Related

Snap7 get_real command not working, how to fix?

client = snap.client.Client()
client.connect('XXX.XXX.X.XXX', 0, 2) #IP address, rack, slot
db = client.db_get(20)
print(db)
intDB = []
for i in range(1, 122):
reading = client.db_read(20, i, 1)
realReading = snap.util.get_real(reading, 0)
array = [realReading]
intDB.append(array)
print(intDB)
This code is supposed to print a DB in bytearrays and then print an array with the floats values of the PLC output. However, when I run the code, I get the following error message:
Traceback (most recent call last):
File "C:/Users/Asus/PycharmProjects/PLC-Connection/main.py", line 19, in <module>
realReading = snap.util.get_real(reading, 0)
File "C:\Users\Asus\PycharmProjects\PLC-Connection\venv\lib\site-packages\snap7\util.py", line 357, in get_real
real = struct.unpack('>f', struct.pack('4B', *x))[0]
struct.error: pack expected 4 items for packing (got 1)
I think that the problem is reading the data:
reading = client.db_read(20, i, 1)
20 is the datablock, i is the index, and you read only 1 byte (3rd parameter).
For retrieving a real, you need 4 bytes read out.

TypeError: 'in <string>' requires string as left operand, not bytes,python

I have an error when executing a script made in python that occupies telnet, at the moment of executing I get the error that I indicate at the end. This error is executed by the line that I mention in the code but I could not find any solution , I hope you can help me solve it.
Code:
def simulate(location,loggers,sensors,host,port,interval):
'''Simulate the reception of oxygen data to cacheton '''
temp_range = MAX_TEMP - MIN_TEMP
o2_range = MAX_O2 - MIN_O2
t = 0.0
steps = -1
while 1:
for logger in loggers:
for sensor in sensors:
temp1 = random.random() * temp_range + MIN_TEMP
oxi1 = random.random() * o2_range + MIN_O2
unix_time = int(time.time())
command = "PUT /%s/oxygen/%i/%i/?oxy=%.1f&temp=%.1f&time=%i&depth=1&salinity=32&status=1" % (location, logger, sensor, oxi1, temp1, unix_time)
print (command)
tn = telnetlib.Telnet(host,port)
tn.write(command+"\n\n")#here is theerror
tn.write("\n")
tn.close()
t += interval
if steps > 0: steps -= 1
if steps == 0: break
time.sleep(interval)
Error:
Traceback (most recent call last):
File "simulate_oxygen_cacheton.py", line 57, in <module>
simulate(args.location, range(loggers), range(sensors), args.host, args.port, args.interval)
File "simulate_oxygen_cacheton.py", line 29, in simulate
tn.write(command+"\n\n")
File "/home/mauricio/anaconda3/lib/python3.7/telnetlib.py", line 287, in write
if IAC in buffer:
TypeError: 'in <string>' requires string as left operand, not bytes
The problem here is that in telnetlib.py, IAC is of type bytes but your command+"\n\n" is of type str. You may also need to convert any strings you are passing to tn.write() into byte strings by feeding them through str.encode()
Try:
tn.write(str.encode(command+"\n\n"))

Python code not storing readings in a .csv file. "sequence expected" error recieved. Any idea how to fix this?

I was applying a code that reads the coordinates from a gps and fills it in a .csv file.i am new to all of this so i can't get my head around this problem. I have used the "csv" code in other programs and it has worked. But here it is giving me a hard time. The error is as follows:
Traceback (most recent call last):
File "GPScodetest2.py", line 48, in <module>
data_writer.writerow(data)
_csv.Error: sequence expected
How to fix this?
P.S the code:
from time import sleep, strftime, time
import serial
import pynmea2
import datetime
from csv import writer
#setup the serial port to which gps is connected
port = "/dev/ttyS0"
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
dataout = pynmea2.NMEAStreamReader()
counter = 0
def get_sense_data():
while True:
newdata = ser.readline()
if newdata[0:6] == '$GPGGA':
parsed_line = pynmea2.parse(newdata)
latitude_reading = parsed_line.latitude
alpha = latitude_reading
#print(newlat)
longitude_reading = parsed_line.longitude
beta = longitude_reading
#print(newlong)
#print(latitude_reading)
#print(longitude_reading)
sense_data=[]
sense_data.append(counter)
sense_data.append(datetime.datetime.now())
sense_data.append(alpha)
sense_data.append(beta)
return sense_data
with open('GPSdata.csv', 'w+') as f:
data_writer = writer(f)
data_writer.writerow(['Term No.','Date and Time','Latitude',
' Longitude'])
while True:
data = get_sense_data
data_writer.writerow(data)
counter = counter + 1
You aren't calling the function:
data = get_sense_data
Try calling it:
data = get_sense_data()

Python - send uint8 and uint16 to socket

I'm trying to send some data with a python script to a java server. I use the socket module in python to send and recieve data.
When I send data, I need to specify a header with the datalength in it. The header is as following:
a uint8 for the version number
a uint8 for padding ('reserved')
a uint16 for the length of the data that is sent
That is a total of 32 bits.
I can use numpy to create an array with a certain data type, but the problem is sending this data through the socket. I use the following function to send data:
def send(socket, message):
r = b''
totalsent = 0
# as long as not everything has been sent ...
while totalsent < len(message):
# send it ; sent = actual sent data
sent = socket.send(message[totalsent:])
r += message[totalsent:]
# nothing sent? -> something wrong
if sent == 0:
raise RuntimeError("socket connection broken")
# update total sent
totalsent = totalsent + sent
return r
message = (something_with_numpy(VERSION_NUMBER, PADDING, len(data)))
send(socket, message)
I keep getting TypeErrors with this function. These pop up at len(message), r += message[...], or some other place.
I was wondering if there is a better way to do this, or how to fix this so it does work?
UPDATE: here are some exact error traces. I have tried several different things, so these error traces might have become irrelevant.
Traceback (most recent call last):
File "quick.py", line 47, in <module>
header += numpy.uint8(VERSION_NUMBER)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S3') dtype('S3') dtype('S3')
header = numpy.array([VERSION_NUMBER * 255 + PADDING, len(greetData)], dtype=numpy.uint16)
Traceback (most recent call last):
File "quick.py", line 48, in <module>
print(header + greetData)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S22') dtype('S22') dtype('S22')
Traceback (most recent call last):
File "quick.py", line 47, in <module>
r = send(conn, numpy.uint8(VERSION_NUMBER))
File "quick.py", line 13, in send
while totalsent < len(message):
TypeError: object of type 'numpy.uint8' has no len()
Traceback (most recent call last):
File "quick.py", line 47, in <module>
r = send(conn, numpy.array([VERSION_NUMBER], dtype=numpy.uint8))
File "quick.py", line 17, in send
r += message[totalsent:]
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S3') dtype('S3') dtype('S3')
You'll want to use the struct module to format the header before sending the data.
import struct
def send_message(socket, message):
length = len(message)
version = 0 # TODO: Is this correct?
reserved = 0 # TODO: Is this correct?
header = struct.pack('!BBH', version, reserved, length)
message = header + message # So we can use the same loop w/ error checking
while ...:
socket.send(...)

DHT Sensor Python script error

I have a sensor type DHT22 connected to a raspberry.
I have written a script in python but when I run it I get errors
#!/usr/bin/python
import MySQLdb
import subprocess
import re
import sys
import time
import datetime
import Adafruit_DHT
conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi")
while(True):
date = time.strftime("%d/%m/%Y")
clock = time.strftime("%H:%M")
#output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]);
output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
matches = re.search("Temp =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
temp = float(matches.group(1))
matches = re.search("Hum =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
humidity = float(matches.group(1))
# MYSQL DATA Processing
c = conn.cursor()
c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity))
#print "DB Loaded"
time.sleep(360)
This is the error encountered on running the script:
root#raspberrypi:/home# ./hdt.py
Traceback (most recent call last):
File "./dht.py", line 22, in <module>
matches = re.search("Temp =\s+([0-9.]+)", output)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
Adafruit_DHT.read_retry() does not return string. re.search expects string as second parameter.
Please have a look at code below (taken from Adafruit_Python_DHT/examples):
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)

Categories

Resources