Close

Programming the microcontroller

A project log for Freeform robot

A simple robot built from wire

RobsonCoutoRobsonCouto 12/26/2018 at 23:520 Comments

To program the microcontroller I went on the simplest route, which is using Arduino. The ATmega8 can be programmed with the Arduino IDE very easily, without modifications to the IDE files (if you use a 16MHz crystal).  Simply choose "Arduino NG or older" on the boards list, then you can burn the chip directly with a supported programmer (I use the USBASP) or burn the bootloader if you are keen to program the chip with just a USB-serial bridge.

I have implemented the following code, which allows simple obstacle avoiding. Pins 11 and 12 are used by the ultrasonic sensor (HC-SR04), while pins 9 and 10 are used by the servos.

#include <Servo.h>

// pin definitions
#define TRIGGER 11
#define ECHO 12
#define MR 9
#define ML 10
#define LEDB 14
#define LEDR 17

#define THRSHLD 10 //cm

Servo motor_r;
Servo motor_l;

int distance = 0;


void setup() {
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(LEDB, OUTPUT);
  pinMode(LEDR, OUTPUT);


  motor_r.attach(MR);
  motor_l.attach(ML);
}

void loop() {
  distance = measure();
  if (distance > THRSHLD) {
    forward();
    blue();
    delay(200);
  } else {
    left();
    red();
    delay(50);
  }


}

int measure() {
  int duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = duration/58;
  return distance;
}

void blue() {
  digitalWrite(LEDR, LOW);
  digitalWrite(LEDB, HIGH);
}
void red() {
  digitalWrite(LEDR, HIGH);
  digitalWrite(LEDB, LOW);
}

void forward() {
  motor_r.write(180);
  motor_l.write(0);
}

void right() {
  motor_r.write(180);
  motor_l.write(180);
}

void left() {
  motor_r.write(0);
  motor_l.write(0);
}

The hacked servos are deprived of the closed loop positioning. The potentiometer used for knowing the position of the servo's shaft is replaced by two resistors of same value. This way, when telling the motor to go towards 180 or 0 degrees, the servo will try to reach this value, without success, rotating continuously in the process. The motor should stop at 90 degrees, but this depends on the motor and the precision of the resistors used. You have to find the value at which your motor stops, but it should be 90 degrees or very  close.

Discussions