Расширение Arduino для iPhone

iRobbie - это революционное приложение, которое привнесет возможности смартфона в ваши проекты Arduino.

Комплектующие

Это не урок по сборке робота, мы хотим рассказать про возможности нового приложения и ту функциональность, которую можно привнести в проекты. Для понимания нам понадобятся следующие детали:

  • Arduino UNO или Genuino UNO × 1
  • Arduino Sensor Shield v5 × 1
  • Модуль Bluetooth HM-10 × 1
  • Комплект шасси робота 4WD × 1
  • L298N Двойной H-Bridge DC контроллер скорости двигателя × 1
  • 2x18650 держатель батареи × 1
  • Зуммер × 1
  • Подставка для смартфона × 1
  • Arduino комплект проводов × 1
  • Двусторонняя монтажная лента × 1
  • Разъем Arduino Power Jack × 1
  • Набор Arduino Smart Robot Car Kit (опционально) × 1

За основу можно взять наш урок по созданию робота на основе Ардуино, если нет возможности купить или собрать сложного робота.

В качестве альтернативы вы можете купить один из имеющихся в продаже комплектов машинки Smart Robot Car. Убедитесь, что вы используете модуль Bluetooth HM-10. Замените модуль Bluetooth на HM-10, если автомобильный комплект Smart Robot оснащен модулем Bluetooth другого типа.

Программное обеспечение, которое также нам пригодится:

Что такое iRobbie

iRobbie (скачать) - это приложение, которое привнесет возможности и функциональность смартфона в ваши проекты Arduino. iRobbie подключается через Bluetooth к плате Arduino. Вы сможете использовать камеру iPhone и играть с распознаванием объектов, отслеживанием объектов и многим другим.

Также iRobbie App помогает начать изучать компьютерное зрение и нейронные сети. Таким образом робот на основе iRobbie и Arduino может распознавать и отслеживать более 60 объектов, будет меть сенсорный джойстик с сенсорным экраном и даже может воспроизводить музыку.

Функции приложения

Отслеживание объектов - нажмите и перетащите объект, который хотите отслеживать, и ваш робот iRobbie будет следовать за объектом.

iFinder - просто скажите iRobbie что вы хотите, чтобы он нашел. iRobbie может распознать более 60 объектов, и он начнет отслеживать объект после его распознавания.

Голосовое управление - вы можете управлять своим роботом iRobbie голосом.

Пульт дистанционного управления - отзывчивый сенсорный джойстик на вашем iPhone для управления роботом iRobbie.

Ксилофон - проигрывание музыки.

Скачать приложение в AppStore вы можете по ссылке ниже:

Скачать iRobbie-A на AppStore

Это всего лишь пример, который может вдохновить вас на разработку и создание своего собственного робота для игры с приложением iRobbie и использованием плат, деталей или комплектов, совместимых с Arduino.

Модуль Bluetooth HM-10 подключается к сенсорному экрану следующим образом:

  • от RX к TX,
  • от TX к RX,
  • от GND до «-»,
  • от VCC до «+».

Вы можете посетить сайт robbie-app.com для загрузки бесплатных программ и расширений Arduino.

Части машинки

Функция каждой части:

  1. Держатель батареи с выключателем: обеспечить электропитание для машинки
  2. Электродвигатели + колеса: движение робота
  3. Акриловые листы: рама машинки
  4. Плата привода двигателя L298N: приводит двигатели во вращение
  5. Arduino UNO контроллер платы: мозг машины
  6. Расширительная плата датчика V5: в сочетании с UNO облегчает подключение
  7. Модуль Bluetooth HM-10: обеспечивает соединение Bluetooth с iPhone и приложением iRobbie.
  8. Подставка для смартфона: держатель смартфона на машинке

Код проекта

Код Arduino ниже. Вы также может скачать его с сайта robbie-app.com.

#include <Servo.h>

Servo servo;
int angle = 0;
boolean forward1 = false ;
String bluetoothRead, Str_x, Str_y, Str_p, Str_s;
int x ;
int y ;
int points;
int length;
const int buzzer = 10; 
int s;
unsigned long previousMillis = millis();        // will store last time LED was updated

const long interval = 1000;           // interval at which to blink (milliseconds)

#define ENA 11
#define ENB 6
#define IN1 5
#define IN2 7
#define IN3 8
#define IN4 9
#define DELAY 20

