Introduction:
In this post, I have used an LDR to sense the black obstacles (cactus )in this game and make the dino jump in the chrome using a system of Arduino and python code.
Link for GitHub Repository for this code (click here)
System in Action:
Contents:
- Hardware Required
- Hardware Setup
- Arduino Code
- Serial Communication (brief)
- Python Code
- Final Step
Hardware Required:
- LDR
- 10k resistor
- Arduino nano
- Few jumper wires
Hardware Setup:
First we need to connect the LDR in series with the 10k resistor across +5v and Gnd.
Next, we take a jumper from the junction of LDR and Resistor to analog pin A0 (as shown below). In a way, we just made a voltage divider configuration and read the voltage drop across the LDR.
This value changes due to change in the amount of light incident on it.
Arduino Code:
In the below code we continuously read the analog value of the LDR sensor and if it comes inside the desired range for black (here : >270 & <400), we update the laststate variable to ‘1‘.
In the other case, first, we check if the laststate was 1 and print the same in the serial monitor for python code to read and next we update the laststate variable to 0.
int val=0;//variable to read and update A0 pin value
int laststate=0; // to update the state of present colour the LDR detects 1:black ,0:white
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(A0,INPUT);
}
void loop() {
val=analogRead(A0);
Serial.println(val);
laststate=0;// by default set to 0:white
while(val>270 && val<400)// this while loop runs until the sensor keeps on detecting black
{
val=analogRead(A0);
laststate=1;
}
if(laststate==1) //if black send 1 ==> jump
{ Serial.println(1);
delay(10);
}
}
Serial Communication (brief Idea):
We cannot control the keyboard strokes directly from Arduino IDE for Arduino nano. So we will make use of python to simulate the keystroke using python’s library pyautogui.
Also, for serial communication, we use library pyserial . Refer here
First, we will upload the code to Arduino and note down the Serial port to which it is connected to the computer.
Next we will run the below python code bring the setup alive.
Python Code:
import pyautogui
import serial # add Serial library for Serial communication
import time
c=0
Arduino_Serial = serial.Serial('com9',9600) #Create Serial port object called arduinoSerialData
while(1):
if(Arduino_Serial.read()=='1'):
pyautogui.keyDown('space')
time.sleep(.1)
pyautogui.keyUp('space')
Final Step :
Now once all the above steps are done and the Arduino code is uploaded. Simply place the LDR sensor in position to your Desktop Screen on the chrome (refer below animation) using a tape.
Finally, run the python code to see this in action.