tomcat53
Posts: 20
Joined: Thu Dec 28, 2017 6:26 pm

Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 7:11 pm

Hi,

I have this frustrating AlphaBot2. When I run any script, it doesn't seam to stop for real. Not sure how to explain this better. For example, I ran a script that powered LEDs. The LEDs are lighting up like a rainbow. Quite beautiful, actually. Anyways, when I press ctrl +c or ctrl + z the animation stops, but the LEDs stay on until I reboot the pi. Furthermore, if I use a web interface to control the robots, if I stop the scipt, the servos are still "working". If I try to run the script again to use the web interface, I get an error message. I have to reboot the pi and start from scratch.

Is there a command I can type in the terminal that is going to wipe the Pi's memory clean and really stop the scripts and starting it again without having to reboot? Thanks again for your help!

User avatar
thagrol
Posts: 3081
Joined: Fri Jan 13, 2012 4:41 pm
Location: Darkest Somerset, UK
Contact: Website

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 8:03 pm

ctrl-z doesn't kill a script it just suspends it so it will still be in memory. You can continue running it using either "fg" or "bg" depending on whether you want to have it running in the forground or background.

If you want to kill it, run

Code: Select all

jobs
kill %n
where n is the job number

ctrl-c kills most scripts dead. As does "kill".

With both the above methods of stopping a script, the script doesn't get any chance to run any clean up code it might have so gpios etc are left in the state they were in when the script was killed.

Sounds like you need your script to trap the ctrl-c (and/or other signals e.g SIGHUP, SIGKILL) and have it run some apropriate cleanup code before exiting.

The way you'd do that depends on which language your script has been written in.
Arguing with strangers on the internet since 1993.

tomcat53
Posts: 20
Joined: Thu Dec 28, 2017 6:26 pm

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 8:23 pm

Thanks for your reply,

Where to begin? I'm really new at all this, 3 days to be exact. I barely understand what you have just said. It is a Python script that was included in the badly translated from Chinese user manual. Here is how the script ends.

Image

Some of the scripts have .py extensions others have .sh

Even with ctrl +c , the scripts stay in memory.

How do I know what the job number is?

tomcat53
Posts: 20
Joined: Thu Dec 28, 2017 6:26 pm

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 9:09 pm

Different question in hopes of a solution.

I run the script. The RGB LEDs light up alike a chritmas tree.

I do ctrl+c

The script stops. The RGB LEDs are still on.

I'm in the terminal. Can I type a command that will turn my RGB LEDs off?

Like I said I'm a NEWBIE trying to learn. Assume that I know nothing.

There must be a sudo wipe-everything-clean-and-start-fresh command that exisits! Thanks

pcmanbob
Posts: 9466
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 9:34 pm

tomcat53 wrote:
Thu Dec 28, 2017 9:09 pm
Different question in hopes of a solution.

I run the script. The RGB LEDs light up alike a chritmas tree.

I do ctrl+c

The script stops. The RGB LEDs are still on.

I'm in the terminal. Can I type a command that will turn my RGB LEDs off?

Like I said I'm a NEWBIE trying to learn. Assume that I know nothing.

There must be a sudo wipe-everything-clean-and-start-fresh command that exisits! Thanks
So your python program has stopped running because you can now type in the terminal, BUT when your python program stopped suddenly due to Ctrl C your gpio pins were frozen in there current state.

what you need to do is add some code to trap this keyboard interrupt as its called and then execute the GPIO.cleanup() command.

if you post your code python program please use code tags
Add [code] at the top



and [/code] at the bottom.

I will have a look and add the code as an example for you.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

tomcat53
Posts: 20
Joined: Thu Dec 28, 2017 6:26 pm

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 9:52 pm

Thanks. I'll show you the lowlevel.py script and perhaps I could apply that to other scripts. I have the same issue with servos.

Code: Select all


# This code will animate a number of WS281x LEDs displaying rainbow colors.
import time

