Lo primero dar las gracias, el problema que tengo es que quiero encender unos leds en arduino, y la idea es que python lee unas variables en otro archivo(ya he probado que eso funciona), pero python deberia enviar una señal al arduino dependiendo de la variable leida pero no parece haber comunicacion entre python y arduino.
Codigo de phyton:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import sys
import time
import json
import serial
arduino = serial.Serial('COM4', 9600) # New serial connection
def sendBombStatus(bomb): # Send bomb status to arduino
if(bomb == 'defused'):
arduino.write('bd')
elif(bomb == 'planted'):
arduino.write('pb')
elif(bomb == 'exploded'):
arduino.write('be')
else:
arduino.write('bn')
return None
class MyServer(HTTPServer):
def init_state(self):
"""
You can store states over multiple requests in the server
"""
self.player_health = None
self.bomb_state = None
self.ammo_status = None
class MyRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers['Content-Length'])
body = self.rfile.read(length).decode('utf-8')
self.parse_payload(json.loads(body))
self.send_header('Content-type', 'text/html')
self.send_response(200)
self.end_headers()
def parse_payload(self, payload):
bomb_state = self.get_bomb_state(payload)
if bomb_state != self.server.bomb_state:
self.server.bomb_state = bomb_state
sendBombStatus(bomb_state)
print('Bomb state: %s' % bomb_state)
def get_bomb_state(self, payload):
if 'round' in payload and 'bomb' in payload['round']:
return payload['round']['bomb']
else:
return None
def log_message(self, format, *args):
#Prevents requests from printing into the console
return
server = MyServer(('localhost', 3001), MyRequestHandler) # make sure cfg's and this port is same
server.init_state()
try:
server.serve_forever()
except (KeyboardInterrupt, SystemExit):
pass
server.server_close()
Codigo arduino:
char Buffer[3];
uint8_t health, bombStatus, bombBegin, ammoBegin, ammoStatus, ledLOW, ledHIGH;
uint16_t bombBlinkLength;
unsigned long bombPreviousLength, ammoBlinkLength;
int bPin = 9;
const uint8_t gPin = 10;
const uint8_t rPin = 11;
uint8_t hRed, hGreen, hBlue;
char commonAC = 'a'; //if RGB led is common anode 'a' else 'c'
void setCommonAC(){
if(commonAC == 'a'){
ledLOW = 255;
ledHIGH = 0;
}
else if(commonAC == 'c'){
ledLOW = 0;
ledHIGH = 255;
}
}
void readSerialData(){
Buffer[0] = NULL;
Buffer[0] = Serial.read();
if(Buffer[0] == 'b'){
readBombData();
}
}
uint8_t chartoInt(){
Buffer[0] = NULL; Buffer[1] = NULL; Buffer[2] = NULL;
Serial.readBytes(Buffer, 3);
Buffer[0] = (Buffer[0] - '0');
Buffer[1] = (Buffer[1] - '0');
Buffer[2] = (Buffer[2] - '0');
Buffer[0] *= 100;
Buffer[1] *= 10;
return Buffer[0] + Buffer[1] + Buffer[2];
}
void readBombData(){
Buffer[0] = Serial.read();
if(Buffer[0] == 'p'){
bombStatus = 1;
bombBegin = 1;
}
else if(Buffer[0] == 'd'){
bombStatus = 2;
}
else if(Buffer[0] == 'pb'){
bombStatus = 3;
}
else if(Buffer[0] == 'n'){
bombStatus = 0;
bombBlinkLength = 1000;
}
}
void bombBlink(){
for(size_t i = 0; i < 100; i++){
driveRGB(i, 0, 0);
delay(2);
}
for(size_t i = 100; i > 0; i--){
driveRGB(i, 0, 0);
delay(2);
}
driveRGB(hRed, hGreen, hBlue);
}
void driveBomb(){
if(bombBegin == 1){
bombBlink();
bombPreviousLength = millis();
bombBegin = 0;
}
else if(bombStatus == 1){
if((millis() - bombPreviousLength) > bombBlinkLength){
bombBlink();
bombBlinkLength -= 25;
bombPreviousLength = millis();
}
}
else if(bombStatus == 2){
bombPreviousLength = millis();
while((millis() - bombPreviousLength) < 5000){
driveRGB(0, 100, 0);
}
bombStatus = 0;
}
else if(bombStatus == 3){
bombPreviousLength = millis();
while((millis() - bombPreviousLength) < 5000){
driveRGB(255,255, 255);
}
bombStatus = 0;
}
}
void driveRGB(uint8_t red, uint8_t green, uint8_t blue){
red = map(red, 0, 100, ledLOW, ledHIGH);
green = map(green, 0, 100, ledLOW, ledHIGH);
blue = map(blue, 0, 100, ledLOW, ledHIGH);
analogWrite(rPin, red);
analogWrite(gPin, green);
analogWrite(bPin, blue);
}
void setup() {
Serial.begin(9600);
pinMode(rPin, OUTPUT);
pinMode(gPin, OUTPUT);
pinMode(bPin, OUTPUT);
digitalWrite(bPin, HIGH);
}
void loop() {
readSerialData();
driveBomb();
}