I have a code which reads a light sensor and spins a servo corresponding to the value of the light, and a code that connects the servo to an app that I made and you can manually control it. I'm having trouble getting it to switch between the two. What I originally wanted was for it to see if the Bluetooth was connected to a phone and switch if it wasn't, but I changed it to change codes depending on if a button was pressed. The two codes work individually, but not when combined. I don not know what's wrong with the code, it only reads the light sensor when combined
int programState = 0;
#include <Servo.h>
#include <SoftwareSerial.h>
Servo myservo;
int photocellPin=0;
int servoPin=9;
int pos = 0;
int bluetoothTx = 10;
int bluetoothRx = 11;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup() {
// put your setup code here, to run once:
myservo.attach(9);
//Setup USB serial connection to computer
Serial.begin(115200);
//Setup Bluetooth serial connection to android
bluetooth.begin(115200);
}
void loop()
{
if(digitalRead(0)) //Button is pressed
{
programState = 1 - programState; //Flip-Flop state between 0 and 1
}
if(programState == 0) //Check to see which state to run
{
//Read from Bluetooth and write to USB serial
if(bluetooth.available()> 0 )
{
int servopos = bluetooth.read();
Serial.println(servopos);
myservo.write(servopos);
}
}
else
{
Serial.print("Cell=");
Serial.println(analogRead(photocellPin));
pos=analogRead(photocellPin);
pos=constrain(pos, 220, 740);
int servoPos = map(pos, 220, 740, 225, 0);
int servoDegree = map(servoPos, 225,0, 0, 179);
myservo.write(servoDegree);
Serial.print("Servo Degree=");
Serial.print(servoDegree);
delay(100);
}
}
the if statement sets up the Bluetooth module so that the servo can be controlled by an Android app
the else statement makes if so that the servo is controlled by the value getting sent from the photocell that's attached
Each work individually but when placed into an if-else statement it only reads the else
The Arduino should switch between the two codes by pressing a button