Problem in sending and receiving commands from PC to Arduino via usb serial - pyserial

I am trying to send commands and receive data from Arduino beta Metro M4 express (programmed using circuitpython) via USB. The version of circuitpython is 4.0.1 and Python version is 3.7.3. I could able to send the data via usb but having problems while receiving the data. The command 'supervisor.runtime.serial_bytes_available' reads the command sent from PC via usb but I am receiving the data printed using 'print' statement in the python shell. Also, I cannot able to get and print the command using in 'data = sys.stdin.read(4)' command.
Any help is much appreciated.
My python code is as follows:
import serial
import time
while(1):
ser = serial.Serial(port='COM9', baudrate=115200, timeout=0.01)
cmd = b'what'
print('cmd=', cmd)
ser.write(cmd)
ser.flushInput()
time.sleep(1)
x = ser.readline()
print("received1: ",x.decode("utf-8"))
y = ser.readline()
print("received2: ",y.decode("utf-8"))
ser.close()
Circuitpython code is as follows:
import supervisor
while(x):
if supervisor.runtime.serial_bytes_available:
print("True")
data = sys.stdin.read(4)
print("in code.py",data)
The expected and results received in the python shell are as follows:
Expected result is: received1: True, received2: what
Received results:
cmd= b'what'
received1: hat
received2:
cmd= b'what'
received1: hat
received2:
cmd= b'what'
received1: hat
received2:
cmd= b'what'
received1: hat
received2:
cmd= b'what'
received1: hat
received2:
cmd= b'what'

Related

How to use Micropython Classes in separate files

Getting started with MicroPython and having problems with classes in separate files:
In main.py:
import clientBase
import time
if __name__ == "__main__":
time.sleep(15) # Delay to open Putty
print("Starting")
print("Going to class")
cb = clientBase.ClientBaseClass
cb.process()
In clientBase.py:
class ClientBaseClass:
def __init__(self):
print("init")
def process(self):
print("Process")
Compiles and copies to Pico without errors but does not run. Putty output: No idea how to run Putty (or other port monitor) without blocking port!
MPY: soft reboot
Traceback (most recent call last):
Thanks
Python Conslole:
"C:\Users\jluca\OneDrive\Apps\Analytical Engine\Python\Client\venv\Scripts\python.exe" "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2.4\plugins\python-ce\helpers\pydev\pydevconsole.py" --mode=client --port=59708
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['C:\Users\jluca\OneDrive\Apps\Analytical Engine\Python\Client', 'C:\Users\jluca\AppData\Roaming\JetBrains\PyCharmCE2021.2\plugins\intellij-micropython\typehints\stdlib', 'C:\Users\jluca\AppData\Roaming\JetBrains\PyCharmCE2021.2\plugins\intellij-micropython\typehints\micropython', 'C:\Users\jluca\AppData\Roaming\JetBrains\PyCharmCE2021.2\plugins\intellij-micropython\typehints\rpi_pico', 'C:/Users/jluca/OneDrive/Apps/Analytical Engine/Python/Client'])
PyDev console: starting.
Python 3.10.3 (tags/v3.10.3:a342a49, Mar 16 2022, 13:07:40) [MSC v.1929 64 bit (AMD64)] on win32
The first problem I see here is that you're not properly instantiating the ClientBaseClass object. You're missing parentheses here:
if __name__ == "__main__":
time.sleep(15) # Delay to open Putty
print("Starting")
print("Going to class")
cb = clientBase.ClientBaseClass # <-- THIS IS INCORRECT
cb.process()
This is setting the variable cb the class ClientBaseClass, rather than creating a new object of that class.
You need:
if __name__ == "__main__":
time.sleep(15) # Delay to open Putty
print("Starting")
print("Going to class")
cb = clientBase.ClientBaseClass()
cb.process()
I don't know if that's your only problem or not; seeing your traceback will shed more details on the problem.
If I fix that one problem, it all seems to work. I'm using ampy to transfer files to my Pico board (I've also repeated the same process using the Thonny edit, which provides a menu-driven interface for working with Micropython boards):
$ ampy -p /dev/usbserial/3/1.4.2 put main.py
$ ampy -p /dev/usbserial/3/1.4.2 put clientBase.py
$ picocom -b 115200 /dev/usbserial/3/1.4.2
I press return to get the Micropython REPL prompt:
<CR>
>>>
And then type CTRL-D to reset the board:
>>> <CTRL-D>
MPY: soft reboot
And then the board comes up, the code executes as expected:
<pause for 15 seconds>
Starting
Going to class
init
Process
MicroPython v1.18 on 2022-01-17; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>>
(note that if you replace MicroPython with CircuitPython,the Pico will show up as a drive and you can just drag-and-drop files on it.)
Tried micropython and circuitpython with Pycharm, Thonny and VisualStudio code. The only thing that reliably works is CircuitPython with Mu editor. I think its all about the way the .py files are copied to the Pico board and life's too short to do more diagnostics. Mu is pretty basic but it works! Thanks for the help.

