Как использовать протокол I2C с Arduinos - PullRequest
0 голосов
/ 15 октября 2019

Я пытаюсь построить лифт / лифт, используя 3 или более Arduino Uno's и 1 Mega (как мастер).

Arduino Uno (Slave) :

Я подключил ИК-датчик, кнопку, светодиод и 7-сегментный дисплей к Uno.

Если я нажму кнопку, светодиод загорится и будет работать до тех пор, пока ИК-датчик не обнаружит клетку лифта. ,Затем светодиод погаснет, и на 7-сегментном дисплее появится номер этажа.

Arduino Mega (Master) :

Мастер используется для шагового двигателяи клавиатура.

Мастер должен спросить рабов (в данном случае Uno) о том, нажата кнопка или нет.

Пример сценария :

Клетка находится на 2 этаже и обнаружена ИК-датчиком. Если я нажму кнопку на втором этаже, Мега должен знать, что клетка уже есть. И если я нажму кнопку на 3-м этаже, Мега должен знать, что клетка находится на 2-м этаже, и что кнопка на 3-м этаже нажата, и она должна управлять двигателем, чтобы поднять клетку на 3-й этаж и показать на 7-сегментном дисплее.

Я должен использовать i2c.

Извините, если трудно понять текст. Мой английский не очень хороший.

Вот код рабов:

#include<arduino.h>

const int dataPin = 11;  //  wire to 74HC595 pin 11
const int latchPin = 8; //  to 74HC595 pin 8
const int clockPin = 12; //  to 74HC595 pin 12

int nummers[6] = {126, 12, 182, 158, 204, 204}; //0, 1, 2, 3, 4, 5

int buttonvalue = 0;
int button = 2;
int buttonLed = 3;

// ir  sensor and irleds
int irLedGreen = 5;
int irLedRed = 6;
#define IR 4
int detect = 0;

void setup() {
    Serial.begin(9600);   

    //ir sensor
    pinMode(irLedGreen, OUTPUT);
    pinMode(IR, INPUT);
    pinMode(irLedRed, OUTPUT);

    //shift out
    pinMode(dataPin, OUTPUT);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);

    //button
    pinMode(button, INPUT);
    pinMode(buttonLed, OUTPUT);
}

void loop(){

    buttonvalue = digitalRead(button);
    detect = digitalRead(IR);

    // ir sensor led. It will be green if it detects something else it will be red.
    if (detect == LOW) { // if if detects something do the following.
        digitalWrite(irLedGreen, HIGH);
        digitalWrite(irLedRed, LOW);
    } else {
        digitalWrite(irLedGreen, LOW);
        digitalWrite(irLedRed, HIGH);
    }

    // button is pressed
    if (buttonvalue != 0 ) { 
        digitalWrite(buttonLed, HIGH);
        Serial.println("button");
    } else if (detect == LOW) {
        digitalWrite(buttonLed, LOW);

        digitalWrite(latchPin, LOW); // prepare shift register for data
        shiftOut(dataPin, clockPin, MSBFIRST, nummers[4]); // send data
        digitalWrite(latchPin, HIGH); // update display

        Serial.println("obstakel");
    }

    digitalWrite(latchPin, LOW); // prepare shift register for data
    shiftOut(dataPin, clockPin, MSBFIRST, nummers[0]); // send data 
    digitalWrite(latchPin, HIGH); // update display
}

1 Ответ

0 голосов
/ 15 октября 2019

Откройте любой веб-поиск. Введите "arduino i2c"

Нажмите первую ссылку

https://www.arduino.cc/en/Reference/Wire

Прочитайте текст. В разделе «Примеры» найдите

Главный читатель / ведомый писатель: запрограммируйте две платы Arduino для связи друг с другом в конфигурации главного считывателя / ведомого отправителя через I2C.

Откройте ссылку

https://www.arduino.cc/en/Tutorial/MasterReader

Прочитайте текст.

Загрузите пример кода в ваши arduinos

Master

// Wire Master Reader
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Reads data from an I2C/TWI slave device
// Refer to the "Wire Slave Sender" example for use with this

// Created 29 March 2006

// This example code is in the public domain.


#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 6);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print(c);         // print the character
  }

  delay(500);
}

Раб

// Wire Slave Sender
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Sends data as an I2C/TWI slave device
// Refer to the "Wire Master Reader" example for use with this

// Created 29 March 2006

// This example code is in the public domain.


#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop() {
  delay(100);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write("hello "); // respond with message of 6 bytes
  // as expected by master
}

Разберитесь с кодом, поиграйте с ним. Затем примените полученные знания к своему проекту.

...