Error while uploading instructions using PyFirmata package - python

So I am trying to learn the PyFirmata module of python that allows us to write codes in Python and upload it to an Arduino Board.
I am learning it from this website.
Code that causes the inbuilt LED to blink:
import pyfirmata
import time
board = pyfirmata.Arduino('/dev/ttyACM0') #This Line gives error
while True:
board.digital[13].write(1)
time.sleep(1)
board.digital[13].write(0)
time.sleep(1)
But, When I run it( in Sublime Text 3) , I get this error:
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port '/dev/ttyACM0': FileNotFoundError(2, 'The
system cannot find the path specified.', None, 3)
[Finished in 7.0s]
Can Anyone help me to fix this error?

The port you are trying to access doesn't exist or your program doesn't have permission to access it.
First checkout whether the port exist or not. If you have Arduino software installed, you can check from it. In case it's missing, another port should appear, smth like /dev/ttyACM*, where * is any number. Choose it and try running.
In case it exists, but the program still doesn't work visit the official arduino site.
This problem is solved in two command. Open terminal and type:
ls -l /dev/ttyACM*
Then you'll get something like this:
crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0
Here what we need is dialout. After the above command, type the below command, and the restart your device.
sudo usermod -a -G your_username
This should work, but there are cases, when it doesn't. Then you need to add your port to root access:
=============================================================================
cd ~/etc/udev/rules.d
In this directory, create a new .rules file and add the following to it:
KERNEL=="ttyACM0", MODE="0666"
This should work.

Related

Python process blocking socket [Errno 98]

I'm running two raspis connected to each other. They both run a program on startup (which starts fine).
However, I keep getting a error: [Errno 98] Address already in use error in the background, and the communication between both Pis doesn't even start.
I went for tracing down the python processes running via ps -fA ¦ grep python and tadaaa, I can see, that another process starts trying to use the same address.
The output of ps looks like:
root 923 917 0 12:25 pts/1 00:00:00 sudo python /home/pi/Documents/3_multithread.py
root 927 923 10 12:25 pts/1 00:00:00 python /home/pi/Documents/3_multithread.py
pi 932 881 0 12:25 pts/0 00:00:00 grep --color=auto python
From what I understand is, that it looks like the same process (3_multithread.py) is called twice (once as su, once not as su).
EDIT#2: I start the program via the .bashrc (sudo python /home/pi/Documents/3_multithread.py) and a lxsession. Might this be the reason for blocking the address?
The errorlog looks like that:
File "/home/pi/Documents/3_multithread.py", line 276, in set_server bind((HOST, PORT))
File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock, name)(*args)
error: [Errno 98] Address already in use
I just also checked the netstat -lptn. I get the following output:
tcp 0 0 0.0.0.0:22 0.0.0.0.* LISTEN -
EDIT#123: I traced the error further down. I imported and printed:
import os
os.getpid()
To get the process PID. Now what happens is: On bootup my script returned the PID 754, while the ps -fA ¦ grep python only stats two python processes with the PIDs 535 and 539. Does .bashrc and lxterminal start the process twice?
This is how i configure my socket inside the python script
def set_server():
global conn_global
global socket_global
global conn_established
HOST = ''
PORT = 22
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
socket_global = s
conn_global = conn
conn_established = 1
I'm using global variables to send commands to send the commands to the other Pi, which is working absolutely perfect (once the connection is established).
Thank you guys very much in advance!
With best regards,
Tobi
So I was FINALLY able to solve that issue.
As Hannu suggested first, the problem was the way I booted the system. First of all, what did I want to do?
I need to boot both Raspis into the X environment (Graphical user interface), since both of my Pis are running a Tkinter GUI. That's why I went for the lxsession based autostart solution. Using the .bashrc file to start my python code failed, since it looked like the .bashrc is called twice on boot.
So what solved my issue was, to use a shell script to start the python code on bootup from a lxterminal.
In order to do this:
Create a shell script in your home directory (the tilde ~ directory)
pi#raspberrypi:~ $ nano start.sh
and add the hashbang as well as the command to start your python script
#!/bin/sh
sudo python ~/Your/file/here.py
Edit the user LX autostart file like:
sudo nano ~/.config/lxsession/LXDE-pi/autostart
and add the call for the lxterminal including your shell script like
#lxterminal -e ./start.sh
Finally, for my application I had to grant access rights to everyone
chmod 775 start.sh
and use global file paths for all images, like
/home/Documents/Your/files/here.png
Save everything and reboot your pi. Now Everything should boot up perfectly.
Thank you all for helping me, especially Hannu!

Flask Running Issue: socket.error: [Errno 98] Address already in use

