Arduino restarting when starting the execution of python code

0

I'm new to development and especially to using Arduino. I'm developing a web application with python with some functions, one of them is turning on and off a light bulb (my problem). I developed the code, I used some already ready from the web (for tests) and the big question is, when executing the python code, the arduino simply restarts and does not execute the connection between the code and the arduino. I noticed that when I start the connection (connection = serial.Serial ('COM3', 9600), the problem occurs, I tried that part of the code inside Try and the problem still persists. solve? ps: I'm using Pyserial.

Python code:

import serial
import time
from time import sleep

conexao = serial.Serial('COM3', 9600) 
def escrever_porta():

   try: 
       valor = (raw_input("Digite o valor a ser enviado: "))
       conexao.write(valor)
       conexao.close()

   except serial.SerialException:
       print"ERRO: Verifique se ha algum dispositivo conectado na porta!"

   return valor

Arduino code (already tried several):

#include "EmonLib.h"
#include <SPI.h>

int pin = 7;
char dados = 0;

void setup() {
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
}

void loop() {
  if (Serial.available()) {
    while (Serial) {
      if (Serial.available()) {
        dados =(char)Serial.read();

        if (dados == "0") {
          delay(1);
          Serial.end();
          if (dados == "1") {
            digitalWrite(pin, HIGH);
          } else {
            if (dados == "2") {
              digitalWrite(pin, LOW);
            }
          }
          dados = "" ;
        }
      }
    }
  }
}
    
asked by anonymous 15.04.2017 / 21:33

2 answers

0

The python code is in Python2, is there a chance your python will be 3? If so, the code should have some changes:

raw_input is now input and print will have parentheses ( counteúdo )

import serial
import time
from time import sleep

conexao = serial.Serial('COM3', 9600) 
def escrever_porta():

   try: 
       valor = (input("Digite o valor a ser enviado: ")) 
      #Esses parenteses antes do input é realmente necessário?
      #valor = input("Digite o valor a ser enviado: ")

       conexao.write(valor)
       conexao.close()

   except serial.SerialException:
   #tente também apenas "except:"
       print("ERRO: Verifique se ha algum dispositivo conectado na porta!")

   return valor

I hope I have helped ... If python really is 2.x, then the problem is only valor

    
15.04.2017 / 22:27
0

Make sure the port is correct, it is quite common for OSs to play the arduino to another port, are you really not using a virtual serial port (FTDI)?

    
17.04.2017 / 16:10