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
en:arduino_module_base_lesson [2020/01/20 16:15]
golikov
en:arduino_module_base_lesson [2020/01/20 16:26]
golikov
Line 140: Line 140:
     switch (msg.id){//​Process in a particular manner depending on message 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 149: 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 164: 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 172: 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 185: 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 210: Line 210:
 </​file>​ </​file>​
  
-====Код для ​Arduino====+====Arduino ​Code====
  
 <file c ArduinoLightSensor_1_Ard.ino>​ <file c ArduinoLightSensor_1_Ard.ino>​
Line 216: 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); // пSend the contents of the data variable to the OCC
         break;         break;
       }       }
Line 254: Line 254:
    
 uint16_t Sensor_data(void){ uint16_t Sensor_data(void){
-  uint16_t data = analogRead(data_pin);​ //Считываем показания освещенности с датчика+  uint16_t data = analogRead(data_pin);​ //Read illuminance values from the sensor
   return data;   return data;
 } }
    
 /* /*
- ​* ​Следующий блок кода необходимо всегда добавлять в конец программы + ​* ​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() {
en/arduino_module_base_lesson.txt · Last modified: 2020/03/25 16:28 (external edit)