Hello, everyone
I was serializing Arduino and Raspberry Pi and I ended up writing this because of a strange error.
Below is the code applied to Arduino Uno.
//blinking led by usb serial communication
const int ledPin = 13; // pin number with built-in LED
void setup() {
// Serial communication initialization
Serial.begin(9600);
// Set internal LED as output pin
pinMode(ledPin, OUTPUT);
}
void loop() {
// If there is data in the serial buffer
if (Serial.available()) {
//Read and process text
String receivedString = Serial.readStringUntil('\n'); // 개행 문자까지 읽기
//Internal LED control when 'pm1' string is received
if (receivedString.startsWith("pm1")) {
int num = receivedString.substring(4).toInt(); // Extract numeric parts from string
Serial.println(receivedString);
blinkLED(num);
}
}
}
// Function that blinks the internal LED a given number of times
void blinkLED(int times) {
for (int i = 0; i < times; i++) {
Serial.println(i+1);
digitalWrite(ledPin, HIGH); // LED 켜기
delay(1000); // 1000ms 대기 (1초)
digitalWrite(ledPin, LOW); // LED 끄기
delay(1000); // 1000ms 대기 (1초)
}
}
And below this is Python code executed by Raspberry Pi.
import serial
import sys
# Serial Port and Speed Settings
serial_port = '/dev/ttyUSB0' # 아두이노와 연결된 포트
baud_rate = 9600
# Serial Port Initialization
ser = serial.Serial(serial_port, baud_rate)
# Translate numbers passed by command-line arguments into strings and send
def send_data(data):
ser.write(data.encode()) #Convert string to bytes and send
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python send_data.py <number>")
sys.exit(1)
number = sys.argv[1]
send_data(number)
I checked on Raspberry Pi that if you run the above codes, the value goes well when you enter the value.

I typed pm1_2 and actually made sure it was typed correctly.
But led doesn't blink twice.
I tried the following method in a different way, and this method succeeded.
But this code doesn't end because the script is a while statement.
import serial
# Serial Port and Speed Settings
serial_port = '/dev/tyUSB0' #Port associated with Arduino
baud_rate = 9600
# Serial Port Initialization
ser = serial.Serial(serial_port, baud_rate)
while True:
# Receive data input from users
data = input("Enter data to send: ")
# data transfer
ser.write(data.code()) #Convert string to bytes and send
The way I want it to be done is once the python code is entered together as an argument from another code, and the executed code forwards the argument to Arduino, blinking the led as much as the entered argument.
In other words, I want to succeed the first code.
I don't know what's wrong with this.
Tell me about your experiences.
I couldn't find this problem on the Internet.

