MBot kontrolleras av Wireless Joystick med mig USB-värd (3 / 4 steg)
Steg 3: kodning
enkel kod för testning dc motor controll
#include "MeUsb.h"
MeUsb usb(10,9); använda mjukvaran följetong, ställa in PIN-kod för tx, rx
void setup()
{
Serial.BEGIN(9600);
USB.init(USB1_0);
initiera USB-värd
}
void loop()
{
IF(!USB.device_online)
{
usb.probeDevice();
Poll för USB-enhetens anslutning
Delay(100);
}
annat
{
mottagna data från USB-enhet
int längd = usb.host_recv();
IF(len>4) {
parseJoystick (usb. RECV_BUFFER);
}
}
}
void parseJoystick (unsigned char * buf)
{
tolka joystickens data
uint8_t buttonCode = buf [4] & 0xff;
uint8_t buttonCode_ext = buf [5] & 0xff;
uint8_t joystickCodeL_V = buf [3] & 0xff; Top 0 botten ff
uint8_t joystickCodeL_H = buf [2] & 0xff; vänster 0 rätt ff
uint8_t joystickCodeR_V = buf [1] & 0xff; Top 0 botten ff
uint8_t joystickCodeR_H = buf [0] & 0xff; vänster 0 rätt ff
uint8_t directionButtonCode = (buttonCode & 0xf);
uint8_t rightButtonCode = (buttonCode & 0xf0) >> 4;
Switch(directionButtonCode) {
...
fall 2: {
motor springa medurs
runMotor(MOTOR_1,100);
runMotor(MOTOR_2,100);
bryta;
}
...
mål 6: {
motor kör motsols
runMotor(MOTOR_1,-100);
runMotor(MOTOR_2,-100);
bryta;
}
...
standard: {
utgåvan;
runMotor(MOTOR_1,0);
runMotor(MOTOR_2,0);
}
}
}
void runMotor (int motor, int hastighet) {
DC motor driver
int _dirPin;
int _pwmPin;
IF(motor==MOTOR_1) {
_dirPin = 7.
_pwmPin = 6;
} annat if(motor==MOTOR_2) {
_dirPin = 4;
_pwmPin = 5;
}
pinMode(_dirPin,OUTPUT);
pinMode(_pwmPin,OUTPUT);
digitalWrite (_dirPin, hastighet > 0);
analogWrite(_pwmPin,abs(speed));
}