Перейти к содержанию

Танкер с дифференциальным управлением (PS2+SPI+LCD16202)


Рекомендуемые сообщения

Управление рулевым управлением с помощью параметров X/Y, управление продолжительностью движения автомобиля, скоростью, рулевым управлением с помощью параметров X/Y (здесь с помощью одного рычага ручки PS2); упрощает более распространенный метод настройки дифференциала. I
раньше использовал 328p, его высокая стоимость, компактный размер, функция может быть использована; с 74LS595 для достижения SPI расширенный параллельный интерфейс разработки; первые четыре бита приводят в действие четырехбитный пятипроводной двигатель (турель), последние четыре бита 754410 приводят в действие два щеточных двигателя.
Эта машина добавляет LCD1602 (может также использовать другие LCD) как человеко-машинное общение, удобное дистанционное общение.

#include <PS2X_lib.h> //PS2X
#include <LiquidCrystal.h> //LCD
#include "pitches.h" //pitches

//LCD initial
const int rs = 5, en = 4, d4 = A0, d5 = A1, d6 = A2, d7 = A3;
//const int rs = A2, en = A1, d4 = A3, d5 = A4, d6 = A5, d7 = 5; data may also be simulated instead.
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//74HC595 SPI initial
#define latch pin 12
#define clock pin 11
#define dataPin 10

//speech
const int speaker = 3;
int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4}; // notes in the melody.
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4, 4}; // Note durations: 4 = quarter note, 8 = eighth note, etc.

// PS2 initial
#define PS2_DAT 8 // 2019.10.20 older versions dat, cmd can't use analog pins.
#define PS2_CMD 7     
#define PS2_SEL A5      
#define PS2_CLK A4      

#define motorL_En12 9 //754410 PinEnable,PWMpin
#define motorR_En34 6
int motorDr[]={B0101,B1010,B0000}; //(-+ -+,+-+-,----)/gofront,goback,stop motorCode
                                      //adjustable pin positive and negative configuration, {B1010,B0101,B0000}
int L_EnValue=0, R_EnValue=0;

PS2X ps2x; // Create PS2 controller class

int PS_LX; // PS2 handle left joystick X axis data left joystick to walk
INT PS_LY;               
int PS_RX; // PS2 handle right joystick X-axis data right joystick for turret turret
INT PS_RY; // temporarily empty

integer error = 0; //ps2 connection correct or not to determine the flag
byte type = 0; //ps2x.readType() conversion discriminator flag     
byteVibrate = 0;

int carCoad=0; //car movement mode code  
integer F=0; //car move value
int turn=0; //car turn value
integer T=0; //turning wheel value
int Degree = 1100; //Maximum number of turns  
int StepNumber = 0; //Step motor will not move the number
int old_Degree = 0;

int StepData = 0; //Step motor execution code
int stepCode[] = {8, 12, 4, 6, 2, 3, 1, 9}; //8-step code
int stepCodeIndex=0; //step code-which layer of the motor's current position 0~7

Invalid setting () {  
  lcd.begin(16, 2); // set the number of columns and rows of LCD.
  
  lcd.print("Lx");      
  lcd.setCursor(0,1);
  lcd.print("Rx"). lcd.setCursor(0,1); lcd.print("Rx");  
  lcd.setCursor(8,0);
  lcd.write("Ly");
  lcd.setCursor(8,1);
  lcd.write("Ry");

  pinMode(dataPin,OUTPUT); pinMode(clockPin,OUTPUT); pinMode(latchPin,OUTPUT); //74HC595 pin configuration  
  pinMode(motorL_En12,OUTPUT); pinMode(motorR_En34,OUTPUT); //motor enable pin configuration

  //Tone
   for (int thisNote = 0; thisNote < 8; thisNote++) {
      int noteDuration = 1000 / noteDurations[thisNote];
      Tone (speaker, melody[thisNote], noteDuration).
      int pauseBetweenNotes = noteDuration * 1.30; // To distinguish between notes, set the minimum time between them.   
                                                     // Duration of notes + 30% seems to work well.
      Delay (pauseBetweenNotes).   
      NoTones (3); // Stops playing the tones.
  }

  // Initialize serial communication
  Serial.begin(9600);              
  Delay (50).
  error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT);
}

