user2294001
user2294001

Reputation: 423

type error occurred using buffer memoryview

I wanted to do a program which gets data from serial port which start and stop bit will be * and #. Data received will be in *1234567# this form. But it says my 'type' object is not subscriptable. I'm really new to Python i don't know what to do next, can anyone help me to solve this problem?

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

MAX_BUF_SIZE = 16
bits = 0

v = memoryview



print("connected to: " + ser.portstr)



while(1):
    for memoryview in ser.read():
        if v[0] == 42:

            if v[-1] == 35:

                print(v[1:-1].tobytes())

        else:
            memoryview = 0
ser.close()

connected to: COM5
Traceback (most recent call last):
  File "C:\Python33\Saves\Receive using buff.py", line 24, in <module>
    if v[0] == 42:
TypeError: 'type' object is not subscriptable
>>> 

Upvotes: 0

Views: 177

Answers (1)

Lennart Regebro
Lennart Regebro

Reputation: 172259

What you are doing is wildly over-complicated. I have no idea why you are using memoryview at all. Just do this:

import serial

ser = serial.Serial(
    port='COM5',
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=0)

print("connected to: " + ser.portstr)
for data in ser.read():
    if data[0] == 42 and data[-1] == 35:
           print(data[1:-1].decode())
ser.close()

This is unlikely to actually work as you want, but it's a simplification of your code. How to actually handle it depends on how the data looks more in detail.

Upvotes: 1

Related Questions