Python + BGE Python to talk to Arduino

I want to run the game engine, and control an object based on arduino inputs. I have the arduino successfully writing to the serial port, it shows when I perform serial monitor. I also have a Blender game, with a code in the python console within Blender. Unfortunately, when I run the script, it says ‘no module named bge’. When I play the game, I can not click “Run script”, yet when I press Alt P , it doesn’t work. The following is the Python code which I pasted in the python console within Blender. It was downloaded from a site, of which the link I have lost.
import bge
import math
from math import *
import mathutils
import time

import sys
#sys.path.append("/usr/lib/python3/dist-packages")
import serial
import glob

port=’’.join(glob.glob("/dev/ttyACM*"))
#port=’’.join(glob.glob("/dev/ttyUSB*"))
#port=’’.join(glob.glob("/dev/rfcomm"))
ser = serial.Serial(port,115200)
print("connected to: " + ser.portstr)

#Connect the suit first and after a ~second launch the script

Get the whole bge scene

scene = bge.logic.getCurrentScene()

Helper vars for convenience

source = scene.objects

Get the whole Armature

main_arm = source.get(‘Armature’)
ob = bge.logic.getCurrentController().owner

def updateAngles():
ser.write(“a”.encode(‘UTF-8’))
s=ser.readline()[:-3].decode(‘UTF-8’) #delete “;\r\n”
angles=[x.split(’,’) for x in s.split(’;’)]
for i in range(len(angles)):
angles[i] = [float(x) for x in angles[i]]

trunk = mathutils.Quaternion((angles[0][0],angles[0][1],angles[0][2],angles[0][3]))
correction = mathutils.Quaternion((0.0, 0.0, 1.0), math.radians(90.0))
trunk_out = correction*trunk   

ob.channels['trunk'].rotation_quaternion = mathutils.Vector([angles[0][0],angles[0][1],angles[0][2],angles[0][3]])

ob.channels['trunk'].rotation_quaternion = trunk_out


ob.update()
time.sleep(0.001)

How can I overcome this issue?
Thanks,

Blender’s python console is talking to Blender ONLY. It has no meaning and no connection towards the BGE.

To use it within a game session, you need to put the code into a text block of the text editor. Then let it execute via a python controller.

Thanks, Managed the previous error, now the error is “no module named serial”
What can it be due to?

This is oyur setup. The python interpreter is telling you it does not know a module with the name “serial”. I guess it is part of your arduino API. It is simply not in your python search path.

To add it to the python search path, you either extend the search path or you place these modules inside the current search path.