Skip to content

Instantly share code, notes, and snippets.

@simonrozsival
Created February 24, 2018 21:17
Show Gist options
  • Save simonrozsival/5660aefeec74a90bcb5a59e3a87a0eb3 to your computer and use it in GitHub Desktop.
Save simonrozsival/5660aefeec74a90bcb5a59e3a87a0eb3 to your computer and use it in GitHub Desktop.
this does not work yet
/*
* Raceing car steering
* - receives commands from the '/racer/driving' topic from ROS on a Raspberry PI through serial port
* - translates throttle and steering commands into servo control
* - publishes actions in the '/racer/driving_status' channel
*/
#include <stdio.h>
#include <ros.h>
#include <geometry_msgs/Twist.h>
#include <Servo.h>
#include <algorithm.h>
#include <string.h>
#define BAUD_RATE 115200
#define STEERING_PIN 9
#define ESC_PIN 10
#define STEERING_LEFT -1
#define STEERING_CENTER 0
#define STEERING_RIGHT 1
#define SPEED_FULL_REVERSE -1
#define SPEED_NEUTRAL 0
#define SPEED_FULL_FORWARD 1
const std::string driving_topic = "/racer/driving";
const std::string driving_status_topic = "/racer/driving_status";
double fmap(double value, double in_min, double in_max, double out_min, double out_max);
void drive_callback(const geometry_msgs::Twist& twist_msg);
ros::NodeHandle node_handle;
std_msgs::String status_msg;
ros::Publisher driving_status(driving_status_topic, &status_msg);
ros::Subscriber<geom> driving(driving_topic, &drive_callback);
Servo steering_servo;
Servo esc_throttle; // The ESC works like a Servo
void setup() {
Serial.begin(BAUD_RATE));
node_handle.initNode();
node_handle.advertise(driving_status);
node_handle.subscribe(driving);
steering_servo.attach(STEERING_PIN);
esc_servo.attach(ESC_PIN);
steering_servo.write(STEERING_CENTER) ;
esc_servo.write(SPEED_NEUTRAL);
}
void loop() {
node_handle.loopOnce();
delay(1);
}
void drive_callback(const geometry_msgs::Twist& twist_msg) {
int steering_angle = fmap(twist_msg.angular.z, 0.0, 1.0, STEERING_LEFT, STEERING_RIGHT);
int throttle = fmap(twist_msg.liner.xm, 0.0, 1.0, SPEED_FULL_REVERSE, SPEED_FULL_FORWARD);
steerring_servo.write(steering_angle);
esc_servo.write(throttle);
}
double fmap(double value, double in_min, double in_max, double out_min, double out_max) {
double mapped_value = (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
return std::clamp(mapped_value, out_min, out_max);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment