2

I am trying to control LEDs connected to Arduino from Python through serial communication. I am attaching both codes in Arduino and python. But I am not getting any response from LEDs when I run the code in Python, though I am not getting any errors. Maybe I am making some mistakes in the syntax?

import serial
import time
arduino=serial.Serial('COM3',250000,timeout=5.0)
m=[]
commands=open('1.txt','r')
lines=commands.readlines()                  
for line in lines:                       
    m.append(line)
commands.close()
s=0
while s!=len(m):
    m[s]=float(m[s])
    s+=1
s=0

def delay():
    x=0
    y=0
    while x!=y:
        x+=1
while s!=len(m):
    c=str(m[s])
    if m[s]==1:
        arduino.write(b'c')
        time.sleep(2)
        print('1on')

    elif m[s]==-1:
        arduino.write(b'c')
        time.sleep(2)
        print('1off')
        delay()
    elif m[s]==2:
        arduino.write(b'c')
        time.sleep(2)
        print('2on')

    elif m[s]==-2:
        arduino.write(b'c')
        time.sleep(2)
        print('2off')

    elif m[s]==3:
        arduino.write(b'c')
        time.sleep(2)
        print('3on')

    elif m[s]==-3:
        arduino.write(b'c')
        time.sleep(2)
        print('3off')

    s+=1

This is the code to control LEDs from Python in Arduino. Arduino code is below

int led1=2;
int led2=3;
int led3=4;
void setup()
{
  Serial.begin(250000);
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led3,OUTPUT);
}
void loop()
{
  if(Serial.available())
  {
    int v=Serial.parseInt();
    if(v==1)
    {
      digitalWrite(led1,HIGH);
      delay(1000);
     }
    else if(v==-1)
    {
      digitalWrite(led1,LOW);
      delay(1000);
    }
    else if(v==2)
    {
      digitalWrite(led2,HIGH);
      delay(1000);
    }
    else if(v==-2)
    {
      digitalWrite(led2,LOW);
      delay(1000);
    }
    else if(v==3)
    {
      digitalWrite(led3,HIGH);
      delay(1000);
    }
    else if(v==-3)
    {
      digitalWrite(led3,LOW);
      delay(1000);
    }
  }
}

3 Answers 3

3

I don't know Python but the problem seem to be the following: arduino.write(b'c'). You keep on sending the "c" character. Shouldn't it be sending whatever is in the c variable?

Sign up to request clarification or add additional context in comments.

1 Comment

yeah it should send the data whatever in the variable c
2

As Blurry Sterk said, you're sending the character 'c' instead of the variable c. Apart from that your code has too much repetition and delay function does nothing

For example, your python code could be much simplier like this:

import serial
import time
arduino=serial.Serial('COM3',250000,timeout=5.0)
m=[]
commands=open('1.txt','r')

lines=commands.readlines()                  
for line in lines:                       
    m.append(float(line)) #Just convert to float at the moment you read it

commands.close()

for c in m:
    arduino.write(str(c).encode())
    time.sleep(2)
    print(abs(c), 'on' if c>0 else 'off') #First two lines are the same in every if sentence, the last one just prints the number of led (abs(c)) and if it's on or off depending if it's negative or positive

Your arduino code can be more readable too if you use an array for the leds and use the absolute value to access the index of the array, similar to the logic in the print statement in python

5 Comments

Traceback (most recent call last): File "C:/Users/shiva/Desktop/desktopfolders/Python/practice3.py", line 14, in <module> arduino.write(str(c)) File "C:\Users\shiva\AppData\Local\Programs\Python\Python35\lib\site-packages\serial\serialwin32.py", line 286, in write data = to_bytes(data) File "C:\Users\shiva\AppData\Local\Programs\Python\Python35\lib\site-packages\serial\serialutil.py", line 76, in to_bytes b.append(item) # this one handles int and str for our emulation and ints for Python 3.x TypeError: an integer is required I AM GETTING THIS ERROR. PLEASE HELP
Sorry my bad, pyserial module documentation says write expects bytearray type to send to arduino. You should do arduino.write(bytearray(str(c)))
Traceback (most recent call last): File "C:/Users/shiva/Desktop/desktopfolders/Python/practice3.py", line 14, in <module> arduino.write(bytearray(str(c))) TypeError: string argument without an encoding NOW THIS
Got it . Tried' arduino.write(bytearray(str(c).encode()))' . thanks for your valuable help Sir.
Serial.Serial(), it says it's a float number that sets how much pyserial should wait for the arduino's answer, if that time passes it will cut the answer and return what has been read. If you don't want to stop reading (Warning) you can skip it arduino = serial.Serial('COM3', 2500000)
0

as Mr. E pointed out, the delay function does nothing. Maybe you wanted this:

def delay(y=0):
if not isinstance(y, int):
    raise ValueError('y must be integer')
if y<0:
    raise ValueError('If y is negative the loop is infinite.')
x=0
while x!=y:
    x+=1

That would in fact, delay the processing of instructions. Is this the best way to achieve that? I don't know.

1 Comment

Delaying via loop is normally a bad idea, as the delay depends on the processore speed. It works only well at very low-level programming. In python time.sleep is usually what you want. Even if you delay via loop, you must take care, that the compiler/interpreter does not optimize it out.

Your Answer

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