This is my transmitter and receiver codes.
//Transmitter Code
int button1 = 9;
int button2 = 10;
int button1Value = 20;
int button2Value = 165;
int currentMode = 1;
void setup()
{
Serial.begin(9600); // Startup the Serial Interface
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
}
void loop()
{
char buf[4];
if (!digitalRead(button1) && currentMode != 1) {
sprintf(buf, "%dx", button1Value);
Serial.print(buf);
currentMode = 1;
delay(500);
}
if (!digitalRead(button1) && currentMode != 2) {
sprintf(buf, "%dx", button2Value);
Serial.print(buf);
currentMode = 2;
delay(500);
}
}
//Receiver Code
#include <Servo.h>
Servo myservo; // Create servo object to control a servo
char readstr[4]; // Character Array to store the serial input
int cstrpos = 0; // Variable to store current input array position
long val = 0; // variable to store the value from the input
int maxValue = 175;
void setup()
{
Serial.begin(9600); // Startup the Serial Interface
myservo.attach(9); // Attaches the servo on pin 9 to the servo object
}
void loop()
{
char ch; //A Place to Store the character we just read
if (Serial.available()) // is there anything to be read from serial port?
{
ch = Serial.read(); // read a single character
// print out to serial port the character we received (similar to an echo)
//Serial.print(ch);
if (ch >= '0' && ch <= '9') // Number so store it in the input array
{
readstr[cstrpos] = ch; // Add the read character to the array of read numbers
++cstrpos; // Increase the positions in the array
}
else
{
readstr[cstrpos] = '\0'; // Add a null to the end of the string array to terminate the string
val = atol(readstr); // Convert the string to a long int
if (val > maxValue) {
val = 175;
}
cstrpos = 0; // Reset the array position back to the beginning so the next input starts a new input
//Print to the serial port what we are going to do
Serial.print("Servo set to: ");
Serial.println(val);
Serial.println("");
}
}
// The servo needs constant feed of values so we constantly output the PWM value
myservo.write(val); // Set the PWM value to send to the servo
delay(15); // Just a little delay
}
I want to add another servo to this and i want both servos to move at the same time. But i want one servo always to move opposite from the other servo. What do i need to add to this code?