pySerial running command to list ports

I am using pySerial and I am running this command using CMD to list available COM ports and displays a COM port number when found:
python -m serial.tools.list_ports
I know that the command line will import the serial module when I use the python -m flag and I can access the objects inside it so it should show the output. However, the same command however does not work when run using the IDLE shell:
import serial
print(serial.tools.list_ports_common)
This returns an error AttributeError: module 'serial' has no attribute 'tools'
Why is it not working at IDLE?
You need to import it first:
from serial.tools import list_ports
list_ports.main() # Same result as python -m serial.tools.list_ports
You can check out the source here
You can simply try connecting to each possible port (COM0...COM255). Then add the ports with successful connections to a list. Here is my example:
import serial
def connectedCOMports ():
allPorts = [] #list of all possible COM ports
for i in range(256):
allPorts.append("COM" + str(i))
ports = [] #a list of COM ports with devices connected
for port in allPorts:
try:
s = serial.Serial(port) #attempt to connect to the device
s.close()
ports.append(port) #if it can connect, add it the the list
except:
pass #if it can't connect, don't add it to the list
return(ports)
print(connectedCOMports())
When I ran this program, it printed ['COM7'] to the console. This represents the ESP32 microcontroller that I connected to my USB port.

VcXsrv WSL X server closes unexpectedly. Do I need to disable GPU?

I am trying to run some code with pybullet. I am on windows 10, have the latest vscode, and I am using WSL remote on vscode with ubuntu 18.04 LTS. I have a GTX 2070 graphics card. I just want to see this work, I've been trying to fix it for the last 3 hours.
First, here is the code I am trying to run in WSL:
import numpy as np
import pybullet as pb
physicsClient = pb.connect (pb.GUI)
#load plane
import pybullet_data
pb.setAdditionalSearchPath(pybullet_data.getDataPath())
planeId = pb.loadURDF('plane.urdf')
#load visual shape
visualShapeId = pb.createVisualShape(
shapeType=pb.GEOM_MESH,
fileName='random_urdfs/000/000.obj',
rgbaColor=None,
meshScale=[0.1, 0.1, 0.1])
collisionShapeId = pb.createCollisionShape(
shapeType=pb.GEOM_MESH,
fileName='random_urdfs/000/000_coll.obj',
meshScale=[0.1, 0.1, 0.1])
multiBodyId = pb.createMultiBody(
baseMass=1.0,
baseCollisionShapeIndex=collisionShapeId,
baseVisualShapeIndex=visualShapeId,
basePosition=[0, 0, 1],
baseOrientation=pb.getQuaternionFromEuler([0, 0, 0]))
I get no errors, but the X server window will pop up (black) and close immediately. I read that you need to disable your GPU with WSL, but I am scared of messing up my PC. I would only want to disable it for when I need to see graphics / use the X server, not for all WSL applications.
Here is what shows in my bash script:
user#DESKTOP-######:~/program$ python3 openAI.py
pybullet build time: Sep 22 2020 00:54:31
startThreads creating 1 threads.
starting thread 0
started thread 0
argc=2
argv[0] = --unused
argv[1] = --start_demo_name=Physics Server
ExampleBrowserThreadFunc started
X11 functions dynamically loaded using dlopen/dlsym OK!
X11 functions dynamically loaded using dlopen/dlsym OK!
Creating context
Failed to create GL 3.3 context ... using old-style GLX context
Indirect GLX rendering context obtained
Making context current
GL_VENDOR=NVIDIA Corporation
GL_RENDERER=GeForce RTX 2070 SUPER/PCIe/SSE2
GL_VERSION=1.4 (4.6.0 NVIDIA 451.67)
GL_SHADING_LANGUAGE_VERSION=(null)
pthread_getconcurrency()=0
Version = 1.4 (4.6.0 NVIDIA 451.67)
Vendor = NVIDIA Corporation
Renderer = GeForce RTX 2070 SUPER/PCIe/SSE2
Segmentation fault (core dumped)
user#DESKTOP-######:~/program$
#Emilio, I have got this working without any changes to the GPU, using the following process:
I used the VcXsrv application set up in the same way as this tutorial : https://jack-kawell.com/2020/06/12/ros-wsl2/ where crucially Native openGL is unchecked.
Export your ip address as in the tutorial, however instead of 'export DISPLAY={your_ip_address}:0.0', go to the VcXsrv window (which should be blank at this point) and replace :0.0 with whatever number of display is given. So for Display DESKTOP-1234AB:1.0 you would enter 'export DISPLAY={your_ip_address}:1.0'
In the linux terminal enter: export LIBGL_ALWAYS_INDIRECT=0
You can check that this has made an effect by entering: glxinfo
Which should print out:
direct rendering: yes
When you run your python program it should open up in the VcXsrv window. For me there was no cursor visible but I could still interact with the object as if I did have a cursor.