import _rpi_ws281x as ws

# LED configuration.
LED_CHANNEL    = 0
LED_COUNT      = 16         # How many LEDs to light.
LED_FREQ_HZ    = 800000     # Frequency of the LED signal.  Should be 800khz or 400khz.
LED_DMA_NUM    = 5          # DMA channel to use, can be 0-14.
LED_GPIO       = 18         # GPIO connected to the LED signal line.  Must support PWM!
LED_BRIGHTNESS = 255        # Set to 0 for darkest and 255 for brightest
LED_INVERT     = 0          # Set to 1 to invert the LED signal, good if using NPN
							# transistor as a 3.3V->5V level converter.  Keep at 0
							# for a normal/non-inverted signal.

# Define colors which will be used by the example.  Each color is an unsigned
# 32-bit value where the lower 24 bits define the red, green, blue data (each
# being 8 bits long).
DOT_COLORS = [  0x200000,   # red
				0x201000,   # orange
				0x202000,   # yellow
				0x002000,   # green
				0x002020,   # lightblue
				0x000020,   # blue
				0x100010,   # purple
				0x200010 ]  # pink


# Create a ws2811_t structure from the LED configuration.
# Note that this structure will be created on the heap so you need to be careful
# that you delete its memory by calling delete_ws2811_t when it's not needed.
leds = ws.new_ws2811_t()

# Initialize all channels to off
for channum in range(2):
    channel = ws.ws2811_channel_get(leds, channum)
    ws.ws2811_channel_t_count_set(channel, 0)
    ws.ws2811_channel_t_gpionum_set(channel, 0)
    ws.ws2811_channel_t_invert_set(channel, 0)
    ws.ws2811_channel_t_brightness_set(channel, 0)

channel = ws.ws2811_channel_get(leds, LED_CHANNEL)

ws.ws2811_channel_t_count_set(channel, LED_COUNT)
ws.ws2811_channel_t_gpionum_set(channel, LED_GPIO)
ws.ws2811_channel_t_invert_set(channel, LED_INVERT)
ws.ws2811_channel_t_brightness_set(channel, LED_BRIGHTNESS)

ws.ws2811_t_freq_set(leds, LED_FREQ_HZ)
ws.ws2811_t_dmanum_set(leds, LED_DMA_NUM)

# Initialize library with LED configuration.
resp = ws.ws2811_init(leds)
if resp != ws.WS2811_SUCCESS:
	message = ws.ws2811_get_return_t_str(resp)
	raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, message))

# Wrap following code in a try/finally to ensure cleanup functions are called
# after library is initialized.
try:
	offset = 0
	while True:
		# Update each LED color in the buffer.
		for i in range(LED_COUNT):
			# Pick a color based on LED position and an offset for animation.
			color = DOT_COLORS[(i + offset) % len(DOT_COLORS)]

			# Set the LED color buffer value.
			ws.ws2811_led_set(channel, i, color)

		# Send the LED color data to the hardware.
		resp = ws.ws2811_render(leds)
		if resp != ws.WS2811_SUCCESS:
			message = ws.ws2811_get_return_t_str(resp)
			raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message))

		# Delay for a small period of time.
		time.sleep(0.25)

		# Increase offset to animate colors moving.  Will eventually overflow, which
		# is fine.
		offset += 1

finally:
	# Ensure ws2811_fini is called before the program quits.
	ws.ws2811_fini(leds)
	# Example of calling delete function to clean up structure memory.  Isn't
	# strictly necessary at the end of the program execution here, but is good practice.
	ws.delete_ws2811_t(leds)

pcmanbob
Posts: 9466
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 10:15 pm

So your program already had the try: & finally: statements in it but because you have a while True loop you never get to the finally bit, which actually has the command to turn off your LED's

so replace finally: with except KeyboardInterrupt: so that it will be executed on Ctrl-c added gpio.cleanup() too.

Code: Select all


