'Arduino/Python Serial communication
I want to send data from python to may Arduino Mega via serial output. The Arduino's RX Led blinks, when I run the Python script. However, the Serial.available() = false
. This is just an example code. The real project is building a speedometer for sim racing games (using UDP data). Any idea why it isn't working?
Here is the code:
Python:
import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);
i = 0
while i<= 9999 :
time.sleep(1/10)
i+=1
print(i)
Arduino.write(i)
Arduino:
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3
int i=0;
int Number;
TM1637Display display(CLK, DIO);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
display.setBrightness(0x0f);
display.showNumberDec(9999);
delay(3000);
}
void loop() {
Number= Serial.read();
if (Serial.available()>0){
display.setBrightness(0x0f);
display.showNumberDec(Number);
}
if (Serial.available() == false){
display.setBrightness(0x0f);
display.showNumberDec(0000);
}
}
Solution 1:[1]
This is how it works. Big thanks to csongoose from reddit who helped me a lot. Also thanks to all your replies on this. Python:
import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);
i = 0
while i<= 9999 :
time.sleep(1)
i+=1
print(i)
#converts int i to string b
b = "%s" %i
Arduino.write(bytes(b, 'utf-8'))
#the Arduino waits for this and can seperate the numbers
Arduino.write(b'\n')
Arduino:
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3
#define D1 5
#define D2 7
int Number;
String b;
//i am using a 7-digit display to show the numbers
TM1637Display display(CLK, DIO);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(D1 ,OUTPUT);
pinMode(D2 ,OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available()>0){
//looks for new numbers, which are sperated with '\n'
b = Serial.readStringUntil('\n');
//converts string b to integer Number
Number = b.toInt();
display.setBrightness(0x0f);
display.showNumberDec(Number);
//delay equals the same rate as python sends data
delay(1000);
}
//this indicates if the data is available and if the Arduino has rebooted
//you need to wait for it and then start your Python stream
if (Serial.available() == 0){
digitalWrite( D1, HIGH);}
else digitalWrite(D1, LOW);
if (Number != 0){
digitalWrite( D2, HIGH);}
else digitalWrite(D2, LOW);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bene |