Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Robot Car remote control v2.1
- This is one of my first Arduino projects.
- Code for the car is available at:
- https://pastebin.com/eDuD2shA
- Enjoy!
- The circuit:
- 433Mhz RF trasmitter:
- ** DAT - pin 12
- Joystick module:
- ** VRx - pin A6
- ** VRy - pin A7
- Push button:
- ** button - pin A2
- created 1 Febr 2020
- modified 23 May 2020
- by Mate Z.
- */
- #include <RH_ASK.h> //Radio Head RF library
- #include <SPI.h> //previous one needs it
- #include <string.h>
- RH_ASK rf_driver;
- int Xvalue;
- int Yvalue;
- int Bpress;
- int Brel = 1;
- char message[6];
- char prevMessage[6];
- int maxSpeed = 100;
- int currentSpeed = 0;
- #define Xpin A6
- #define Ypin A7
- #define Bpin A2
- void setup() {
- // put your setup code here, to run once:
- rf_driver.init();
- pinMode(LED_BUILTIN, OUTPUT);
- pinMode(Xpin, INPUT);
- pinMode(Ypin, INPUT);
- pinMode(Bpin, INPUT);
- Serial.begin(9600);
- }
- void maxSpeedChg(){
- if(maxSpeed!=250) maxSpeed+=50;
- else maxSpeed=100;
- }
- void sendMsg(const String& output){
- char *message = output.c_str();
- if(strcmp(message, prevMessage)!=0 || (millis()%1000 < 3 && message[0] != 'D')){
- rf_driver.send((uint8_t *)message, strlen(message));
- rf_driver.waitPacketSent();
- Serial.print("Transmitting code:\t");
- Serial.println(message);
- strcpy(prevMessage, message);
- }
- }
- void loop() {
- // put your main code here, to run repeatedly:
- Xvalue=analogRead(Xpin)-525;
- Yvalue=analogRead(Ypin)-525;
- Bpress=digitalRead(Bpin);
- if(millis()%250==0){
- Serial.print("Joystick data: ");
- Serial.print("X: ");
- Serial.print(Xvalue);
- Serial.print(" Y: ");
- Serial.print(Yvalue);
- Serial.print("\tButton: ");
- Serial.println(Bpress);
- }
- String output;
- if(Bpress && Brel){
- maxSpeedChg();
- Serial.print("speed change: ");
- Serial.println(maxSpeed);
- Brel = 0;
- }
- else{
- if(!Bpress) Brel = 1;
- if(abs(Yvalue)<abs(Xvalue)){
- if (Xvalue > 120){ //FWD
- currentSpeed = map(sqrt(Xvalue), 10, sqrt(500), 60, maxSpeed);
- output = 'F';
- }
- else if (Xvalue < -120){ //BWD
- currentSpeed = map(sqrt(abs(Xvalue)), 10, sqrt(525), 60, maxSpeed);
- output = 'B';
- }
- else{ //DEF
- currentSpeed = 0;
- output = 'D';
- }
- }
- if(abs(Xvalue)<abs(Yvalue)){ //RGT
- if (Yvalue > 120){
- currentSpeed = map(sqrt(Yvalue), 10, sqrt(500), 80, maxSpeed);
- output = 'R';
- }
- else if (Yvalue < -120){ //LFT
- currentSpeed = map(sqrt(abs(Yvalue)), 10, sqrt(525), 80, maxSpeed);
- output = 'L';
- }
- else{ //DEF
- currentSpeed = 0;
- output = 'D';
- }
- }
- }
- //Serial.println(output);
- if(strlen(output.c_str())==0) output = 'D';
- if(currentSpeed<100){
- output += '0';
- if(currentSpeed<10) output += '0';
- }
- output += String(currentSpeed);
- sendMsg(output);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement