Stap 3: codering
eenvoudige code voor testen dc motor controle
#include "MeUsb.h"MeUsb usb(10,9); //use software serial, setting up pin for tx,rx
void setup() { Serial.begin(9600); usb.init(USB1_0); //initialize USB Host } void loop() { if(!usb.device_online) { usb.probeDevice(); //poll for usb device's connection delay(100); } else { //received data from usb device int len = usb.host_recv(); if(len>4){ parseJoystick(usb.RECV_BUFFER); } } } void parseJoystick(unsigned char * buf) { //parse joystick's data uint8_t buttonCode = buf[4]&0xff; uint8_t buttonCode_ext = buf[5]&0xff; uint8_t joystickCodeL_V = buf[3]&0xff; //top 0 bottom ff uint8_t joystickCodeL_H = buf[2]&0xff; //left 0 right ff uint8_t joystickCodeR_V = buf[1]&0xff; //top 0 bottom ff uint8_t joystickCodeR_H = buf[0]&0xff; //left 0 right ff uint8_t directionButtonCode = (buttonCode&0xf); uint8_t rightButtonCode = (buttonCode&0xf0)>>4; switch(directionButtonCode){ ... case 2:{ //motor run clockwise runMotor(MOTOR_1,100); runMotor(MOTOR_2,100); break; } ... case 6:{ //motor run counterclockwise runMotor(MOTOR_1,-100); runMotor(MOTOR_2,-100); break; } ... default:{ // release; runMotor(MOTOR_1,0); runMotor(MOTOR_2,0); } } } void runMotor(int motor,int speed){ //dc motor driver int _dirPin; int _pwmPin; if(motor==MOTOR_1){ _dirPin = 7; _pwmPin = 6; }else if(motor==MOTOR_2){ _dirPin = 4; _pwmPin = 5; } pinMode(_dirPin,OUTPUT); pinMode(_pwmPin,OUTPUT); digitalWrite(_dirPin,speed>0); analogWrite(_pwmPin,abs(speed)); }