S. R. Colledge
S. R. Colledge

Reputation: 111

What is causing this "TypeError: a bytes-like object is required, not 'str'" error?

I know this may be a petty issue but I seriously couldn't find a solution to this problem. I am using this code:

# Import the modules
from __future__ import division
import spidev, datetime, time
from sys import exit
import RPi.GPIO as GPIO

# Setup SPI
spi = spidev.SpiDev()
spi.open(0, 0)
spi.mode = 3

# Constants
accres = 16
accrate = 15

# Set GPIO chip select pins
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
cs1 = 23
cs2 = 24
motor = 18
GPIO.setup(cs1, GPIO.OUT)
GPIO.setup(cs2, GPIO.OUT)
GPIO.setup(motor, GPIO.OUT)

# Note: the duty cycle goes from 0.0 to 100.0, with 100.0 being no motor movement,
# and 0.0 being the maximum motor speed.
motor_output = GPIO.PWM(motor, 60)

# Initialize the ADXL345
def initadxl345():
    # Set data rate (accrate=15 -> 3200 Hz, 14=1600 Hz, 13=800 Hz, 12=400 Hz, 11=200 Hz, 10=100 Hz etc.)
    spi.xfer2([44, accrate])

    # Enable full range (10 bits resolution) and +/- 16g 4 LSB
    spi.xfer2([49, accres])

# Read the first ADXL x-y-z axes
def readadxl345_1():
    # Chip select pin ensures that the first sensor is being read by grounding its pin
    GPIO.output(cs1, 0)
    GPIO.output(cs2 ,1)

    rx = spi.xfer2([242, 0, 0, 0, 0, 0, 0])
    out = [rx[1] | (rx[2] << 8), rx[3] | (rx[4] << 8), rx[5] | (rx[6] << 8)]
    # Format x-axis
    if (out[0] & (1 << 16 - 1 )):
        out[0] = out[0] - (1 << 16)
    # Format y-axis
    if (out[1] & (1 << 16 - 1 )):
        out[1] = out[1] - (1<<16)
    # Format z-axis
    if (out[2] & (1 << 16 - 1 )):
        out[2] = out[2] - (1 << 16)
    # Return human readable values
    return out

# Read the second ADXL x-y-z axes
def readadxl345_2():
    # Chip select pin ensures that the first sensor is being read by grounding its pin
    GPIO.output(cs1, 1)
    GPIO.output(cs2 ,0)

    rx = spi.xfer2([242, 0, 0, 0, 0, 0, 0])
    out = [rx[1] | (rx[2] << 8), rx[3] | (rx[4] << 8), rx[5] | (rx[6] << 8)]
    # Format x-axis
    if (out[0] & (1 << 16 - 1 )):
        out[0] = out[0] - (1 << 16)
    # Format y-axis
    if (out[1] & (1 << 16 - 1 )):
        out[1] = out[1] - (1<<16)
    # Format z-axis
    if (out[2] & (1 << 16 - 1 )):
        out[2] = out[2] - (1 << 16)
    # Return human readable values
    return out

print("Vibration Reader Initializing...")
time.sleep(1)
print(GPIO.RPI_INFO)

response = input("Proceed measurements? [Y, n]")
pwm_speed = float(input("Motor PWM value: "))

if response == "Y" or "y":
    # Initialize the ADXL345 accelerometer
    print("Initializing ADXL345s...")
    initadxl345()
    motor_output.start(pwm_speed)

    timeout = 0.0003125 / 2 # timeout=1/samplerate=>not sufficient measurements. Half the time is sufficient (don't know why!)

    timetosend = 1

    while(1):
       with open('/proc/uptime', 'r') as f: # get uptime
           uptime_start = float(f.readline().split()[0])
       uptime_last = uptime_start
       active_file_first = "10bit" + str(accres) + 'g' + '.csv'
       file = open('/var/log/sensor/' + active_file_first, 'wb')
       while uptime_last < uptime_start + timetosend:

           time1 = str(datetime.datetime.now().strftime('%S.%f'))
           sensor1 = readadxl345_1()
           sensor2 = readadxl345_2()
           file.write(str(sensor1[0]) + ',' + str(sensor1[1]) + ',' + str(sensor1[2]) + ',' + str(sensor2[0]) + ',' + str(sensor2[1]) + ',' + str(sensor2[2]) + ',' + time1 + '\n')

           # Print data every "timeout" second
           elapsed = time.clock()
           current = 0
           while(current < timeout):
               current = time.clock() - elapsed

    motor_output.stop
    print("Motor shutting off and cleaning up GPIO.")
    GPIO.cleanup()

elif response == "N" or "n":
    print("Quitting...")
    time.sleep(1)
    quit()

and the interpreter gives an issue with line 106, saying

Traceback (most recent call last):
  File "accelerometer.py", line 106, in <module>
    file.write(str(sensor1[0]) + ',' + str(sensor1[1]) + ',' + str(sensor1[2]) + ',' + str(sensor2[0]) + ',' + str(sensor2[1]) + ',' + str(sensor2[2]) + ',' + time1 + '\n')
TypeError: a bytes-like object is required, not 'str'

Does anyone have an idea how to fix this or improve/streamline the code? I am using Python 3.8.1 and I am doing it on a Linux machine.

Upvotes: 0

Views: 44

Answers (1)

Prashant Kumar
Prashant Kumar

Reputation: 2092

You have opened the file in "wb" mode for writing.

file = open('/var/log/sensor/' + active_file_first, 'wb')

So it is expecting the data to be written in the file to be byte objects.

You need to convert the string you are writing into byte object or maybe change the mode in which you opened the file to "w" mode.

file = open('/var/log/sensor/' + active_file_first, 'w')

Upvotes: 1

Related Questions