int carSpeed = (y*3);
int speed_Coeff = (1 + (x/50));

void setup() { 
  Serial.begin(9600);
  Serial.flush();
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  pinMode(ENA,OUTPUT);
  pinMode(ENB,OUTPUT);
  pinMode(buzzer, OUTPUT);
  stop();
  servo.attach(13);
  servo.write(angle);
}

void loop() {
 int i=0;
  char commandbuffer[200];
unsigned long currentMillis = millis();

  if(Serial.available()){
    
     delay(10);

     while( Serial.available() && i< 199) {
        commandbuffer[i++] = Serial.read();
  
      
     }
     commandbuffer[i++]='\0';
     bluetoothRead = (char*)commandbuffer;
     length = bluetoothRead.length();
     Serial.println(bluetoothRead);
  
     
     if(bluetoothRead.substring(0, 1).equals("x")){
       
       int i=1;
       while(bluetoothRead.substring(i, i+1) != ("y")){
       i++;
       }
       
       Str_x = bluetoothRead.substring(1, i);
       x = Str_x.toInt();
            
       Str_y = bluetoothRead.substring(i+1, length - 2);
       y = Str_y.toInt();

       Str_p = bluetoothRead.substring(length - 2, length - 1);
       points = Str_p.toInt();

       Str_s = bluetoothRead.substring(length - 1, length);
       s = Str_s.toInt(); 

       i = 1;
 
       Serial.println(x);
       Serial.println(y);
       Serial.println(points);
       Serial.println(s);
       Serial.println(length );        
      
       stop();
       carSpeed = (y*2.5);
       speed_Coeff = (1 + (x/50));

  
    if(points == 1){
    forward();
    }
    if(points == 0){
    stop();
    }
    if(points == 2){
    back(); 
    }
  
    if(points == 3){
    fleft(); 
    }

    if(points == 4){
    fright(); 
    }

    if(points == 5){
     left(); 
    }

    if(points == 6){
    right(); 
    }

    if(points == 7){
     bleft(); 
    }

    if(points == 8){
    bright(); 
    }

    if(points == 9){
    findo(); 
    }
     
  
    
    if (s == 7){
    play_do();
    }

    if (s == 6){
    play_re();
    }

    if (s == 5){
    play_mi();
    }

    if (s == 4){
    play_fa();
    }

    if (s == 3){
    play_sol();
    }

    if (s == 2){
    play_la();
    }

    if (s == 1){
    play_ci();
    }
//When an object is detected the iRobbie App will start sending s = 8 to the Arduino. 
//You can use it in your own Arduino code. The commented lines is an example. 

    if (s == 8){
  //    if (millis() - previousMillis >= DELAY)
  //    {previousMillis += DELAY;
 //     if (forward1)
 //     {
 //       servo.write(-- angle);
 //       if(angle == 0)
 //       forward1 = false;
//      }
 //     else
//      {
 //      servo.write(++ angle);
 //       if (angle == 30)
 //       forward1 = true;
 //     }
 //     }
 
      // scan from 0 to 180 degrees
 // for(angle = 10; angle < 90; angle++)  
 // {                                  
//    servo.write(0);               
//    delay(15);                   
//  } 
//      servo.write(90);

 //    }
 // servo.write(-90);

//    }
     
  // now scan back from 180 to 0 degrees
//  for(angle = 90; angle > 10; angle--)    
 // {                                
 //   servo.write(angle);           
 //   delay(15);       
//  } 
//     servomove(); 
    }

}
}
}

void servomove(){
    unsigned long currentMillis = millis();
 if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
  
   for(angle = 0; angle < 60; angle++)  
  {                                  
    servo.write(angle); 
      previousMillis = currentMillis;              
    delay(10);                   
  } 
  // now scan back from 180 to 0 degrees
 for(angle = 60; angle > 0; angle--)    
  {                                
    servo.write(angle); 
  }
      previousMillis = currentMillis;          
    delay(10);  
}
}


void forward(){ 
  analogWrite(ENA,carSpeed);
  analogWrite(ENB,carSpeed);
  digitalWrite(IN1,LOW);
  digitalWrite(IN2,HIGH);
  digitalWrite(IN3,LOW);
  digitalWrite(IN4,HIGH);
  delay(25);
//  Serial.println("Forward");
}

