Python: FuncAnimation doesn't work in “while True” loopEmulate a do-while loop in Python?open() in Python does not create a file if it doesn't existWhat is __future__ in Python used for and how/when to use it, and how it worksWhy does python use 'else' after for and while loops?Python: Checking if a 'Dictionary' is empty doesn't seem to workI need to find the location of a value in one numpy array and use it to refer to a value in the same location of another numpy arrayUpdating matplotlib.pyplot figure in pythongraph is not updating in the x-axis where the date and time is displayedPython, quitting matplotlib FuncAmination() when animation is fed by incoming sensor data`key_press_event` not working in python matplotlib FuncAnimation

Why would five hundred and five same as one?

Error in master's thesis, I do not know what to do

Non-Borel set in arbitrary metric space

Weird lines in Microsoft Word

Is there any common country to visit for persons holding UK and Schengen visas?

"Oh no!" in Latin

What is the meaning of "You've never met a graph you didn't like?"

Friend wants my recommendation but I don't want to give it to him

Highest stage count that are used one right after the other?

Trouble reading roman numeral notation with flats

Pre-Employment Background Check With Consent For Future Checks

Relations between homogeneous polynomials

Is this saw blade faulty?

Is divisi notation needed for brass or woodwind in an orchestra?

How to preserve electronics (computers, ipads, phones) for hundreds of years?

Why doesn't Gödel's incompleteness theorem apply to false statements?

What is the period/term used describe Giuseppe Arcimboldo's style of painting?

Asserting that Atheism and Theism are both faith based positions

What is the tangent at a sharp point on a curve?

Do people actually use the word "kaputt" in conversation?

Writing in a Christian voice

Checking @@ROWCOUNT failing

What is the purpose of using a decision tree?

Put the phone down / Put down the phone



Python: FuncAnimation doesn't work in “while True” loop


Emulate a do-while loop in Python?open() in Python does not create a file if it doesn't existWhat is __future__ in Python used for and how/when to use it, and how it worksWhy does python use 'else' after for and while loops?Python: Checking if a 'Dictionary' is empty doesn't seem to workI need to find the location of a value in one numpy array and use it to refer to a value in the same location of another numpy arrayUpdating matplotlib.pyplot figure in pythongraph is not updating in the x-axis where the date and time is displayedPython, quitting matplotlib FuncAmination() when animation is fed by incoming sensor data`key_press_event` not working in python matplotlib FuncAnimation













0















I have a Raspberry Pi connected with an accelerometer. In Python, I'm want to draw a animated graph of X-axis value. It's a realtime graph that shows the change of X-axis value as I move the Pi in my hand. However the graph shows only the initial value.



from mpu6050 import mpu6050
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use("fivethirtyeight")

sensor = mpu6050(0x68)
print " waiting for the sensor to callibrate..."

sleep(2)

acc = np.empty((0,3), float) # storage for x, y, z axes values of the accelerometer
t = 0
time = np.empty((0,1), int) # time counter(this becomes the x axis of the graph)

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

axis = 0 # accelerometer x axis. y axis = 1, z axis = 2

def animate(i):
ax1.clear()
ax1.plot(time, acc[:,axis])

while True:
accel_data = sensor.get_accel_data()
print("Accelerometer data")
print("x: " + str(accel_data['x']))
print("y: " + str(accel_data['y']))
print("z: " + str(accel_data['z']))
acc = np.append(acc, np.array([[accel_data['x'], accel_data['y'], accel_data['z']]]), axis=0)

# increment time array
time = np.append(time, t)
t = t + 1

print("acc[:,0]:" + str(acc[:,0]))
print("time:" + str(time))
ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()
sleep(2)


However, when I run the script, it only prints the value in the first loop like below. It also shows the graph but it's an empty graph because in the first loop there is only one data point.



waiting for the sensor to callibrate...
Accelerometer data
x: 6.2009822998
y: 3.36864173584
z: 9.27513723145
acc[:,0]: [ 6.2009823]
time: [0]


enter image description here



