- TS TS
- #21
using arduino Make a code for bouncing ball effect by making the LED start at one end,Here is a sample code for creating a bouncing ball effect on an LED connected to an Arduino board:
Code:const int LED_PIN = 9; const int MAX_BOUNCE_HEIGHT = 9; int currentHeight = 0; int direction = 1; void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { digitalWrite(LED_PIN, HIGH); delay(100); // Move the ball down for (int i = 0; i < MAX_BOUNCE_HEIGHT; i++) { digitalWrite(LED_PIN, LOW); delay(100); } // Make the ball bounce back up for (int i = MAX_BOUNCE_HEIGHT; i > 0; i--) { digitalWrite(LED_PIN, LOW); delay(100); } // Adjust the bounce height if (currentHeight == 0) { direction = 1; } else if (currentHeight == MAX_BOUNCE_HEIGHT) { direction = -1; } currentHeight += direction; }
In this code, we start by defining a few constants and variables.LED_PIN
is the pin number on which the LED is connected, andMAX_BOUNCE_HEIGHT
is the maximum height that the ball will bounce to.currentHeight
anddirection
are used to keep track of the current height of the ball and the direction in which it is moving.
In thesetup()
function, we set theLED_PIN
as an output pin.
In theloop()
function, we first turn on the LED by setting theLED_PIN
toHIGH
, and then wait for a short period of time using thedelay()
function.
Next, we move the ball down by turning off the LED and waiting for a short period of time, using afor
loop to control how far down the ball should move.
After the ball has reached the bottom, we use anotherfor
loop to make the ball bounce back up. We again use afor
loop to control how far up the ball should bounce.
Finally, we adjust the bounce height by checking whether the ball has reached the top or the bottom of its bounce, and changing the direction accordingly. We then update thecurrentHeight
variable to reflect the new height of the ball.
Overall, this code should create a bouncing ball effect on the LED, with the ball bouncing up and down a decreasing height with each bounce.
ʻdropʼ toward the other end, bounce back up, but to only go up 9
spaces, bounce, go up 8 spaces, then 7, then 6, etc. To give the
effect it is a bouncing ball, getting bouncing up to a lower height on
each bounce