First post, so forgive me if this is in the wrong place, too detailed, not detailed enough, etc....
I'm trying to build an Arduino based alarm system - A few (very bright) LEDs point at an LDR, and when then LEDs are turned off / moved, the arduino sounds the alarm. The idea, of course, being that when the LDR finds the light to be much less, it does .
consists of writing to serial "1", which a python program on my computer should intemperate, and do it's part, until a "0" is written to Serial, which happens when a button is pressed. This essentially 'deactivates' the alarm.
When watching the serial communication in the arduino IDE (tools > Serial Monitor), all is well - "1" appears when the light is removed, and "0" appears once the light is back in place and the button has been pressed.
However - when looking at the same serial communications from my Python program, only "1" is printed, and it continues to print repeatedly until the light is put back infront of the LDR. Upon pushing the button to print a "0", nothing happens.
Anyway, Here's my code:
Arduino:
const int buttonPin = 2;
const int Buzzer1 = 3;
const int LDR = A0;
int LDRValue = 0;
int buttonState = 0;
int alarmActivated = 0; //0 = no, 1 = yes
void setup() {
// initialize the piezo as output:
pinMode(Buzzer1, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop(){
buttonState = digitalRead(buttonPin);
LDRValue = analogRead(LDR);
//Serial.println(LDRValue);
if ((LDRValue < 1000) && (alarmActivated == 0)) {
Serial.print("1");
Serial.print("\n");
tone(Buzzer1, 500, 500);
//door is open
alarmActivated = 1;
}
if ((alarmActivated == 1) && (buttonState == HIGH)) {
Serial.print("0");
Serial.print("\n");
alarmActivated = 0;
noTone(Buzzer1);
}
}
Python:
import serial
def readSerial(port, baudrate):
arduinoData = serial.Serial(port, baudrate)
arduinoSerial = (arduinoData.readline().strip())
text = arduinoSerial.decode('utf-8')
return text
def doYourThingPython():
#not yet coded :(
#if line = 1, play sound1
#if line = 0, stop sound1
while True:
for line in readSerial('/dev/ttyUSB0', 9600):
print(line)
doYourThingPython(line)