void forwards(){ 
  analogWrite(ENA,carSpeed);
  analogWrite(ENB,carSpeed);
  digitalWrite(IN1,LOW);
  digitalWrite(IN2,HIGH);
  digitalWrite(IN3,LOW);
  digitalWrite(IN4,HIGH);
  delay(25);
 // Serial.println("Forward_slow");
}

void back(){
  analogWrite(ENA,(carSpeed - 20));
  analogWrite(ENB,(carSpeed - 20));
  digitalWrite(IN1,HIGH);
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,HIGH);
  digitalWrite(IN4,LOW);
  delay(25);
 // Serial.println("Back");
}

void backs(){
  analogWrite(ENA,(carSpeed - 20));
  analogWrite(ENB,(carSpeed - 20));
  digitalWrite(IN1,HIGH);
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,HIGH);
  digitalWrite(IN4,LOW);
  delay(25);
//  Serial.println("Back_slow");
}
void left(){
  analogWrite(ENA,x);
  analogWrite(ENB,x);
  digitalWrite(IN1,LOW);
  digitalWrite(IN2,HIGH);
  digitalWrite(IN3,HIGH);
  digitalWrite(IN4,LOW);
  delay(25); 
//  Serial.println("Left");
}

void right(){
  analogWrite(ENA,x);
  analogWrite(ENB,x);
  digitalWrite(IN1,HIGH);
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,LOW);
  digitalWrite(IN4,HIGH);
  delay(25);
 // Serial.println("Right");
}


void fright(){
  analogWrite(ENA,carSpeed);
  analogWrite(ENB,carSpeed/speed_Coeff);
  digitalWrite(IN1,LOW);
  digitalWrite(IN2,HIGH);
  digitalWrite(IN3,LOW);
  digitalWrite(IN4,HIGH);
  delay(25);
//  Serial.println("Forward_right");
}



void fleft(){
  analogWrite(ENA,carSpeed/speed_Coeff);
  analogWrite(ENB,carSpeed);
  digitalWrite(IN1,LOW);
  digitalWrite(IN2,HIGH);
  digitalWrite(IN3,LOW);
  digitalWrite(IN4,HIGH);
  delay(25);
//  Serial.println("Forward_left");
}

void bright(){
  analogWrite(ENB,carSpeed);
  analogWrite(ENA,carSpeed/speed_Coeff);
  digitalWrite(IN1,HIGH);
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,HIGH);
  digitalWrite(IN4,LOW);
  delay(25);
//  Serial.println("Back_right");
}



void bleft(){
  analogWrite(ENB,carSpeed/speed_Coeff);
  analogWrite(ENA,carSpeed);
  digitalWrite(IN1,HIGH);
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,HIGH);
  digitalWrite(IN4,LOW);
  delay(25);
 // Serial.println("Back_left");
}

void findo(){
  analogWrite(ENA,90);
  analogWrite(ENB,90);
  digitalWrite(IN1,HIGH);
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,LOW);
  digitalWrite(IN4,HIGH);


  delay(25) ;    


 }


void stop(){
  digitalWrite(ENA,LOW);
  digitalWrite(ENB,LOW);
 // Serial.println("Stop!");
}


void play_do(){
  tone(buzzer, 533);
  delay(500);        
  noTone(buzzer);     
}

void play_re(){
  tone(buzzer, 587);
  delay(500);        
  noTone(buzzer); 
}

void play_mi(){
  tone(buzzer, 659);
  delay(500);        
  noTone(buzzer); 
}

void play_fa(){
  tone(buzzer, 698);
  delay(500);        
  noTone(buzzer); 
}

void play_sol(){
  tone(buzzer, 784);
  delay(500);        
  noTone(buzzer); 
}

void play_la(){
  tone(buzzer, 880);
  delay(500);        
  noTone(buzzer); 
}

void play_ci(){
  tone(buzzer, 987);
  delay(500);        
  noTone(buzzer); 
}

На этом всё. В следующих уроках и публикациях мы постараемся более широко осветить тему роботов и робототехники.

26 сентября 2019 в 16:44 | Обновлено 7 ноября 2020 в 01:20 (редакция)
Опубликовано:
Статьи,

Добавить комментарий

Ваш E-mail не будет никому виден. Обязательные поля отмечены *