When I close the graph window, the loop resumes from the second loop and prints the values onwards, but the graph is never shown again.



Although it does not give any Error message, I assume something is wrong with animation.FuncAnimation or the place I should put plt.show() in the while loop.



I'm using Raspberry Pi 3b + with Python 2.7.13. Accelerometer is MPU6050.



It would be great if anybody could tell me how to fix this problem. Thank you!










share|improve this question






















  • No, you should not use a while loop at all. The FuncAnimation itself can be seen as the loop that you want to use to change your plot.

    – ImportanceOfBeingErnest
    Mar 7 at 20:36











  • Thank you! But in order to continuously read and print the value from the accelerometer, I used while loop. Could you elaborate a bit more on how to use FuncAnination without while loop, and at the same time constantly read the value from the accelerometer?

    – Makoto Miyazaki
    Mar 7 at 20:57











  • FuncAnimation repeatedly calls a function (in your case animate). Inside this function you do whatever you need to in order to continuously read and print the value from the accelerometer.

    – ImportanceOfBeingErnest
    Mar 7 at 21:01











  • Okay, so you mean I should read the accelerometer values inside the animate function only once, then FuncAnimation will call animate repeatedly, with updated accelerometer values? Hope I understood you correctly.

    – Makoto Miyazaki
    Mar 7 at 21:07
















0















I have a Raspberry Pi connected with an accelerometer. In Python, I'm want to draw a animated graph of X-axis value. It's a realtime graph that shows the change of X-axis value as I move the Pi in my hand. However the graph shows only the initial value.



from mpu6050 import mpu6050
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use("fivethirtyeight")

sensor = mpu6050(0x68)
print " waiting for the sensor to callibrate..."

sleep(2)

acc = np.empty((0,3), float) # storage for x, y, z axes values of the accelerometer
t = 0
time = np.empty((0,1), int) # time counter(this becomes the x axis of the graph)

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

axis = 0 # accelerometer x axis. y axis = 1, z axis = 2

def animate(i):
ax1.clear()
ax1.plot(time, acc[:,axis])

while True:
accel_data = sensor.get_accel_data()
print("Accelerometer data")
print("x: " + str(accel_data['x']))
print("y: " + str(accel_data['y']))
print("z: " + str(accel_data['z']))
acc = np.append(acc, np.array([[accel_data['x'], accel_data['y'], accel_data['z']]]), axis=0)

# increment time array
time = np.append(time, t)
t = t + 1

print("acc[:,0]:" + str(acc[:,0]))
print("time:" + str(time))
ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()
sleep(2)


However, when I run the script, it only prints the value in the first loop like below. It also shows the graph but it's an empty graph because in the first loop there is only one data point.



waiting for the sensor to callibrate...
Accelerometer data
x: 6.2009822998
y: 3.36864173584
z: 9.27513723145
acc[:,0]: [ 6.2009823]
time: [0]


enter image description here



When I close the graph window, the loop resumes from the second loop and prints the values onwards, but the graph is never shown again.



Although it does not give any Error message, I assume something is wrong with animation.FuncAnimation or the place I should put plt.show() in the while loop.



I'm using Raspberry Pi 3b + with Python 2.7.13. Accelerometer is MPU6050.



It would be great if anybody could tell me how to fix this problem. Thank you!










share|improve this question






















  • No, you should not use a while loop at all. The FuncAnimation itself can be seen as the loop that you want to use to change your plot.

    – ImportanceOfBeingErnest
    Mar 7 at 20:36











  • Thank you! But in order to continuously read and print the value from the accelerometer, I used while loop. Could you elaborate a bit more on how to use FuncAnination without while loop, and at the same time constantly read the value from the accelerometer?

    – Makoto Miyazaki
    Mar 7 at 20:57











  • FuncAnimation repeatedly calls a function (in your case animate). Inside this function you do whatever you need to in order to continuously read and print the value from the accelerometer.

    – ImportanceOfBeingErnest
    Mar 7 at 21:01











  • Okay, so you mean I should read the accelerometer values inside the animate function only once, then FuncAnimation will call animate repeatedly, with updated accelerometer values? Hope I understood you correctly.

    – Makoto Miyazaki
    Mar 7 at 21:07














