I am trying to send integer from my Python program to Arduino MEGA. If I send 1, the LED should turn on and If I send 0 the LED should turn off.
I was able to write Python code correctly as I think. I have configure the port and made serialWrite(val)
function for send data to Arduino only if data is changed.
This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used serialWrite(val)
function to prevent that.
But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?
import serial as ser
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
preSerVal=0
#function for send data..data will send only val is changed
def serialWrite(val):
global preSerVal
if(not preSerVal == val):
prt.write(str(val)+'\r\n')
preSerVal=val
This is my Arduino program.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}
byte incomingByte;
void loop()
{
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (incomingByte == '1') {
digitalWrite(13, HIGH);
} else if (incomingByte == '0') {
digitalWrite(13, LOW);
}
}
}
UPDATE 1
I write testing program like this.
Python code:
import serial as ser
import time
preSerVal=0
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
def serialWrite(val):
global preSerVal
if(not preSerVal == val):
prt.write(str(val)+'\r\n')
preSerVal=val
while 1:
for i in range(0,10):
serialWrite(0)
time.sleep(1)
for i in range(0,10):
serialWrite(1)
Arduino code:
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}
byte incomingByte;
void loop()
{
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (incomingByte == '1') {
digitalWrite(13, HIGH);
} else if (incomingByte == '0') {
digitalWrite(13, LOW);
}
}
}
This code gives this result. see the video bellow:
https://www.youtube.com/watch?v=utC4vo8YDVU&list=PLM5AA5oFchgC25da44Q2X900pz0eojSQJ&index=1
UPDATE 2
This is a piece of code..it sends 0..i checked it.
try:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
houghCenter=(i[0],i[1])
cv2.circle(src,houghCenter,i[2],(0,255,0),2)
cv2.circle(src,houghCenter,2,(0,255,255),1)
cv2.circle(drawing,houghCenter,i[2],(0,255,0),2)
cv2.circle(drawing,houghCenter,2,(0,255,255),1)
#print (houghCenter," ",contourCenter)
dx=math.fabs(houghCenter[0]-contourCenter[0])
dy =math.fabs(houghCenter[1]-contourCenter[1])
if (dx>diff and dy>diff):
serialWrite(0)
else:
serialWrite(1)
except Exception:
serialWrite(0)
time.sleep(1)
and see if anything changes. – SoreDakeNoKoto Sep 24 '16 at 23:48serialWrite()
avoids sending twice same data. Then add theprint
afterprt.write
if the 1 and 0 are wery fast you will not have time to see anything blink. If you do not describe the expected and observed behaviour I cannot help you – Julien Sep 25 '16 at 9:22