# This code will animate a number of WS281x LEDs displaying rainbow colors.
import time

import _rpi_ws281x as ws

# LED configuration.
LED_CHANNEL    = 0
LED_COUNT      = 16         # How many LEDs to light.
LED_FREQ_HZ    = 800000     # Frequency of the LED signal.  Should be 800khz or 400khz.
LED_DMA_NUM    = 5          # DMA channel to use, can be 0-14.
LED_GPIO       = 18         # GPIO connected to the LED signal line.  Must support PWM!
LED_BRIGHTNESS = 255        # Set to 0 for darkest and 255 for brightest
LED_INVERT     = 0          # Set to 1 to invert the LED signal, good if using NPN
							# transistor as a 3.3V->5V level converter.  Keep at 0
							# for a normal/non-inverted signal.

# Define colors which will be used by the example.  Each color is an unsigned
# 32-bit value where the lower 24 bits define the red, green, blue data (each
# being 8 bits long).
DOT_COLORS = [  0x200000,   # red
				0x201000,   # orange
				0x202000,   # yellow
				0x002000,   # green
				0x002020,   # lightblue
				0x000020,   # blue
				0x100010,   # purple
				0x200010 ]  # pink


# Create a ws2811_t structure from the LED configuration.
# Note that this structure will be created on the heap so you need to be careful
# that you delete its memory by calling delete_ws2811_t when it's not needed.
leds = ws.new_ws2811_t()

# Initialize all channels to off
for channum in range(2):
    channel = ws.ws2811_channel_get(leds, channum)
    ws.ws2811_channel_t_count_set(channel, 0)
    ws.ws2811_channel_t_gpionum_set(channel, 0)
    ws.ws2811_channel_t_invert_set(channel, 0)
    ws.ws2811_channel_t_brightness_set(channel, 0)

channel = ws.ws2811_channel_get(leds, LED_CHANNEL)

ws.ws2811_channel_t_count_set(channel, LED_COUNT)
ws.ws2811_channel_t_gpionum_set(channel, LED_GPIO)
ws.ws2811_channel_t_invert_set(channel, LED_INVERT)
ws.ws2811_channel_t_brightness_set(channel, LED_BRIGHTNESS)

ws.ws2811_t_freq_set(leds, LED_FREQ_HZ)
ws.ws2811_t_dmanum_set(leds, LED_DMA_NUM)

# Initialize library with LED configuration.
resp = ws.ws2811_init(leds)
if resp != ws.WS2811_SUCCESS:
	message = ws.ws2811_get_return_t_str(resp)
	raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, message))

# Wrap following code in a try/finally to ensure cleanup functions are called
# after library is initialized.
try:
	offset = 0
	while True:
		# Update each LED color in the buffer.
		for i in range(LED_COUNT):
			# Pick a color based on LED position and an offset for animation.
			color = DOT_COLORS[(i + offset) % len(DOT_COLORS)]

			# Set the LED color buffer value.
			ws.ws2811_led_set(channel, i, color)

		# Send the LED color data to the hardware.
		resp = ws.ws2811_render(leds)
		if resp != ws.WS2811_SUCCESS:
			message = ws.ws2811_get_return_t_str(resp)
			raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message))

		# Delay for a small period of time.
		time.sleep(0.25)

		# Increase offset to animate colors moving.  Will eventually overflow, which
		# is fine.
		offset += 1

except KeyboardInterrupt:
	# Ensure ws2811_fini is called before the program quits.
	ws.ws2811_fini(leds)
	# Example of calling delete function to clean up structure memory.  Isn't
	# strictly necessary at the end of the program execution here, but is good practice.
	ws.delete_ws2811_t(leds)
        GPIO.cleanup()
    
now servos are different just running gpio.cleanup() may not affect the servo or it may cause the servo to move to a different position it depends some what on your servo.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

tomcat53
Posts: 20
Joined: Thu Dec 28, 2017 6:26 pm

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 10:28 pm

Thanks,

