Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: IOTON-API QEI USBDevice mbed-ton ton-bot
Fork of ton-bot_seguidor_linha by
Diff: main.cpp
- Revision:
- 1:584ac95c4061
- Parent:
- 0:52cc151dc505
- Child:
- 2:027fe033f5f7
diff -r 52cc151dc505 -r 584ac95c4061 main.cpp
--- a/main.cpp Thu Jun 29 20:37:24 2017 +0000
+++ b/main.cpp Thu Jun 29 20:59:25 2017 +0000
@@ -1,205 +1,151 @@
-// Includes --------------------------------------------------------------------
-#include "Ioton.h"
-
-// Defines ---------------------------------------------------------------------
-#define MY_SSID "mySSID" // Enter router ssid inside the quotes
-#define MY_PASS "myPASS" // Enter router password inside the quotes
-#define MY_API_KEY "myAPIKEY" // Enter ThingSpeak API KEY of channel
-
-
-// Private variables -----------------------------------------------------------
-PwmOut pwm(PIN13); // PWM output
-DigitalOut out(PIN14); // Digital output
-AnalogIn ain(PIN15); // Analog input
-DigitalIn in(PIN16); // Digital input
-
-InterruptIn button(SW_USER); // USER button - interrupt mode
-int userCount = 0; // USER button counter
-
-char bufferRxBluetooth[20]; // Buffer of Bluetooth commands
-volatile uint8_t bufferCountRxBluetooth = 0; // Index counter - Blutooth buffer
-volatile bool flagCmdBluetooth = false; // Indicates new Bluetooth command received
-
-char* replyHttp; // Buffer of reply http get method
-uint8_t countThingSpeak = 0; // Auxiliar counter - ThingSpeak
-
-Ticker imuTick; // IMU Tick Timer
+/**
+******************************************************************************
+* @file main.cpp
+* @author Kleber Lima da Silva (kleber@ioton.cc)
+* @version V0.0.1
+* @date 19-Junho-2017
+* @brief Programa para testes do hardware do Robô TON-BOT.
+******************************************************************************
+* @attention
+*
+* COPYRIGHT(c) 2017 IOTON Technology
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+******************************************************************************
+*/
-
-// *****************************************************************************
-// Private functions ***********************************************************
-// *****************************************************************************
-// Runs the AHRS algorithm - Rate: 0.1 s - 10 Hz -------------------------------
-// AHRS provide: roll, pitch and yaw
-void imuCallback(void)
-{
-// imu.runAHRS(0.1); // ### FIX: BUG TICKER
-} // end of imuCallback
-
+/* Includes ------------------------------------------------------------------*/
+#include "main.h"
-// Called everytime a new character goes into the RX buffer --------------------
-void bluetoothRxCallback(void)
-{
- bufferRxBluetooth[bufferCountRxBluetooth] = bluetooth.getc();
- bufferCountRxBluetooth++;
+/** @addtogroup Teste TON-BOT
+ * @{
+ */
- if (bluetooth.readable() == 0) flagCmdBluetooth = true;
-} // end of bluetoothRxCallback
-
-
-// USER button interrupt callback ----------------------------------------------
-void userCallback(void)
-{
- userCount++;
-} // end of userCallback
+/* Variáveis privadas --------------------------------------------------------*/
+Ticker imuTick; /* Timer para o algoritmo da IMU */
+Timer t1; /* Timer auxiliar */
-// Parse the Bluetooth commands ------------------------------------------------
-// COMMAND | DESCRIPTION
-// -----------------------------------------------------------------------------
-// #PWM:float | Update pwm output. Ex: #PWM:0.5
-// #OUT:int | Update digital output. Ex: #OUT:1
-// #RGB:rgbcode | Update LED RGB color. Ex: #RGB:00AFEF
-// #AIN? | Return analog input
-// #DIN? | Return digital input
-// #BAT? | Return battery voltage
-// #IMU? | Return imu data (roll, pitch and yaw)
-// #ALL? | Return all values
-void parseCmdBluetooth(char* str)
+/* Funções Privadas ----------------------------------------------------------*/
+
+/**
+ * @brief Callback para execução do Algoritmo AHRS com taxa de 10 Hz
+ * @note O algoritmo AHRS calcula os ângulos: roll, pitch and yaw
+ * @param Nenhum
+ * @retval Nenhum
+ */
+void imuCallback(void)
+{
+// imu.runAHRS(0.1); // ### FIX: TICKER com bug nesta versao do mbed
+} // fim da imuCallback
+
+/**
+ * @brief Programa Principal
+ * @param Nenhum
+ * @retval Nenhum
+ */
+int main(void)
{
- if (strncmp("#PWM:", str, 5) == 0)
- {
- pwm = strtof(str + 5, NULL);
- }
- else if (strncmp("#OUT:", str, 5) == 0)
- {
- out = atoi(str + 5);
- }
- else if (strncmp("#RGB:", str, 5) == 0)
- {
- ton.setLED(str + 5);
- }
- else if (strncmp("#AIN?", str, 5) == 0)
- {
- bluetooth.printf("#AIN:%0.2f\r\n", ain.read());
- }
- else if (strncmp("#DIN?", str, 5) == 0)
- {
- bluetooth.printf("#DIN:%d\r\n", in.read());
- }
- else if (strncmp("#BAT?", str, 5) == 0)
- {
- bluetooth.printf("#BAT:%0.2fV\r\n", ton.getBattery());
- }
- else if (strncmp("#IMU?", str, 5) == 0)
- {
- bluetooth.printf("pitch: %0.2f\r\nroll: %0.2f\r\nyaw: %0.2f\r\n",
- imu.getPitch(), imu.getRoll(), imu.getYaw());
- }
- else if (strncmp("#ALL?", str, 5) == 0)
- {
- bluetooth.printf("#AIN:%0.2f\r\n#DIN:%d\r\n#BAT:%0.2fV\r\n",
- ain.read(), in.read(), ton.getBattery());
+ float lf = 0, l = 0, r = 0, rf = 0;
+
+ /* Ligue o TON com o botão USER pressionado para indicar o estado da bateria */
+ if (ton.USERisPressed())
+ {
+ /* Necessário pressionar o botão RESET voltar ao modo normal */
+ ton.batteryStatus();
+ }
+
+ /* Inicialização dos periféricos */
+ ton.setLED(BLUE);
+ initTonBot();
+ ton.setLED(RED);
+ ton.enableBluetooth();
+ ton.enableIMU(); /* Deixe o robô parado durante a inicialização (~5s) */
+
+ /* Configura o Timer da IMU - intervalo = 0.1 segundos */
+ imuTick.attach(&imuCallback, 0.1);
+
+ /* Inicio do programa ------------------------------------------------------*/
+ usb.printf("Programa TESTE - TON-BOT!\r\n");
+ ton.setLED(WHITE);
+ wait(1);
+ ton.setLED(NONE);
+ beeps(3, 100, 50);
+
+ resetEncoderEsquerda();
+ resetEncoderDireita();
- bluetooth.printf("pitch: %0.2f\r\nroll: %0.2f\r\nyaw: %0.2f\r\n",
- imu.getPitch(), imu.getRoll(), imu.getYaw());
- }
- else
- {
- bluetooth.printf("Invalid command!\r\n");
- }
-} // end of parseCmdBluetooth function
+ /* LOOP principal ----------------------------------------------------------*/
+ while (1)
+ {
+ /* Zera e inicia o timer para estabelecer a base de tempo */
+ t1.reset();
+ t1.start();
+
+ /* Envia mensagens de estados dos periféricos a cada 1s para a USB */
+ usb.printf("Sensores de Linha (erro): %d\r\n", getSensoresLinha());
+ usb.printf("\r\n");
+
+ usb.printf("Sensores de Paredes: %d\r\n", getSensoresParede(&lf, &l, &r, &rf));
+ usb.printf("%0.3f | %0.3f | %0.3f | %0.3f\r\n", lf, l, r, rf);
+ usb.printf("\r\n");
+
+ usb.printf("IMU - Algoritmo AHRS:\r\n");
+ usb.printf("pitch: %0.3f\r\n", imu.getPitch());
+ usb.printf("roll: %0.3f\r\n", imu.getRoll());
+ usb.printf("yaw: %0.3f\r\n", imu.getYaw());
+ usb.printf("\r\n");
+
+ usb.printf("Bateria: %0.3fV\r\n", ton.getBattery());
+ usb.printf("\r\n");
+
+ usb.printf("Encoders: %d | %d\r\n", getEncoderEsquerda(), getEncoderDireita());
+ usb.printf("\r\n");
+
+ usb.printf("---\r\n");
-// Data format: #rgbcode,float,int | Ex: #00AFEF,0.5,1 ------------------------
-void parseCmdWifi(char* str)
-{
- char* tmp = strstr(str, "#"); // Search the first character of the command
-
- if (tmp != NULL)
- {
- tmp = strtok(tmp, ",\n");
- ton.setLED(tmp + 1); // Remove the '#' and update LED RGB color
-
- tmp = strtok(NULL,",\n");
- pwm = strtof(tmp, NULL); // Convert to float and update pwm output
-
- tmp = strtok(NULL,",\n");
- out = atoi(tmp); // Convert to int and update digital output
- }
-} // end of parseCmdWifi function
+ /* Caso queira direcionar alguma mensagem para o Bluetooth, basta..
+ * mudar de 'usb.' para 'bluetooth.' - como o exemplo a seguir: */
+ bluetooth.printf("%0.3f | %0.3f | %0.3f | %0.3f\r\n", lf, l, r, rf);
-// *****************************************************************************
-// MAIN PROGRAM ****************************************************************
-// *****************************************************************************
-int main(void)
-{
- // Initializations
- ton.setLED(RED);
- ton.enableBluetooth();
- ton.enableWifi();
- ton.enableIMU(); // Leave standing the TON board at initialization (~5s)
- ton.setLED(BLUE);
-
- // Configure Tick Timer for IMU reads - interval (0.1 second)
- imuTick.attach(&imuCallback, 0.1);
-
- // Configure RX interrupt of Bluetooth
- bluetooth.attach(&bluetoothRxCallback, Serial::RxIrq);
-
- // Try to connect to the access point
- if (wifi.connect(MY_SSID, MY_PASS) == true) ton.setLED(GREEN);
- else ton.setLED(YELLOW);
-
- // Configure USER button interrupt
- button.rise(&userCallback);
-
- // The main LOOP -----------------------------------------------------------
- while (1)
+ /* Se o botão for pressionado: liga os motores por 1 segundo
+ * .. ou aguarda 1 segundo sem fazer nada */
+ while (t1.read_ms() < 1000)
{
- // Prints messages to the USB ------------------------------------------
- usb.printf("pitch: %0.3f\r\n", imu.getPitch());
- usb.printf("roll: %0.3f\r\n", imu.getRoll());
- usb.printf("yaw: %0.3f\r\n", imu.getYaw());
- usb.printf("---\r\n");
- usb.printf("battery: %0.3fV\r\n", ton.getBattery());
- usb.printf("count: %d\r\n", userCount);
- usb.printf("\r\n");
+ if (ton.USERisPressed())
+ {
+ ton.setLED(YELLOW);
+ beep(100);
+ setMotores(0.2, -0.2); /* CUIDADO COM VELOCIDADES ALTAS (~ 2.0 m/s) */
+ wait(1);
+ setMotores(0, 0);
+ ton.setLED(NONE);
+ }
+ }
- // Checks new Blutooth commands ----------------------------------------
- if (flagCmdBluetooth == true)
- {
- // Parse the Bluetooth commands
- parseCmdBluetooth(bufferRxBluetooth);
- bufferCountRxBluetooth = 0;
- memset(bufferRxBluetooth, 0, sizeof(bufferRxBluetooth));
- flagCmdBluetooth = false;
- } // end of check new Bluetooth commands
+ /* Pisca o LED verde */
+ ton.toggleLED(GREEN);
- // Checks if wifi is connected and run wifi tasks ----------------------
- if (wifi.isConnected() == true)
- {
- // Parse the http get method
- replyHttp = wifi.httpGet("ioton.cc", "/ton-demo.txt");
- parseCmdWifi(replyHttp);
+ } // fim do loop principal
+} // fim da função principal
- // Send data via ThingSpeak (does not support high rates)
- if (++countThingSpeak == 5)
- {
- char thingspeak[50];
-
- sprintf(thingspeak, "field1=%0.3f&field2=%d&field3=%0.3f",
- ain.read(), in.read(), ton.getBattery());
- usb.printf("Send to ThingSpeak: %s\r\n", thingspeak);
- wifi.sendThingSpeak(thingspeak, MY_API_KEY);
+/**
+ * @}
+ */
- countThingSpeak = 0;
- } // end of send to ThingSpeak
- } // end of wifi tasks
-
- wait(1);
- } // end of main LOOP
-} // end of main function
+/************************ (C) COPYRIGHT IOTON Technology **********************/
+/***********************************END OF FILE********************************/