User Tools

Site Tools


en:arduino_module_base_lesson

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Next revision Both sides next revision
en:arduino_module_base_lesson [2020/01/20 16:07]
golikov
en:arduino_module_base_lesson [2020/01/20 16:24]
golikov
Line 92: Line 92:
   
  /*   /* 
-Передадим команду на выполнение команды с идентификатором ​на Arduino, используя встроенную функцию ​arduino_send +Transfer a command for executing command ID to Arduino ​using the arduino_send ​built-in function 
-Первый аргумент - номер ​Arduino (по умолчанию ​0) +The first argument is the Arduino ​ID (defaults to 0) 
-        * Второй аргумент - идентификатор сообщения ​(в данном случае ​1) +        * The second argument is message ID (1 in our case
-        * Третий аргумент - передаваемые данные ​(в данном случае ​NULL - данных для передачи нет+        * The third argument is the data being transferred ​(NULL as we don’t have any data to send
-        * Четвертый аргумент - буфер для получаемых данных  ​(в данном случае ​NULL - ответ не ждем+        * The fourth argument is the buffer to receive data (NULL as we don’t expect a response
-        * Пятый аргумент - время ожидания ответа от Arduino (в данном случае ​100 мс, но по сути это число роли тут не играет,​ так ответа не ждем)+        * The fifth argument is the time to wait for a response from Arduino (100 ms in this case but it matters little in this case as we aren’t waiting for any response)
  */  */
-  ​ 
  
  arduino_send(0,​ 1, NULL, NULL, 100);  arduino_send(0,​ 1, NULL, NULL, 100);
Line 106: Line 105:
 </​file>​ </​file>​
  
-====Код для ​Arduino====+====Arduino ​Code====
  