Still didn't work, here's what I see on my terminal after I do ctrl+c

^CTraceback (most recent call last):
File "lowlevel.py", line 99, in <module>
GPIO.cleanup()
NameError: name 'GPIO' is not defined

pcmanbob
Posts: 9466
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 10:38 pm

tomcat53 wrote:
Thu Dec 28, 2017 10:28 pm
Thanks,

Still didn't work, here's what I see on my terminal after I do ctrl+c

^CTraceback (most recent call last):
File "lowlevel.py", line 99, in <module>
GPIO.cleanup()
NameError: name 'GPIO' is not defined
just remove GPIO.cleanup() from the end of the program my mistake did not look to see if GPIO had been setup, which in this case it has not, it will still run the other 2 commands which I assume are to turn off the LED's
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

tomcat53
Posts: 20
Joined: Thu Dec 28, 2017 6:26 pm

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 10:58 pm

It was worth a try, but the LED are still on...
Even power off doesn't turn them off. have to physically remove the power cord to turn everything off.

Thanks

pcmanbob
Posts: 9466
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Stopping a script and clearing it from Pi memory

Thu Dec 28, 2017 11:15 pm

tomcat53 wrote:
Thu Dec 28, 2017 10:58 pm
It was worth a try, but the LED are still on...
Even power off doesn't turn them off. have to physically remove the power cord to turn everything off.

Thanks
then you need to find the command that turns the LED's off and add this to the line after the except KeyboardInterrupt: line.

no shutting down the pi does not disconnect the power , it only safely shuts down the operating system, to remove power you need to switch off at mains or remove usb plug.

Edit....
looking at the code there seems to be a section that sets all the LED's to off

Code: Select all

# Initialize all channels to off
for channum in range(2):
    channel = ws.ws2811_channel_get(leds, channum)
    ws.ws2811_channel_t_count_set(channel, 0)
    ws.ws2811_channel_t_gpionum_set(channel, 0)
    ws.ws2811_channel_t_invert_set(channel, 0)
    ws.ws2811_channel_t_brightness_set(channel, 0)
    
may be you could try adding this to see if it turns all the LED's off. some experimentation may be required to get it to work.


finally if you want to just restart your pi the at the command line just type

Code: Select all

sudo reboot 
pi will power off and back on restarting the OS
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

User avatar
thagrol
Posts: 3081
Joined: Fri Jan 13, 2012 4:41 pm
Location: Darkest Somerset, UK
Contact: Website

Re: Stopping a script and clearing it from Pi memory

Fri Dec 29, 2017 12:42 am

pcmanbob beat me to it :) so I'll stay out of that.

To answer this question though
tomcat53 wrote:
Thu Dec 28, 2017 8:23 pm
How do I know what the job number is?
The "jobs" command returns a list of background jobs you've started in that shell (or nothing if you haven't started any). First column is the job number, second is curent status, last is the command entered. So pick the line that matches the command you entered.

For example (this assumes you're using a terminal window in the raspberry pi desktop not ssh):
Run this

Code: Select all

leafpad &
jobs
You'll get something like

Code: Select all

[1]+	Running		leafpad &
and a leafpad window :)
To kill leafpad run

Code: Select all

kill %1

My appologies if my first post was about as clear as mud.

As an aside, most, but not all, system installed shell commands have a manual page, try

Code: Select all

man <command>
e.g.

Code: Select all

man man

Some also provide basic help when given the "--help" argument e.g.

Code: Select all

python --help
( that's two "-" btw)
Arguing with strangers on the internet since 1993.

pcmanbob
Posts: 9466
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Stopping a script and clearing it from Pi memory

Fri Dec 29, 2017 12:54 am

thagrol wrote:
Fri Dec 29, 2017 12:42 am
pcmanbob beat me to it :) so I'll stay out of that.
Please feel free to add anything you can I am just working from the posted program and my personal experience with python.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Return to “Automation, sensing and robotics”