Hi, first post. I am fairly competent with JavaScript and have been trying to control my robot using the johnny-five library with a direct usb connection, so far to no avail.
I have already written a function which controls a mirobot drawing bot, I am trying to write the same code for Arduino, but have no exposure to C++.
This is my code:
#include <AFMotor.h>
AF_DCMotor motor1(3, MOTOR12_64KHZ);
AF_DCMotor motor2(4, MOTOR12_64KHZ);
int rndNumber;
int rndNumberLength;
int rndNumberArc;
word motor = 'motor1'; // does not work
word direction = 'FORWARD'; // does not work
void setup()
{
//Set initial speed of the motor & stop
motor1.setSpeed(100);
motor2.setSpeed(100);
motor1.run(RELEASE);
motor2.run(RELEASE);
}
void drawLine ()
{
uint8_t i;
rndNumberLength = random(255); // set random number between 1 and 255
motor1.run(FORWARD); // both motors forward
motor2.run(FORWARD);
// Accelerate from zero to max speed defined by rndNumber
for (i=0; i<rndNumberLength; i++)
{
motor1.setSpeed(i);
motor2.setSpeed(i);
delay(10);
}
// Decelerate from maximum speed to zero
for (i=255; i!=0; i--)
{
motor1.setSpeed(i);
motor2.setSpeed(i);
delay(10);
}
// Now turn off motor
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(1000);
}
void drawArc ()
{
uint8_t i;
rndNumber = random(2); // set random numner between 1 and 2
rndNumberArc - random(100); // set random number between 1 and 100
if(rndNumber == 1) {
motor = motor1;
direction = FORWARD;
} else {
motor = motor2;
direction = BACKWARD;
}
motor.run(direction);
// Accelerate from zero to max speed defined by rndNumber
for (i=0; i<rndNumberArc; i++)
{
motor.setSpeed(i);
delay(10);
}
// Decelerate from maximum speed to zero
for (i=255; i!=0; i--)
{
motor.setSpeed(i);
delay(10);
}
// Now turn off motor
motor.run(RELEASE);
delay(1000);
}
void loop()
{
// rndNumber === 0 ? drawLine() : drawArc(); // convert this to C++
}
The basic premise is to initialise 1 of 2 functions depending on calling random number (between 1 and 2).
If 1 then run drawLine() function else drawArc(). That is the loop. Both the functions should also pass in random values for length, radius or time etc.
It seems to make sense to wrap these functions and then initialise them via a callback. I was trying to read up on that here:
- Gammon Forum : Electronics : Microprocessors : Function pointers / function callbacks / function variables
- why use callbacks - Programming Questions - Arduino Forum
If it helps anyone I have a jsfiddle here: Control micro-bit robot via JS - JSFiddle - Code Playground
Which contains pretty much the exact JS code. you can paste that code into this app: mirobot.io and see it working (sorry this is very roundabout).
I realise there are several errors in my code, I have been playing with this for some time, and decided to bite the bullet and hope someone here can help. TIA