I can provide you with an example code for both Arduino and Python that uses a 405nm laser connected to pin D13 on the Arduino board and a webcam connected to the Python script via OpenCV (cv2) library. Keep in mind that this is just an example, and you may need to modify it according to your specific project requirements.
Arduino Code:
const int laserPin = 13;
void setup() {
pinMode(laserPin, OUTPUT);
digitalWrite(laserPin, LOW); // Ensure the laser is off initially
Serial.begin(9600); // Start the serial communication with the Python script
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
if (command == '1') {
digitalWrite(laserPin, HIGH); // Turn on the laser
} else if (command == '0') {
digitalWrite(laserPin, LOW); // Turn off the laser
}
}
}
Python Code:
import cv2
import numpy as np
import serial
laser_on_off = serial.Serial('COM3', 9600) # Change 'COM3' to your Arduino's serial port
cap = cv2.VideoCapture(0) # Connect to the webcam
def apply_threshold(frame):
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_blue = np.array([90, 50, 50])
upper_blue = np.array([130, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
return mask
while True:
ret, frame = cap.read()
if not ret:
break
mask = apply_threshold(frame)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
laser_on_off.write(b'1') # Send '1' to turn on the laser
else:
laser_on_off.write(b'0') # Send '0' to turn off the laser
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
laser_on_off.close()
This example code demonstrates two synergistic functions between the Arduino and Python scripts:
- The Arduino code listens for serial communication from the Python script and turns the 405nm laser on and off based on the received data ('1' turns it on, '0' turns it off).
- The Python script captures video from a webcam, applies a thresholding function to detect blue color (you may need to adjust the threshold values for 405nm laser detection), and sends the appropriate command to the Arduino to toggle the laser.
Please note that you should never look directly into a laser beam, especially a 405nm laser, as it can cause permanent eye damage. Always use appropriate safety measures when working with lasers.