I got this error message sublime issue(My OS: Ubuntu 16.04) "socket.error: [Errno 98] Address already in use" If I run flask in sublime text or PyCharm. But if I run flask on my Ubuntu terminal,it is running. I understood that port used another service. Then i was trying to solve this issue from google/stackoverflow.
# ps ax | grep 5000 // or # ps ax | grep name_of_service
# kill 3750 // or # killall name_of_service
But nothing changed. Only i found this problem when i was trying to run on sublime or pycharm IDE.
Simple way is to use fuser.
fuser <yourport>/tcp #this will fetch the process/service
Replace <yourport> with the port you want to use
#to kill the process using <yourport> add `-k` argument
fuser <yourport>/tcp -k
In your case
fuser 5000/tcp -k
Now you can run flask with that port.
Pycharm allows you to edit the run configuration, so enter the configuration and check the box (top-right corner) saying: "singleton instance". In this way, every time you restart the server, the previous connection on port 5000 is closed and opened again.

Is there a way to have the default terminal window execute my python program from within shell script?

How can I doc a specific terminal window on my Mac ( OS X 10.9.2) that upon clicking executes my python program from within shell script?
In my job.sh file I have this:
#!/bin/bash
python python_script.py
This is what I have in my python_script.py file:
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Basically I don't want to have to open up my terminal window, type ./job.sh and run the command, I want my terminal window to run ./job.sh by default just by clicking it.
You can just put the command in your .profile or .bash_profile or .bashrc file:
echo 'python python_script.py' >> ~/.profile
# or
# echo '/path/to/job.sh' >> ~/.profile
When you open up a new terminal, the .profile file will be sourced and your job will be run.
Note: Command to be put into the file is python python_script.py or /path/to/job.sh
Figured it out! It was the .bash_profile file in my case(OS X) that needed the
'python python_script.py' >> ~/.bash_profile
command executed as my .profile is overlooked due to the order in which bash profile files are read. For anyone who has no idea about this(like me until today), definitely checkout http://hayne.net/MacDev/Notes/unixFAQ.html#shellStartup
The accepted answer for this question led me there, https://apple.stackexchange.com/questions/12993/why-doesnt-bashrc-run-automatically
After that, it was simply a matter of being in the right directory to execute the script.
Also be careful and make sure to properly exit out of your server(ctrl-c) when your done, as I closed out the workspace by accident before and it led to process being bound to the default port and kept giving me an error which was solved by this.
socket.error: [Errno 48] Address already in use

How to invoke sudo password request in Python

I've got a USB GPIO electronic gizmo attached to a desktop PC running Linux Mint 17 "Mate"; in this environment the gizmo appears as /dev/ttyACM0. I've written a GUI Python 2.7/Tkinter program to control the gizmo via the pySerial module. The program works when run from the console using sudo.
Being a GUI program, I want to be able to run it from the "Mate" desktop - but I can't, because being a serial device, accessing the gizmo requires root privileges obtained via sudo, wot has to be invoked at a Terminal.
# here's the offending code
import serial
numa = serial.Serial("/dev/ttyACM0", 19200, timeout=1)
....
How do I invoke the "Enter your password..." routine from within the Python program so a raw user doesn't have to open a Terminal to enter the password?
Thanks for any advice you can provide!
I can't answer your question, but instead I'm going to solve your problem.
When you list the device file, you'll see something like this:
$ ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 188, 0 Apr 4 11:22 /dev/ttyACM0
Both the owner (root) and the owner group (dialout) have read-write-access (rw-), while everybody else isn't able to access the device (---). Therefore, instead of giving the program root access to your system, you can simply add the user(s) to the dialout group:
$ sudo usermod -aG dialout <username>
Logging out and back in will be necessary, but afterwards your script will be able to both read and write to the serial interface without the need of a root password.
Use gksudo rather than sudo
from subprocess import call
call('gksudo -D "Program requires root priveledge \nSudo "your command here",shell=True)
for example:
call('gksudo -D "Override Sudo message " cp /etc/hosts /home/new.hosts',shell=True)

pynotify in python script go wrong when running with sudo in KDE

I just want to show notification in KDE environment.So i tried
pynotifytest.py
from pynotify import *
init("test")
Notification("test", "test").show()
then i run sudo python pynotifytest.py,the error i got was:
No protocol specified
/usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display warnings.warn(str(e), _gtk.Warning)
----> 3 Notification("test", "test").show()
Error: Command line `dbus-launch --autolaunch=cb94cb23372d0aff09ce7d8a000024b4 --binary-syntax --close-stderr' exited with non-zero exit status 1: No protocol specified\nAutolaunch error: X11 initialization failed.
then i tried to drop privilege
pynotifytest.py
import os
os.setuid(1000)
from pynotify import *
init("test")
Notification("test", "test").show()
still i got the same error only in KDE.In gnome-shell and awesome the notification show up as expected.I have a python program must running with root privilege so i can't leave sudo behind. 1000 is my user's uid logging in X.
My linux distribution is Arch. Thanks
"it works for me" -- please give more details of your system. It worked on a fedora 15 with SELinux disabled here. Also note that the problem you are getting is on the GTK+ part - not pynotify per se.
Also - does your user "1000" is the one logged in the graphical environment? Of course this won't work if you are trying to diaplay windows with a user other than the one logged in or root itself.
To allow sudo to start graphical application in X, you need to add:
Defaults env_keep += "HOME"
to visudo.

Categories

Resources