0

I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the ser.write() command in a while loop (which I want to avoid) the sketch runs fine.

For example, I wrote this script on my PC -

import serial
ser = serial.Serial('COM3',9600)
counter = 'Y'
ser.write(counter)

This script should pass a "Y" to the Arduino and should stop executing.

My Arduino code-

int flag = 0;
void setup() {
   Serial.begin(9600); // set the baud rate
   Serial.println("Ready"); // print "Ready" once
   pinMode(13, OUTPUT);
}

void loop() {
   char inByte = ' ';
   if(Serial.available()){
      inByte = Serial.read(); // read the incoming data
      Serial.println(inByte); 
      flag ++;
   }
   if(flag == 1){
      digtalWrite(13, HIGH);
   }
}

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put ser.write in a loop. I can't put ser.write in a loop as my script won't run further.

So how can a value be passed to an Arduino without having to put the ser.write() in a loop.

Thanks!

EDIT :

I wrote a new sketch, but it still doesn't work. Here's the sketch -

int ledPin = 13;
char data = ' ';

void setup(){
   pinMode(ledPin, OUTPUT);
   Serial.begin(9600);
}

void loop(){
   if (Serial.available()>0) {
      data = Serial.read();
   }
   if (data == 'Y'){
      digitalWrite(ledPin, HIGH);
   }
   delay(500);
}

Here's an image of the wiring - enter image description here

1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Nick Gammon
    Commented Jun 5, 2016 at 6:30

1 Answer 1

0

Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.