Arduino itself doesn't run Python natively since it uses C/C++ as its primary programming language. However, there are a few ways you can integrate Python with Arduino:
### 1. **MicroPython and CircuitPython** (For Specific Boards)
MicroPython and CircuitPython are streamlined versions of Python designed for microcontrollers. While most standard Arduino boards (like Uno and Mega) don’t support these, boards based on the ARM Cortex architecture, such as the **Arduino Nano 33 BLE** or **ESP32/ESP8266** boards, can run MicroPython or CircuitPython.
- **MicroPython**: Allows you to write Python scripts and run them on microcontrollers. It works on many boards, including ESP32, ESP8266, and some other Arduino-compatible boards.
- **CircuitPython**: Developed by Adafruit, it is similar to MicroPython and runs on a variety of microcontrollers, especially Adafruit boards.
### 2. **Python-Arduino Communication via Serial**
If you want to run a Python program on your computer while interacting with an Arduino board, you can use the **pySerial** library. This allows Python on your computer to communicate with the Arduino through a serial connection (USB).
#### Example:
1. **Arduino Code (C++):**
Write a simple program on the Arduino to listen for serial input.
```cpp
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
int data = Serial.parseInt();
Serial.print("Received: ");
Serial.println(data);
}
}
```
2. **Python Code (using `pySerial`):**
On your computer, you can run Python code to send data to Arduino.
```python
import serial
import time
arduino = serial.Serial(port='COM3', baudrate=9600, timeout=.1)
time.sleep(2) # wait for Arduino to initialize
def write_read(data):
arduino.write(bytes(data, 'utf-8'))
time.sleep(0.05)
response = arduino.readline().decode('utf-8').strip()
return response
while True:
data = input("Enter data to send: ")
print(write_read(data))
```
### 3. **Firmata Protocol**
Another method is using the **Firmata** protocol, where the Arduino acts as a bridge that executes commands sent from a Python script running on your computer. The Python library **pyFirmata** is used to control Arduino through Python.
#### Example:
1. **Upload the Standard Firmata Sketch**: In the Arduino IDE, go to `File > Examples > Firmata > StandardFirmata`, and upload this to your board.
2. **Python Code (using pyFirmata)**:
```python
import pyfirmata
import time
board = pyfirmata.Arduino('COM3') # Adjust to the correct COM port
while True:
board.digital[13].write(1) # Turn on the LED on pin 13
time.sleep(1)
board.digital[13].write(0) # Turn off the LED
time.sleep(1)
```
### Summary
- **Running Python on Arduino**: Limited to boards that support MicroPython or CircuitPython (e.g., ESP32, ESP8266, etc.).
- **Python and Arduino via Serial or Firmata**: Allows Python scripts on your computer to control or interact with the Arduino via USB or serial communication.