首页>Raspberry Pi>source

我正在从rpi向arduino发送一个整数变量.但是,它显示一个错误.其他一切都正确,这是发送数据的代码:-

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub, SubscribeListener
import time
import numpy as np
import cv2
import serial
import RPi.GPIO as GPIO
import logging
#PubNub.set_stream_logger('recieve', logging.DEBUG)
#PubNub.SDK_VERSION
ser=serial.Serial("/dev/ttyACM0",9600)  #change ACM number as found from ls /dev/tty/ACM*
ser.baudrate=9600
ser.flushInput()
GPIO.setmode(GPIO.BOARD)
#GPIO.setup(11, GPIO.OUT)
pnconfig = PNConfiguration()
pnconfig.subscribe_key = "sub-c-fefb53da-045f-11ea-a185-1a72d7432d4b"
pnconfig.publish_key = "pub-c-811efe68-1f19-4cbc-9583-473ef14f04f5"
pnconfig.ssl = False
print("Code Run")
pubnub = PubNub(pnconfig)
print("lol1")
my_listener = SubscribeListener()
print("lol2")
pubnub.add_listener(my_listener)
print("lol3")
pubnub.subscribe().channels('recieve').execute()
print("lol4")
my_listener.wait_for_connect()
print("connected")
#pubnub.publish().channel("my_channel").message('hello there').sync()
result = my_listener.wait_for_message_on('recieve')
print(result.message)
if (result.message == 'point+B'):
        print("msg send")
        time.sleep(1)
        video_capture = cv2.VideoCapture(0)
        print("video activated")
        while(True):
                # Capture the frames
                ret, frame = video_capture.read()
                print("image processing on")
                crop_img = frame[0:1200, 0:700]
                gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
                # Gaussian blur
                blur = cv2.GaussianBlur(gray,(5,5),0)
                # Color thresholding
                ret,thresh = cv2.threshold(blur,60,255,cv2.THRESH_BINARY_INV)
                # Find the contours of the frame
                #contours,hierarchy = cv2.findContours(thresh.copy(), 1, cv2.CHAIN_APPROX_NONE)                    
                _, contours, _= cv2.findContours(thresh.copy(), 1, cv2.CHAIN_APPROX_NONE)
                # Find the biggest contour (if detected)
                if (len(contours) > 0):
                        c = max(contours, key=cv2.contourArea)
                        M = cv2.moments(c)
                        cx = int(M['m10']/M['m00'])
                        cy = int(M['m01']/M['m00'])
                        cv2.line(crop_img,(cx,0),(cx,720),(255,0,0),1)
                        cv2.line(crop_img,(0,cy),(1280,cy),(255,0,0),1)
                        cv2.drawContours(crop_img, contours, -1, (0,255,0), 1)
                        print(cx)
                        #cv2.imshow('frame',crop_img)
                        str(cx)
                        #cx = cx + str('\n')
                        write_ser=ser.write(cx.encode())
                        #write_ser=ser.write(cx)
                        int(cx)
                        if cx >= 450:
                                print ("Turn Right!")
                        if cx < 400 and cx > 300:
                                print ("On Track!")
                        if cx <= 50:
                                print ("Turn Left!")
                        else:
                                print ("I don't see the line")
                    #Display the resulting frame
                    cv2.imshow('frame',crop_img)
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                            break
                    #cap.release()
                    #cv2.destroyAllWindows()

控制台:-

Code Run
lol1
lol2
lol3
lol4
connected
point+B
msg send
video activated
image processing on
222
Traceback (most recent call last):
  File "/home/pi/Desktop/Transporter codes/Final_transporter.py", line 97, in <module>
    write_ser=ser.write(cx.encode())
AttributeError: 'int' object has no attribute 'encode'

我尝试转换为字符串变量,但是没有用.解决方案是什么?

最新回答
  • 9天前
    1 #

    您收到的错误消息说 'int' object has no attribute 'encode'encode   方法仅适用于 str类型的对象

    我相信你想要 str()   威兹威兹   而是将整数转换为 function的字符串(或字节数组)   然后可以使用该功能.您还提到(在注释中),当您向新创建的字符串中添加换行符时,Arduino端仅接收数据:这可能是因为Arduino代码使用的是 write   并正在寻找EOL角色。

    顺便说一句,有些人可能会争辩说,转换 readline   转换为字符串并将其放入相同的变量中,然后添加换行符以进行发送是一种较差的形式,尤其是如果您随后将其转换回整数的话.更加"易读"的代码行更易于查看正在发生的事情,并且更加紧凑,可能类似于...

    cx
    
    # Send CX as an ASCII string over the serial connection, terminate with newline. write_ser = ser.write( str( cx ).encode( 'ascii' ) + b'\n' )

  • pi 3:为什么树莓派3无法读取1000 p / r旋转编码器,而我的8位Nuvoton微控制器却能正确读取呢?
  • OMXPlayer返回"已中止"