TeocraftOP
TeocraftOP

Reputation: 9

python code that seems to not work and says 'name 'myDataone' is not defined'

My code needs to use an ultrasonic sensor on Arduino and I send the data to python to use pygame to make a virtual environment and the code has a problem

import pygame
import serial

pygame.init()
arduinoSerialData = serial.Serial('/dev/cu.usbserial-1410', 9600)
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 0
y = 115

clock = pygame.time.Clock()

##if (arduinoSerialData.inWaiting()>0):
##  myData = arduinoSerialData.readline()

while not done:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      done = True
    if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
      is_blue = not is_blue

  pressed = pygame.key.get_pressed()
  ##if pressed[pygame.K_UP]: y -= 0.1
  ##if pressed[pygame.K_DOWN]: y += 0.1
  ##if pressed[pygame.K_LEFT]: x -= 0.1
  ##if pressed[pygame.K_RIGHT]: x += 0.1
  if (arduinoSerialData.inWaiting()>0):
    myDataone = arduinoSerialData.readline()  
  x = myDataone

  screen.fill((0, 0, 0))
  if is_blue: color = (0, 128, 255)
  else: color = (255, 100, 0)
  pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

  pygame.display.flip()
  clock.tick(60)

It says 'name 'myDataone' is not defined' when it is please help.

Upvotes: 0

Views: 98

Answers (1)

dyz
dyz

Reputation: 127

You'll need to define the case where arduinoSerialData.inWaiting() <= 0.

if arduinoSerialData.inWaiting() > 0:
    myDataone = arduinoSerialData.readline()
else:
    myDataone = ???

x = myDataone

But judging from your code, I think you want to wait until there's data in waiting?

from time import sleep

...

while arduinoSerialData.inWaiting() <= 0:
    sleep(0.2) # set this to something reasonable

myDataone = arduinoSerialData.readline()

x = myDataone

A better solution might be found here

Upvotes: 1

Related Questions