0












0








0








I have a Raspberry Pi connected with an accelerometer. In Python, I'm want to draw a animated graph of X-axis value. It's a realtime graph that shows the change of X-axis value as I move the Pi in my hand. However the graph shows only the initial value.



from mpu6050 import mpu6050
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use("fivethirtyeight")

sensor = mpu6050(0x68)
print " waiting for the sensor to callibrate..."

sleep(2)

acc = np.empty((0,3), float) # storage for x, y, z axes values of the accelerometer
t = 0
time = np.empty((0,1), int) # time counter(this becomes the x axis of the graph)

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

axis = 0 # accelerometer x axis. y axis = 1, z axis = 2

def animate(i):
ax1.clear()
ax1.plot(time, acc[:,axis])

while True:
accel_data = sensor.get_accel_data()
print("Accelerometer data")
print("x: " + str(accel_data['x']))
print("y: " + str(accel_data['y']))
print("z: " + str(accel_data['z']))
acc = np.append(acc, np.array([[accel_data['x'], accel_data['y'], accel_data['z']]]), axis=0)

# increment time array
time = np.append(time, t)
t = t + 1

print("acc[:,0]:" + str(acc[:,0]))
print("time:" + str(time))
ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()
sleep(2)


However, when I run the script, it only prints the value in the first loop like below. It also shows the graph but it's an empty graph because in the first loop there is only one data point.



waiting for the sensor to callibrate...
Accelerometer data
x: 6.2009822998
y: 3.36864173584
z: 9.27513723145
acc[:,0]: [ 6.2009823]
time: [0]


enter image description here



When I close the graph window, the loop resumes from the second loop and prints the values onwards, but the graph is never shown again.



Although it does not give any Error message, I assume something is wrong with animation.FuncAnimation or the place I should put plt.show() in the while loop.



I'm using Raspberry Pi 3b + with Python 2.7.13. Accelerometer is MPU6050.



It would be great if anybody could tell me how to fix this problem. Thank you!










share|improve this question














I have a Raspberry Pi connected with an accelerometer. In Python, I'm want to draw a animated graph of X-axis value. It's a realtime graph that shows the change of X-axis value as I move the Pi in my hand. However the graph shows only the initial value.



from mpu6050 import mpu6050
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use("fivethirtyeight")

sensor = mpu6050(0x68)
print " waiting for the sensor to callibrate..."

sleep(2)

acc = np.empty((0,3), float) # storage for x, y, z axes values of the accelerometer
t = 0
time = np.empty((0,1), int) # time counter(this becomes the x axis of the graph)

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

axis = 0 # accelerometer x axis. y axis = 1, z axis = 2

def animate(i):
ax1.clear()
ax1.plot(time, acc[:,axis])

while True:
accel_data = sensor.get_accel_data()
print("Accelerometer data")
print("x: " + str(accel_data['x']))
print("y: " + str(accel_data['y']))
print("z: " + str(accel_data['z']))
acc = np.append(acc, np.array([[accel_data['x'], accel_data['y'], accel_data['z']]]), axis=0)

# increment time array
time = np.append(time, t)
t = t + 1

print("acc[:,0]:" + str(acc[:,0]))
print("time:" + str(time))
ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()
sleep(2)


However, when I run the script, it only prints the value in the first loop like below. It also shows the graph but it's an empty graph because in the first loop there is only one data point.



waiting for the sensor to callibrate...
Accelerometer data
x: 6.2009822998
y: 3.36864173584
z: 9.27513723145
acc[:,0]: [ 6.2009823]
time: [0]


enter image description here



When I close the graph window, the loop resumes from the second loop and prints the values onwards, but the graph is never shown again.



Although it does not give any Error message, I assume something is wrong with animation.FuncAnimation or the place I should put plt.show() in the while loop.



