Probleme encodage pour arduino
Salut
J'ai un petit soucis de dialogue entre l'arduino et python3
Le script python surveille mqtt a chaque message il active un switch controler par un MCP23017
En premier le prog arduino
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #include "Adafruit_MCP23017.h"
#include "Wire.h"
Adafruit_MCP23017 mcp;
void setup() {
mcp.begin();
for (int pin = 0; pin < 16; pin ++)
{
mcp.pinMode(pin, OUTPUT);
}
for (int pin = 0; pin < 16; pin++)
{
mcp.digitalWrite(pin, HIGH);
}
Serial.begin(9600);
}
void loop() {
if(Serial.available())
{
String pinstr = Serial.readStringUntil(',');
String commandestr = Serial.readStringUntil('\n');
int pin = pinstr.toInt();
Serial.print(pin);
int commande = commandestr.toInt();
Serial.print(commande);
mcp.digitalWrite(pin, commande); |
avec ce programme en ligne de commande ca marche nikel
Code:
1 2 3
| >>> ser=serial.Serial('/dev/ttyUSB0', 9600, timeout=1, writeTimeout=1)
>>> ser.write(b'1,1')
3 |
par contre quand je lance le script seul le pin 0 est activé ....
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import sys
import queue
import serial
import time
import threading
from threading import *
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
class arduinocommande(threading.Thread):
def __init__(self, commande,fin):
threading.Thread.__init__(self)
self.commande=commande
self.terminated = fin
def run(self):
while self.terminated:
try:
ser = serial.Serial('/dev/tty-arduino', 9600, timeout=1, writeTimeout=1)
time.sleep(6)
print("connection ok")
while ser.isOpen():
if not self.commande.empty():
com=str(self.commande.get())+"\n"
print ("commande "+str(com))
com=bytes(com,'utf-8')
ser.write(com)
print (ser.readline())
print (ser.readline())
time.sleep(0.5)
except:
try:ser.close()
except:pass
print(sys.exc_info())
time.sleep(3)
commande=queue.Queue()
fin=True
arduinocommande(commande,fin).start()
def on_connect(client, userdata, flags, rc):
print ("Connected with result code "+str(rc))
client.subscribe("filpilote")
def on_message(client, userdata, msg):
print(msg.payload)
commande.put(str(msg.payload))
while True:
try:
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("127.0.0.1", 1883, 60)
client.loop_forever()
except:
print(sys.exc_info())
print ("Exception handled, reconnecting...\nDetail:\n%s")
time.sleep(5)
fin=False |
Je lance la commande mqtt avec ce script
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
| import sys
import paho.mqtt.publish as publish
import urllib2
print sys.argv
channel=sys.argv[1]
command=sys.argv[2]
host=sys.argv[3]
publish.single(channel,command, hostname=host) |
Code:
python mqttc.py filpilote 9,0 10.0.0.22
Un peu aide ?
Merci