-Нашей задачей является включить по команде с [[http://​orbicraft.sputnix.ru/​doku.php?​id=pc_subsys|бортового компьютера]] встроенный светодиод на секунды и выключить егоДля этого мы должны получить посылку с идентификатором от бортового компьютера и выполнить соответствующую команду - вызвать функцию по работе со светодиодом.+Our task is to turn on the built-in LED for seconds by sending a command from the orbiter computer and then turn it offIn order to accomplish that we must receive a packet containing an ID from the orbiter computer and execute the respective command by calling the LED control function.
  
 <note tip> <note tip>
-Не забудьте предварительно ​[[https://​www.arduino.cc/​en/​guide/​libraries|установить]] в Arduino IDE библиотеку для взаимодействия Arduino и бортового компьютераБиблиотека находится в разделе [[http://​orbicraft.sputnix.ru/​doku.php?​id=software|необходимое ПО]].+To enable interaction between Arduino and orbiter computer, be sure to [[https://​www.arduino.cc/​en/​guide/​libraries|install]] an interoperability library in Arduino IDE firstThe library can be found in the Required Software section.
 </​note>​ </​note>​
  
 <file c ArduinoTestLed_1_Ard.ino>​ <file c ArduinoTestLed_1_Ard.ino>​
-#include <​OrbicraftBus.h>​ // подключаем библиотеку для работы с конструктором ОрбиКрафт+#include <​OrbicraftBus.h>​ // Import the Orbicraft Construction Set control library
  
 /* /*
-  * Объявим переменную ​msg как тип данных ​Message +  * Declare the msg variable as the Message ​data type 
-  * Message ​- представляет собой структуру,​ содержащую идентификаторы и данные передаваемого сообщения+  * Message ​comprises a structure that contains IDs and transferred message content
 */ */
 Message msg; Message msg;
  
 /* /*
-  * Объявим переменную ​bus как тип данных ​OrbicraftBus  +  * Declare the bus variable as the OrbicraftBus ​data type  
-  * OrbicraftBus ​- представляет собой класс, описывающий взаимодействие ​Arduino ​и шины конструктора ​Orbicraft+  * OrbicraftBus ​is a class describing interaction between ​Arduino ​and Orbicraft ​construction set bus
 */ */
 OrbicraftBus bus; OrbicraftBus bus;
  
-// Объявим переменную ​msgSize, в которую будет записываться размер принятого сообщения+// Declare the msgSize ​variable to hold the size of the received message
 uint16_t msgSize = 0; uint16_t msgSize = 0;
  
 void setup() { void setup() {
-  Serial1.begin(9600);​ // задаем скорость обмена информацией по Serial1 ​!!! (проверить ​Serial2.begin(9600))+  Serial1.begin(9600);​ // Define data transfer rate over Serial1 (Check Serial2.begin(9600))
 } }
  
 void loop() { void loop() {
-  msgSize = bus.takeMessage(msg);​ // пробуем прочитать сообщение с помощью метода ​takeMessage +  msgSize = bus.takeMessage(msg);​ // Try to read the message using the takeMessage ​method 
-  if (msgSize > 0){ //если сообщение есть +  if (msgSize > 0){ //If there is a message… 
-    switch (msg.id){//в зависимости от идентификатора сообщения выполняем те или иные действия+    switch (msg.id){//Process in a particular manner depending on message ID
  
-      // Рассмотрим случай с идентификатором ​1+      // Consider the case with ID 1
         case 0x01:         case 0x01:
-          turnOnLed();​ // Вызов функции для включения и выключения светодиода+          turnOnLed();​ // Call the function for turning the LED on and off
           break;           break;
     }              }         
Line 150: Line 149:
  
 void turnOnLed(void){ void turnOnLed(void){
-  digitalWrite(LED_BUILTIN,​ HIGH); //Включаем встроенный светодиод +  digitalWrite(LED_BUILTIN,​ HIGH); //Turn on the built-in LED 
-  delay(3000);​ //Ждем ​секунды +  delay(3000);​ //Wait seconds 
-  digitalWrite (LED_BUILTIN,​ LOW); //Выключаем встроенный светодиод+  digitalWrite (LED_BUILTIN,​ LOW); //Turn off the built-in LED
 } }
  
 /* /*
- ​* ​Следующий блок кода необходимо всегда добавлять в конец программы + ​* ​The following block of code must always be appended to the program. 
- ​* ​Функция вызывается автоматически и необходима для обработки сообщения+ ​* ​The function is called automatically and is necessary for message processing.
 */  */ 
 void serialEvent2() { void serialEvent2() {
Line 165: Line 164:
  
  
-=====Получение данных от Arduino=====+=====Retrieving Data from Arduino=====
  
-Получение данных от Arduino ​к БКУ осуществляется с помощью той же функции на стороне БКУ:+Data from Arduino ​is received by the OCC using the same function on the OCC side:
  
 <code c> <code c>
Line 173: Line 172:
 </​code>​ </​code>​
  
-Суть работы та же, что и при передаче команда с БКУ на Arduino. ​Используются для работы лишь другие аргументы функции //arduino_send// и соответственно нужно еще сформировать данные для передачи на стороне ​Arduino. ​Для примера будем принимать значения с фоторезистора ​(датчик освещенности), подключенного к пину **A0** Arduino. ​Примеры кода с пояснениями представлены ниже.+It works in the same manner as when transferring commands from OCC to Arduino. ​The only difference is that arduino_send ​takes other arguments and the respective data to be sent will have to be generated on the Arduino ​sideFor our example we will receive the data from the photoresistive cell (the illuminance sensorconnected to the pin A0 on Arduino. ​Commented code examples follow.
  
 <note important>​ <note important>​
-Прежде чем подключать фоторезистор к Arduino, посмотрите как это правильно делаетсяФоторезистор может быть использован в виде отдельного элемента с необходимой периферией,​ а может быть в виде готового модуля с готовой обвязкой.+Before you connect the photoresistive cell to Arduino ​take some time to see how to do it properlyThe photoresistive cell can be used as a separate component in combination with requisite peripherals or in the form of off-the-shelf module shipped with all necessary accessories.
 </​note>​ </​note>​
  
-====Код для бортового компьютера====+====Orbiter-Side Code====
  
 <file c ArduinoTestLightSensor_1_Orbi.c>​ <file c ArduinoTestLightSensor_1_Orbi.c>​
Line 186: Line 185:
  void control(void)  void control(void)
  {  {
- char answer[255];​ // Создаем массив для сохранения ответа + char answer[255];​ // Create an array to hold the response 
- int32_t count = 5; // Устанавливаем счетчик на шагов+ int32_t count = 5; // Set the counter for steps
 /*  /* 
-Передадим команду на получение ответа с идентификатором ​на Arduino, используя встроенную функцию ​arduino_send +Transfer a command for receiving the response with ID to Arduino ​using the arduino_send ​built-in function 
-Первый аргумент - номер ​Arduino (по умолчанию ​0) +The first argument is the Arduino ​ID (defaults to 0) 
-        * Второй аргумент - идентификатор сообщения ​(в данном случае ​2) +        * The second argument is message ID (2 in our case
-        * Третий аргумент - передаваемые данные ​(в данном случае ​NULL - данных для передачи нет+        * The third argument is the data being transferred ​(NULL as we don’t have any data to send
-        * Четвертый аргумент - буфер для получаемых данных  ​(в данном случае ​answer ​- массив для сохранения полученных данных+        * The fourth argument is the buffer to receive data (in our case it is the array named answer ​for incoming data
-Пятый аргумент - время ожидания ответа от Arduino ​в мс (в данном случае ​100 мс+The fifth argument is the time, in milliseconds,​ to wait for a response from Arduino (100 ms in our case). 
- */+*/
  while (count > 0){  while (count > 0){
  int status = arduino_send(0,​ 2, NULL, answer, 100);  int status = arduino_send(0,​ 2, NULL, answer, 100);
Line 211: Line 210:
 </​file>​ </​file>​
  
-====Код для ​Arduino====+====Arduino ​Code====
  
 <file c ArduinoLightSensor_1_Ard.ino>​ <file c ArduinoLightSensor_1_Ard.ino>​
Line 217: Line 216:
  
 /* /*
-  * Объявим переменную ​msg как тип данных ​Message +  * Declare the msg variable as the Message ​data type 
-  * Message ​- представляет собой структуру,​ описывающую идентификаторы передаваемого сообщения+  * Message ​comprises a structure that that describes the identifiers of the message being transferred
 */ */
 Message msg; Message msg;
    
 /* /*
-  * Объявим переменную ​bus как тип данных ​OrbicraftBus  +  * Declare the bus variable as the OrbicraftBus ​data type  
-  * OrbicraftBus ​- представляет собой класс, описывающий взаимодействие ​Arduino ​и шины конструктора ​Orbicraft+  * OrbicraftBus ​is a class describing interaction between ​Arduino ​and Orbicraft ​construction set bus
 */ */
 OrbicraftBus bus; OrbicraftBus bus;
    
-// Объявим переменную ​msgSize, в которую будет записываться передаваемое сообщение+// Declare the msgSize ​variable to hold the message being transferred
 int16_t msgSize = 0; int16_t msgSize = 0;
-// Объявим номер пина для считывания показаний +// Declare the pin number to sense readings 
-int data_pin = A0; // Указываем пин, с которого будем считывать показания датчика+int data_pin = A0; // These pin will be used for readouts from the sensor
    
 void setup() { void setup() {
-  Serial1.begin(9600);​ // задаем скорость обмена информацией по Serial1 ​!!! (проверить ​Serial2.begin(9600))+  Serial1.begin(9600);​ // Define data transfer rate over Serial1 (Check Serial2.begin(9600))
 } }
    
 void loop() { void loop() {
  
-  msgSize = bus.takeMessage(msg);​ // пробуем прочитать сообщение с помощью метода ​takeMessage+  msgSize = bus.takeMessage(msg);​ // Try to read the message using the takeMessage ​method
   ​   ​
-  if (msgSize > 0){ //если сообщение есть +  if (msgSize > 0){ //If there is a message… 
-    switch (msg.id){//в зависимости от идентификатора сообщения выполняем те или иные действия+    switch (msg.id){//Process in a particular manner depending on message ID
    
-      // Рассмотрим случай с идентификатором ​2+      // Consider the case with ID 2
         case 0x02:{         case 0x02:{
-        String data = String(Sensor_data());​ // записываем показания,​ полученные от функции ​Sensor_data() ​в переменную ​data+        String data = String(Sensor_data());​ // Store readings obtained from Sensor_data() ​in the data variable
         bus.sendMessage(bus.obcAddress,​ 0, data); // передаем содержимое переменной data на БКУ         bus.sendMessage(bus.obcAddress,​ 0, data); // передаем содержимое переменной data на БКУ
         break;         break;
en/arduino_module_base_lesson.txt · Last modified: 2020/03/25 16:28 (external edit)