I'm using Raspberry Pi 3b + with Python 2.7.13. Accelerometer is MPU6050.



It would be great if anybody could tell me how to fix this problem. Thank you!







python matplotlib animation graph raspberry-pi






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 20:27









Makoto MiyazakiMakoto Miyazaki

3372313




3372313












  • No, you should not use a while loop at all. The FuncAnimation itself can be seen as the loop that you want to use to change your plot.

    – ImportanceOfBeingErnest
    Mar 7 at 20:36











  • Thank you! But in order to continuously read and print the value from the accelerometer, I used while loop. Could you elaborate a bit more on how to use FuncAnination without while loop, and at the same time constantly read the value from the accelerometer?

    – Makoto Miyazaki
    Mar 7 at 20:57











  • FuncAnimation repeatedly calls a function (in your case animate). Inside this function you do whatever you need to in order to continuously read and print the value from the accelerometer.

    – ImportanceOfBeingErnest
    Mar 7 at 21:01











  • Okay, so you mean I should read the accelerometer values inside the animate function only once, then FuncAnimation will call animate repeatedly, with updated accelerometer values? Hope I understood you correctly.

    – Makoto Miyazaki
    Mar 7 at 21:07


















  • No, you should not use a while loop at all. The FuncAnimation itself can be seen as the loop that you want to use to change your plot.

    – ImportanceOfBeingErnest
    Mar 7 at 20:36











  • Thank you! But in order to continuously read and print the value from the accelerometer, I used while loop. Could you elaborate a bit more on how to use FuncAnination without while loop, and at the same time constantly read the value from the accelerometer?

    – Makoto Miyazaki
    Mar 7 at 20:57











  • FuncAnimation repeatedly calls a function (in your case animate). Inside this function you do whatever you need to in order to continuously read and print the value from the accelerometer.

    – ImportanceOfBeingErnest
    Mar 7 at 21:01











  • Okay, so you mean I should read the accelerometer values inside the animate function only once, then FuncAnimation will call animate repeatedly, with updated accelerometer values? Hope I understood you correctly.

    – Makoto Miyazaki
    Mar 7 at 21:07

















No, you should not use a while loop at all. The FuncAnimation itself can be seen as the loop that you want to use to change your plot.

– ImportanceOfBeingErnest
Mar 7 at 20:36





No, you should not use a while loop at all. The FuncAnimation itself can be seen as the loop that you want to use to change your plot.

– ImportanceOfBeingErnest
Mar 7 at 20:36













Thank you! But in order to continuously read and print the value from the accelerometer, I used while loop. Could you elaborate a bit more on how to use FuncAnination without while loop, and at the same time constantly read the value from the accelerometer?

– Makoto Miyazaki
Mar 7 at 20:57





Thank you! But in order to continuously read and print the value from the accelerometer, I used while loop. Could you elaborate a bit more on how to use FuncAnination without while loop, and at the same time constantly read the value from the accelerometer?

– Makoto Miyazaki
Mar 7 at 20:57













FuncAnimation repeatedly calls a function (in your case animate). Inside this function you do whatever you need to in order to continuously read and print the value from the accelerometer.

– ImportanceOfBeingErnest
Mar 7 at 21:01





FuncAnimation repeatedly calls a function (in your case animate). Inside this function you do whatever you need to in order to continuously read and print the value from the accelerometer.

– ImportanceOfBeingErnest
Mar 7 at 21:01













Okay, so you mean I should read the accelerometer values inside the animate function only once, then FuncAnimation will call animate repeatedly, with updated accelerometer values? Hope I understood you correctly.

– Makoto Miyazaki
Mar 7 at 21:07






Okay, so you mean I should read the accelerometer values inside the animate function only once, then FuncAnimation will call animate repeatedly, with updated accelerometer values? Hope I understood you correctly.

– Makoto Miyazaki
Mar 7 at 21:07













0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55052276%2fpython-funcanimation-doesnt-work-in-while-true-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55052276%2fpython-funcanimation-doesnt-work-in-while-true-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived