Python Serial() not etablishing on start up - python

I've made a python script to read information from Serial port. I want this script to run at the boot of my ubuntu.
I've made my python file executable, and added a lign to the crontab : #reboot sleep 10s; python /home/MyUser/Documents/MyScript.py &
The script is indeed started when i'm booting but it's seems like the specific line ser = serial.Serial('/dev/ttyACM0', 9600) won't work. Indeed, if I try to execute something before, it will work, but not after.
I can't figure out why it's not working. When i'm executing my script from the terminal, it does work without problem.
I believe it may be because of the fact that the serial port may not be ready yet when the script start but even when adding a longer sleep before the script start, it doesn't work. I'm running out of ideas and I really need your help.
Here is my python script :
#!/usr/bin/env python
import serial
import subprocess
import os
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
os.system('export DISPLAY=:0 && xset dpms force off &') #this line won't work, that's why I know the problem is coming from the serial beginning.
time.sleep(60)
urgency = 0
diffusion = 0
while 1 :
line = ser.readline().strip()
if line == "start":
#do something
else
#do something else

Related

Connection checker Script on Python

I was working on a connection everytime checker script on Python, trying to implement it by crontabs on a Raspberry Pi 4 with Ubuntu desktop 21.04. The code is the next:
from gpiozero import LED
from ping3 import ping
from time import sleep
program_flag=LED(24)
while True:
ping_test=ping('8.8.8.8')
if isinstance(ping_test, float):
program_flag.on()
else:
program_flag.off()
print(ping_test)
print(program_flag)
sleep(3)
This code works fine for me, but the problem comes when I try to put this script on crontab. I read something about infinite loops or while loops on crontabs, and I think that they doesn't work. What is the best solution for this? The target is configure a gpio with a 1 or 0 depending if connection works fine or not.
EDIT: my crontab line: #reboot python3 /bin/connection_test.py &
Thank you so much!
I have checked line by line, and the while loop doesn't work porpertly on crontab because of this line: ping_test=ping('8.8.8.8').
I supose that the problem comes from ping3 module.
Thank you for your answer Teejay Bruno.

Node-red daemon

I am new to using Node-red and the raspberry pi. I have a python script that would like to run from node-red and receive the mag.payload. I cannot figure the correct command in the daemon node to start the python script. Any help is appreciated.
Current Python script:
import time
import board
import busio
import adafruit_mprls
import RPi.GPIO as GPIO
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need
superuser privileges.")
i2c = busio.I2C(board.SCL, board.SDA)
mpr = adafruit_mprls.MPRLS(i2c, psi_min=0, psi_max=25)
"""
import digitalio
reset = digitalio.DigitalInOut(board.D5)
eoc = digitalio.DigitalInOut(board.D6)
mpr = adafruit_mprls.MPRLS(i2c, eoc_pin=eoc, reset_pin=reset,
psi_min=0, psi_max=25)
"""
while True:
print((mpr.pressure,))
time.sleep(1)
The python script is stored at home/pi/Document/pressure.py
I am not sure what the command and arguments should be in the daemon node of node-red. I have tried in
command: usr/bin/python
arguments: home/pi/Documents/prressure.py
Firstly paths need to start with a leading /
So you need to put /usr/bin/python into the command and /home/pi/Documents/prressure.py into the arguments.
The only problem is the script implies it needs to be run as root. You should NOT run Node-RED as root unless you REALLY REALLY know what you are doing. The other option would be to run with sudo in which case you would put /usr/bin/sudo in the command and /usr/bin/python /home/pi/Documents/prressure.py in the arguments. This will only work on a raspberry pi because the pi user is normally allowed to use sudo without a password.
If you want to run a program/script/command from node-red i recommend you checkout Exec Node
Runs a system command and returns its output.
The node can be configured to either wait until the command completes, or to send its output as the command generates it.
The command that is run can be configured in the node or provided by the received message.
For more information check the info tab of the node in Node-Red

Start a Python script in a shell with SSH

I want to start a Python script with paramiko which connects to my raspberry wich acts as a server. Then after the conection to the raspberry it starts a script like this(to send data to an arduino from another pc):
import tty
import sys
import termios
import serial
import os
arduino = serial.Serial('/dev/ttyUSB0' , 9600)
x = "./mjpg_streamer -i \"./input_uvc.so -d /dev/video0 -y\" -o \"./output_http.so -w ./www\""
os.system(x)
orig_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin)
x = 0
while x != chr(27): # ESC
x=sys.stdin.read(1)[0]
arduino.write(x)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)
This code works okay, kind of a raw_input just to simplify.
I want to connect automatically to the raspberry by ssh, and start a python script that will ask for an input -which in the code above is a constant-.
I thought something like opening a new shell with the script above already iniciated or something like that...
Quick answer, there is not any options that could help you insert password into ssh command. You have to set up a share key-pair to use ssh without password prompt. Searching on the internet can give you ton of answers, for example: http://www.thegeekstuff.com/2008/11/3-steps-to-perform-ssh-login-without-password-using-ssh-keygen-ssh-copy-id
So at first, set up key-pairs. Then use normal ssh to check whether it was successful. Then finally, in your python script, add some codes to deal with ssh.

Following Code works in python interpreter but not as a script

I just made a tiny code to change the colors of my led strip in Linux too (I already did it in C# on Windows).
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write(b'a')
When I type this into bash like this:
$sudo python2
>>>import serial
>>>ser = serial.Serial('/dev/ttyACM0', 9600)
>>>ser.write(b'a')
1
it's working fine, but if I then execute the .py script like this:
$sudo python2 light.py
The ser.write part seems not to work. I dont get an err msg or anything. But I know that it's communicatin with the arduino cause the Onboard LED flashes when I execute the script.
Okay, got it, the Arduino resets after getting serial input, I just added a 3 Seconds delay before writing the Serial data

Restart python script

I have a script that collects data from the streaming API. I'm getting an error at random that I believe it's coming from twitter's end for whatever reason. It doesn't happen at specific time, I've been seen it as early as 10 minutes after running my script, and other times after 2 hours.
My question is how do I create another script (outside the running one) that can catch if it terminated with an error, then restart after a delay.
I did some searching and most were related to using bash on linux, I'm on windows. Other suggestions were to use Windows Task Scheduler but that can only be set for a known time.
I came across the following code:
import os, sys, time
def main():
print "AutoRes is starting"
executable = sys.executable
args = sys.argv[:]
args.insert(0, sys.executable)
time.sleep(1)
print "Respawning"
os.execvp(executable, args)
if __name__ == "__main__":
main()
If I'm not mistaken that runs inside the code correct? Issue with that is my script is currently collecting data and I can't terminate to edit.
How about this?
from os import system
from time import sleep
while True: #manually terminate when you want to stop streaming
system('python streamer.py')
sleep(300) #sleep for 5 minutes
In the meanwhile, when something goes wrong in streamer.py , end it from there by invoking sys.exit(1)
Make sure this and streamer.py are in the same directory.

Categories

Resources