Determining operating system of the host using python-nmap

Until Python 3.4 you were able to determine target's operating system with
Python as follows:
import nmap
nm = nmap.PortScanner()
scanner = nm.scan(IP, port, arguments='-O')
print(scanner['scan'][IP]['osmatch'])
I'm using Python 3.6 and osmatch returns nothing.
Is there a way how to go about this ?
I've tested your script with Python 3.7.6:
import nmap
nm = nmap.PortScanner()
scanner = nm.scan(IP, port, arguments='-O')
print(scanner['scan'][IP]['osmatch'])
and it works well. The problem you have is that, for some reasons, the scan didn't retrieve any result, and the result object is empty, but if you try again on a different host it should work.

How Can I use my GPU on Ipython Notebook?

OS : Ubuntu 14.04LTS
Language : Python Anaconda 2.7 (keras, theano)
GPU : GTX980Ti
CUDA : CUDA 7.5
I wanna run keras python code on IPython Notebook by using my GPU(GTX980Ti)
But I can't find it.
I want to test below code. When I run it on to Ubuntu terminal,
I command as below (It uses GPU well. It doesn't have any problem)
First I set the path like below
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
Second I run the code as below
THEANO_FLAGS='floatX=float32,device=gpu0,nvcc.fastmath=True' python myscript.py
And it runs well.
But when i run the code on pycharm(python IDE) or
When I run it on Ipython Notebook, It doesn't use gpu.
It only uses CPU
myscript.py code is as below.
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time
vlen = 10 * 30 * 768 # 10 x #cores x # threads per core
iters = 1000
rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in xrange(iters):
r = f()
t1 = time.time()
print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
print('Used the cpu')
else:
print('Used the gpu')
To solve it, I force the code use gpu as below
(Insert two lines more on myscript.py)
import theano.sandbox.cuda
theano.sandbox.cuda.use("gpu0")
Then It generate the error like below
ERROR (theano.sandbox.cuda): nvcc compiler not found on $PATH. Check your nvcc installation and try again.
how to do it??? I spent two days..
And I surely did the way of using '.theanorc' file at home directory.
I'm using theano on an ipython notebook making use of my system's GPU. This configuration seems to work fine on my system.(Macbook Pro with GTX 750M)
My ~/.theanorc file :
[global]
cnmem = True
floatX = float32
device = gpu0
Various environment variables (I use a virtual environment(macvnev):
echo $LD_LIBRARY_PATH
/opt/local/lib:
echo $PATH
/Developer/NVIDIA/CUDA-7.5/bin:/opt/local/bin:/opt/local/sbin:/Developer/NVIDIA/CUDA-7.0/bin:/Users/Ramana/projects/macvnev/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
echo $DYLD_LIBRARY_PATH
/Developer/NVIDIA/CUDA-7.5/lib:/Developer/NVIDIA/CUDA-7.0/lib:
How I run ipython notebook (For me, the device is gpu0) :
$THEANO_FLAGS=mode=FAST_RUN,device=gpu0,floatX=float32 ipython notebook
Output of $nvcc -V :
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2015 NVIDIA Corporation
Built on Thu_Sep_24_00:26:39_CDT_2015
Cuda compilation tools, release 7.5, V7.5.19
From your post, probably you've set the $PATH variable wrong.