Invalid loop () {
    integer number = 5.   
    ps2x.read_gamepad(false, vibration); //read the controller and set the big motor to rotate at "vibration" speed
   
    /*if(ps2x.Button(PSB_START)) //start selection
      Serial.println("Start is being held");   
    if(ps2x.Button(PSB_SELECT)) //select selected
      Serial.println("selection is being held"); */

   PS_LX=ps2x.Analog(PSS_LX); //put PS2 joystick X-axis data down PS_LX
   PS_RX=ps2x.Analog(PSS_RX); // pull down PS_RX for PS2 joystick X-axis data
   PS_LY=ps2x.Analog(PSS_LY); //Pull down PS2 joystick Y-axis data to PS_LY
   PS_RY=ps2x.Analog(PSS_RY); //Pull down PS_RY for PS2 joystick Y-axis data

   lcd.setCursor(3,0); //LCD display parameters
   LCD print (PS_LX).
   lcd.setCursor(11,0);
   LCD printing (PS_LY).
   lcd.setCursor(3,1);
   LCD printing (PS_RX).
   lcd.setCursor(11,1);
   LCD printing (PS_RY).
   
/***************** travel control ************************/           
    if(PS_LY<=125){ //wheel enable/motor function function toward configuration                  
      F = map (PS_LY,125,0,90,255); //motor enable value determined
      carCoad = motorDr[0]; //each motor running direction determined goFront
      }
    Otherwise if (PS_LY>=130) {
      F = map (PS_LY,130,255,90,255).     
      carCoad = motorDr[1]; //go back
      }
     else {F=0; carCoad = motorDr[2];} //stop
     // steering affects the perspective of rotation enable            
     if(PS_LX<=125){ //turn left                     
      Turn = Map(PS_LX,125,0,90,40);
      L_EnValue = F * Turn/100; // steering side motor enable value decreases
        if(L_EnValue<30) L_EnValue = 0; //If the enable value is less than a certain value, it is directly defined as 0; pole burn motor.
      R_EnValue = F;     
      }
     else if(PS_LX>=130){ //right turn
      Turn = Map(PS_LX,130,255,90,40);
      L_EnValue = F;
      R_EnValue = F * Turn/100; // steering side motor enable value decreases
         if(R_EnValue<30) R_EnValue = 0; //If the enable value is less than a certain value, it is directly defined as 0; pole burn motor.
      }
    else { // turn = 0;
      L_EnValue = F;
      R_EnValue = F;
      }
                       
  carMove(carCoad,L_EnValue,R_EnValue,StepData); // Call the step subroutine with the resulting parameters.
  
   /***************** turret control ************************/
   { }   
}  
              /************************************************
              Walk subroutine (walk mode, en_L, en_R, Turrent_StepData)
               ************************************************/
void carMove(int carCoad,int L_EnValue,int R_EnValue,int StepData)
{                     
      Byte data bytes.
         digital write (motorL_En12, low); // first close each enPin
         digital write (motorR_En34, low).
         
      DataByte = (StepData<< 4) | license plate; //Byte combination
      //Serial.print(" StepData ");Serial.print(StepData);Serial.print(" carCoad ");Serial.println(carCoad);
      
      digital write (latch pin, low); //data trigger output, turn off latchPin.         
      shiftOut(dataPin, clockPin, MSBFIRST, DataByte); //send byte by byte
      //delay(5);   
      Digital write (latch pin, high); //open latchPin, data output in parallel
      
        Analog write (motor L_En12, L_EnValue).   
        analog write (motor R_En34, R_EnValue).      
}

 

Ссылка на комментарий
Поделиться на другие сайты

Реклама: ООО ТД Промэлектроника, ИНН: 6659197470, Тел: 8 (800) 1000-321

20% скидка на весь каталог электронных компонентов в ТМ Электроникс!

Акция "Лето ближе - цены ниже", успей сделать выгодные покупки!

Плюс весь апрель действует скидка 10% по промокоду APREL24 + 15% кэшбэк и бесплатная доставка!

Перейти на страницу акции

Реклама: ООО ТМ ЭЛЕКТРОНИКС, ИНН: 7806548420, info@tmelectronics.ru, +7(812)4094849

Differential Steering Tanker (PS2+SPI+LCD16202)

Differential control steering, you can use the X / Y parameters (here with a joystick PS2 handle) to control the vehicle forward and backward, speed regulation, steering; simplify the difficulty of manipulation.
I use Promini328p, because it is cost-effective, compact, functional enough; with 74LS595 to achieve SPI extended parallel interface; the first four bits drive a four-phase five-wire stepper motor (turret), the last four bits through 754410 drive two brushed motors. Boot music has not yet progressed to develop applications.
This machine adds LCD1602 as a human-machine dialogue, to facilitate the commissioning stage to detect remote control communication.

Ссылка на комментарий
Поделиться на другие сайты

Выбираем схему BMS для корректной работы литий-железофосфатных (LiFePO4) аккумуляторов

 Обязательным условием долгой и стабильной работы Li-FePO4-аккумуляторов, в том числе и производства EVE Energy, является применение специализированных BMS-микросхем. Литий-железофосфатные АКБ отличаются такими характеристиками, как высокая многократность циклов заряда-разряда, безопасность, возможность быстрой зарядки, устойчивость к буферному режиму работы и приемлемая стоимость. Но для этих АКБ, также как и для других, очень важен контроль процесса заряда и разряда, а специализированных микросхем для этого вида аккумуляторов не так много. Инженеры КОМПЭЛ подготовили список имеющихся микросхем и возможных решений от разных производителей. Подробнее>>

Реклама: АО КОМПЭЛ, ИНН: 7713005406, ОГРН: 1027700032161

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.
Примечание: Ваш пост будет проверен модератором, прежде чем станет видимым.

Гость
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Ответить в этой теме...

×   Вставлено с форматированием.   Восстановить форматирование

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

Загрузка...
  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...