how to i make this two diferent codes work a¡in the same skecth but with afecting the other. When i tried combining them together, it started working slow, as if one is working after the other. Here is the two code combined
#define trigPin 6
#define echoPin 7
int speakerPin = 8;
Servo gripperPin;
Servo wristPin;
Servo armPin;
Servo shoulderPin;
Servo basePin;
int potpin = 0;
int potpin1 =1;
int potpin2 =2;
int potpin3 =3;
int potpin4 =4;
int val;
int timer = 100;
void setup() {
gripperPin.attach(3);
wristPin.attach(5);
armPin.attach(9);
shoulderPin.attach(10);
basePin.attach(11);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
for (int thisPin = 0; thisPin < 2; thisPin++) {
pinMode(thisPin, OUTPUT);
}
pinMode(speakerPin, OUTPUT);
}
void loop() {
//GripperPin a pin analògic 0
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 250);
gripperPin.write(val);
delay(15);
val = analogRead(potpin1);
val = map(val, 0, 1023, 10, 250);
wristPin.write(val);
delay(15);
val = analogRead(potpin2);
val = map(val, 0, 1023, 45, 150);
armPin.write(val);
delay(15);
val = analogRead(potpin3);
val = map(val, 0, 1023, 45, 150);
shoulderPin.write(val);
delay(15);
val = analogRead(potpin4);
val = map(val, 0, 1023, 45, 150);
basePin.write(val);
delay(15);
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance <= 7) {
for (int thisPin = 0; thisPin < 2; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
tone(speakerPin, 200000, 200);
}
// loop from the highest pin to the lowest:
for (int thisPin = 2; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
tone(speakerPin, 200000, 200);
}
}
else if (distance > 7 && distance <= 14){
for (int thisPin = 0; thisPin < 2; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
tone(speakerPin, 5000, 200);
}
// loop from the highest pin to the lowest:
for (int thisPin = 2; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
tone(speakerPin, 5000, 200);
}
}
else if (distance > 14 && distance <= 21){
for (int thisPin = 0; thisPin < 2; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
tone(speakerPin, 1000, 200);
}
// loop from the highest pin to the lowest:
for (int thisPin = 2; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
tone(speakerPin, 1000, 200);
}
}
else if (distance > 21|| distance <= 0){
noTone(speakerPin);
}
delay(300);
}