Check system settings error or timeout ардуино

I got similar error with #3 , but mine when I tried to send settings command to the module The message written can be seen in screenshot provided I developed the code in Windows, but tried to send ...

@miqbal23

I got similar error with #3 , but mine when I tried to send settings command to the module

The message written can be seen in screenshot provided

5292a154-fbaf-4c79-8df3-c60436083674

I developed the code in Windows, but tried to send this command from my Ubuntu PC. The code worked well in Windows.

Could it be a problem on me changing PC or the problem in module?

@wilson-elechouse

@miqbal23

I see. Thanks for the reply

I also noticed on your documents about certain VR3 feature :

Recognize maximum 7 voice commands at same time

Does it mean that if I give several commands at the same time, the module will be able to recognize each of them up to 7 different commands?

@wilson-elechouse

@miqbal23

Thank you.

I also looking for some hardware specifications, like datasheets. Do you have that available for this device?

@safari2

Please add a comment, that if you use MEGA2560, you should change ping to 10,11 (2,3 don’t maintain SoftwareSerial MEGA 2560);
// 2:RX 3:TX, you can choose your favorite pins
its not correct phrase, because not all pins on AVR processors maintains interrupts, needs for RX!!!

@trychaga

Hie
I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the connections as outlined at the start of the VR3 tutorial and change serial pins to 0&1 on the serial monitor i get the error : Check system settings or timeout
also on my recognizer i only see one led light for power is coming on, is it a hardware problem since i soldered the vr3 pins on my own or its a software problem?
if i try a different command it says Command unrecognized
May you help

@wilson-elechouse

if you use MEGA2560, you should change ping to 10,11

2017-04-10 14:43 GMT+08:00 trychaga <notifications@github.com>:

Hie
I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the
connections as outlined at the start of the VR3 tutorial and change serial
pins to 0&1 on the serial monitor i get the error : *Check system
settings or timeout*
also on my recognizer i only see one led light for power is coming on, is
it a hardware problem since i soldered the vr3 pins on my own or its a
software problem?
if i try a different command it says Command unrecognized
May you help


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#4 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AEPYDDlSfpMGecsxEvCL8gvnZ0lyeGgWks5ruc-MgaJpZM4JkPvM>
.

@trychaga

Dear Wilson
Thank you very much i managed to configure the module after changing the
ping to (10,11) and a managed to record my voice as well.
However i still have a small challenge I’m designing a security system
using this system and i like the response rate and recognition rate of this
module but two in three test users seem to share the same voice signature
which i do not like because there wont b any security at all.
How can I go about this? Is it that I have to record and train using high
pitch always or is it about how i train it. Where i am missing it is how
many times should i train my voice to this module before it begins to
recognize me and only me. Please help.
My other question and comeback is i wish to provide an audio feedback or
acknowledgement when the signature s correct and how can i achieve this
using the VR3.1 module if i do not want to interface the Funduino Mega 2560
with an SD Can i access the pre-recorded voice recordings from the VR3
group and achieve playback? If so how can i achieve this?
Regards

On Mon, Apr 10, 2017 at 10:19 AM, wilson-elechouse ***@***.*** > wrote:
[image: Boxbe] <https://www.boxbe.com/overview> This message is eligible
for Automatic Cleanup! ***@***.***) Add cleanup rule
<https://www.boxbe.com/popup?url=https%3A%2F%2Fwww.boxbe.com%2Fcleanup%3Fkey%3DyqsQeu9BiEg49KOBzeuDqSmrsOlyloWvWExKdSLw8W8%253D%26token%3DyZonL8JuiJZhJGQ4Wlm4NuCYvheLq16ox1UEtbaa94WMZDVYBnZvHTZ7mVQ5131OxAgMq3XrCMX90tRg49ERafTe8XzW8RvzpKE6ybIRUVpnf5TuuriLtPUpq%252F2XfBdcSq%252Flq11tmsSde1IvBz%252Ft8g%253D%253D&tc_serial=29738523661&tc_rand=673730014&utm_source=stf&utm_medium=email&utm_campaign=ANNO_CLEANUP_ADD&utm_content=001>
| More info
<http://blog.boxbe.com/general/boxbe-automatic-cleanup?tc_serial=29738523661&tc_rand=673730014&utm_source=stf&utm_medium=email&utm_campaign=ANNO_CLEANUP_ADD&utm_content=001>

if you use MEGA2560, you should change ping to 10,11

2017-04-10 14:43 GMT+08:00 trychaga ***@***.***>:

> Hie
> I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the
> connections as outlined at the start of the VR3 tutorial and change
serial
> pins to 0&1 on the serial monitor i get the error : *Check system
> settings or timeout*
> also on my recognizer i only see one led light for power is coming on, is
> it a hardware problem since i soldered the vr3 pins on my own or its a
> software problem?
> if i try a different command it says Command unrecognized
> May you help
>
> —
> You are receiving this because you commented.
> Reply to this email directly, view it on GitHub
> <#4#
issuecomment-292862923>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/
AEPYDDlSfpMGecsxEvCL8gvnZ0lyeGgWks5ruc-MgaJpZM4JkPvM>
> .
>


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#4 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AM_oqETmU0g_YcuMiHVPbkgLlw50kSlHks5rueYDgaJpZM4JkPvM>
.

@htorus

Hi! I’m using Arduino Mega 2560 R3. The cable connection is correct but I’m facing this problem. I can not record sound. How can I solve this problem?

@shinny1711

hi,
i connected voice module v3 with arduino mega such as
vcc-5v
gnd-gnd
tx-10
rx-11
when i connected usb cable to arduino then light in the arduino is not glowing.
but when i disconnect either vcc or gnd pin from voice module then the light is glowing but the light in the voice module is not glowing in any way. why???
does my my voice module v3 is working or not???
how to know whether it is working or not?

@mzyada

hi everyone, when I try my vr3 it stopped working! I don’t know what happened, anyone has an idea or solution?? plz help me.

@hamzi7860

Please add a comment, that if you use MEGA2560, you should change ping to 10,11 (2,3 don’t maintain SoftwareSerial MEGA 2560);
// 2:RX 3:TX, you can choose your favorite pins
its not correct phrase, because not all pins on AVR processors maintains interrupts, needs for RX!!!

I’m Using AT-Mega2560 and pins 10,11 are working for me, Thank You

@hamzi7860

if you use MEGA2560, you should change ping to 10,11 2017-04-10 14:43 GMT+08:00 trychaga notifications@github.com:

Hie I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the connections as outlined at the start of the VR3 tutorial and change serial pins to 0&1 on the serial monitor i get the error : Check system settings or timeout also on my recognizer i only see one led light for power is coming on, is it a hardware problem since i soldered the vr3 pins on my own or its a software problem? if i try a different command it says Command unrecognized May you help — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#4 (comment)>, or mute the thread https://github.com/notifications/unsubscribe-auth/AEPYDDlSfpMGecsxEvCL8gvnZ0lyeGgWks5ruc-MgaJpZM4JkPvM .

Yes you are right , Thanks it worked for me :)

@AKQ8

hi,
im using Arduino Uno and Geeetech Voice Recognition, and i use the «train» sample from the libraray and try to type settings or any other command i get the following error.
Screen Shot 2020-03-20 at 2 00 37 AM

@hamzi7860

hey! can you please mention about pins you are using for TXD and RXD on arduino uno. You are getting this error because your pin configuration is not correct.

@AKQ8

hey! can you please mention about pins you are using for TXD and RXD on arduino uno. You are getting this error because your pin configuration is not correct.

TXD -> 2
RXD -> 3
GND -> GND
VCC -> 5V

@hamzi7860

use this pin configuration without doing any change in code. just change wires of module. your module will start working.
TXD -> 3
RXD -> 2
GND -> GND
VCC -> 5V

@AKQ8

still getting error, with the changes you provided above.

@hamzi7860

then please attach a screenshot of code (which lines include pins configuration)

@AKQ8

im using the example «train» from the library

@hamzi7860

check your connections and pin configuration again and play with RXD and TXD pins by replacing their positionsposition with 2 or 3. It will gona work.

@AKQ8

still getting same error, but when i configure the following, commands dont respond to the monitor
TXD->0
RXD->1

@hamzi7860

if you are using arduino uno. use only 2 and 3 pins of arduino for TXD and RXD in code but replace their positions on hardware only.

@AKQ8

still getting the error even with pins 2 and 3.

@AKQ8

if anyone got the fix for this issue please help out :)

@Charisavena97

@AKQ8 I have the same problem, did anyone find the solution?

@AKQ8

unfortunately still, the issue occurs and no one has given/found a solution

@Charisavena97

@Devi1136

hii, im using Arduino Nano board. Facing the same problem. Every mentioned command in the serial monitor is failed or timed out. I tried both the connections 1) Rx : 2 , TX : 3 ( Recommended by the Sampletrain program by VR3 lib) …2) RX : 2 , TX : 1 (Built in Pins of arduino nano ) . Still the commands fails…… And one more thing the led on voice recognition module is always on….not blinking as i see in the tutorials in youtube about VR3. Please Help…

@taf2

@Devi1136 i found that for arduino uno board at least I had to reverse in the code 2 and 3 until it works. So what I did is wire 2 and 3 to the board’s RX and TX. Then in software I reversed the

VR myVR(3,2);    // 2:RX 3:TX, you can choose your favourite pins.

and now it works great.

@Aswini2414

@taf2 I checked in the way u told above, but still i am getting the error

@IslamEmran

@pumpkinandknife

Did u try uploading the code? That worked for us and we found that a lot of ppl we know didnt do this. :3

Skip to main content

Forum for Electronics

Forum for Electronics

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals… and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

  • Digital Design and Embedded Programming

  • Microcontrollers

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

[AVR] check system settings error or timeout in arduino


  • Thread starter

    aameer


  • Start date

    Jan 20, 2015

Status
Not open for further replies.
Status
Not open for further replies.

Similar threads

  • Digital Design and Embedded Programming

  • Microcontrollers

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

miqbal23 opened this issue 6 years ago · comments

I got similar error with #3 , but mine when I tried to send settings command to the module

The message written can be seen in screenshot provided

5292a154-fbaf-4c79-8df3-c60436083674

I developed the code in Windows, but tried to send this command from my Ubuntu PC. The code worked well in Windows.

Could it be a problem on me changing PC or the problem in module?

I see. Thanks for the reply

I also noticed on your documents about certain VR3 feature :

Recognize maximum 7 voice commands at same time

Does it mean that if I give several commands at the same time, the module will be able to recognize each of them up to 7 different commands?

Thank you.

I also looking for some hardware specifications, like datasheets. Do you have that available for this device?

Please add a comment, that if you use MEGA2560, you should change ping to 10,11 (2,3 don’t maintain SoftwareSerial MEGA 2560);
// 2:RX 3:TX, you can choose your favorite pins
its not correct phrase, because not all pins on AVR processors maintains interrupts, needs for RX!!!

Hie
I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the connections as outlined at the start of the VR3 tutorial and change serial pins to 0&1 on the serial monitor i get the error : Check system settings or timeout
also on my recognizer i only see one led light for power is coming on, is it a hardware problem since i soldered the vr3 pins on my own or its a software problem?
if i try a different command it says Command unrecognized
May you help

if you use MEGA2560, you should change ping to 10,11

2017-04-10 14:43 GMT+08:00 trychaga <notifications@github.com>:

Hie
I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the
connections as outlined at the start of the VR3 tutorial and change serial
pins to 0&1 on the serial monitor i get the error : *Check system
settings or timeout*
also on my recognizer i only see one led light for power is coming on, is
it a hardware problem since i soldered the vr3 pins on my own or its a
software problem?
if i try a different command it says Command unrecognized
May you help


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#4 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AEPYDDlSfpMGecsxEvCL8gvnZ0lyeGgWks5ruc-MgaJpZM4JkPvM>
.

Dear Wilson
Thank you very much i managed to configure the module after changing the
ping to (10,11) and a managed to record my voice as well.
However i still have a small challenge I’m designing a security system
using this system and i like the response rate and recognition rate of this
module but two in three test users seem to share the same voice signature
which i do not like because there wont b any security at all.
How can I go about this? Is it that I have to record and train using high
pitch always or is it about how i train it. Where i am missing it is how
many times should i train my voice to this module before it begins to
recognize me and only me. Please help.
My other question and comeback is i wish to provide an audio feedback or
acknowledgement when the signature s correct and how can i achieve this
using the VR3.1 module if i do not want to interface the Funduino Mega 2560
with an SD Can i access the pre-recorded voice recordings from the VR3
group and achieve playback? If so how can i achieve this?
Regards

On Mon, Apr 10, 2017 at 10:19 AM, wilson-elechouse ***@***.*** > wrote:
[image: Boxbe] <https://www.boxbe.com/overview> This message is eligible
for Automatic Cleanup! ***@***.***) Add cleanup rule
<https://www.boxbe.com/popup?url=https%3A%2F%2Fwww.boxbe.com%2Fcleanup%3Fkey%3DyqsQeu9BiEg49KOBzeuDqSmrsOlyloWvWExKdSLw8W8%253D%26token%3DyZonL8JuiJZhJGQ4Wlm4NuCYvheLq16ox1UEtbaa94WMZDVYBnZvHTZ7mVQ5131OxAgMq3XrCMX90tRg49ERafTe8XzW8RvzpKE6ybIRUVpnf5TuuriLtPUpq%252F2XfBdcSq%252Flq11tmsSde1IvBz%252Ft8g%253D%253D&tc_serial=29738523661&tc_rand=673730014&utm_source=stf&utm_medium=email&utm_campaign=ANNO_CLEANUP_ADD&utm_content=001>
| More info
<http://blog.boxbe.com/general/boxbe-automatic-cleanup?tc_serial=29738523661&tc_rand=673730014&utm_source=stf&utm_medium=email&utm_campaign=ANNO_CLEANUP_ADD&utm_content=001>

if you use MEGA2560, you should change ping to 10,11

2017-04-10 14:43 GMT+08:00 trychaga ***@***.***>:

> Hie
> I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the
> connections as outlined at the start of the VR3 tutorial and change
serial
> pins to 0&1 on the serial monitor i get the error : *Check system
> settings or timeout*
> also on my recognizer i only see one led light for power is coming on, is
> it a hardware problem since i soldered the vr3 pins on my own or its a
> software problem?
> if i try a different command it says Command unrecognized
> May you help
>
> —
> You are receiving this because you commented.
> Reply to this email directly, view it on GitHub
> <#4#
issuecomment-292862923>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/
AEPYDDlSfpMGecsxEvCL8gvnZ0lyeGgWks5ruc-MgaJpZM4JkPvM>
> .
>


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#4 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AM_oqETmU0g_YcuMiHVPbkgLlw50kSlHks5rueYDgaJpZM4JkPvM>
.

Hi! I’m using Arduino Mega 2560 R3. The cable connection is correct but I’m facing this problem. I can not record sound. How can I solve this problem?

hi,
i connected voice module v3 with arduino mega such as
vcc-5v
gnd-gnd
tx-10
rx-11
when i connected usb cable to arduino then light in the arduino is not glowing.
but when i disconnect either vcc or gnd pin from voice module then the light is glowing but the light in the voice module is not glowing in any way. why???
does my my voice module v3 is working or not???
how to know whether it is working or not?

hi everyone, when I try my vr3 it stopped working! I don’t know what happened, anyone has an idea or solution?? plz help me.

Please add a comment, that if you use MEGA2560, you should change ping to 10,11 (2,3 don’t maintain SoftwareSerial MEGA 2560);
// 2:RX 3:TX, you can choose your favorite pins
its not correct phrase, because not all pins on AVR processors maintains interrupts, needs for RX!!!

I’m Using AT-Mega2560 and pins 10,11 are working for me, Thank You

if you use MEGA2560, you should change ping to 10,11 2017-04-10 14:43 GMT+08:00 trychaga notifications@github.com:

Hie I am using Funduino Mega 2560(Atmega 2560) and VR3 it seems when i do the connections as outlined at the start of the VR3 tutorial and change serial pins to 0&1 on the serial monitor i get the error : Check system settings or timeout also on my recognizer i only see one led light for power is coming on, is it a hardware problem since i soldered the vr3 pins on my own or its a software problem? if i try a different command it says Command unrecognized May you help — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#4 (comment)>, or mute the thread https://github.com/notifications/unsubscribe-auth/AEPYDDlSfpMGecsxEvCL8gvnZ0lyeGgWks5ruc-MgaJpZM4JkPvM .

Yes you are right , Thanks it worked for me :)

hi,
im using Arduino Uno and Geeetech Voice Recognition, and i use the «train» sample from the libraray and try to type settings or any other command i get the following error.
Screen Shot 2020-03-20 at 2 00 37 AM

hey! can you please mention about pins you are using for TXD and RXD on arduino uno. You are getting this error because your pin configuration is not correct.

hey! can you please mention about pins you are using for TXD and RXD on arduino uno. You are getting this error because your pin configuration is not correct.

TXD -> 2
RXD -> 3
GND -> GND
VCC -> 5V

use this pin configuration without doing any change in code. just change wires of module. your module will start working.
TXD -> 3
RXD -> 2
GND -> GND
VCC -> 5V

still getting error, with the changes you provided above.

then please attach a screenshot of code (which lines include pins configuration)

im using the example «train» from the library

check your connections and pin configuration again and play with RXD and TXD pins by replacing their positionsposition with 2 or 3. It will gona work.

still getting same error, but when i configure the following, commands dont respond to the monitor
TXD->0
RXD->1

if you are using arduino uno. use only 2 and 3 pins of arduino for TXD and RXD in code but replace their positions on hardware only.

still getting the error even with pins 2 and 3.

if anyone got the fix for this issue please help out :)

@AKQ8 I have the same problem, did anyone find the solution?

unfortunately still, the issue occurs and no one has given/found a solution

@Charisavena97

hii, im using Arduino Nano board. Facing the same problem. Every mentioned command in the serial monitor is failed or timed out. I tried both the connections 1) Rx : 2 , TX : 3 ( Recommended by the Sampletrain program by VR3 lib) …2) RX : 2 , TX : 1 (Built in Pins of arduino nano ) . Still the commands fails…… And one more thing the led on voice recognition module is always on….not blinking as i see in the tutorials in youtube about VR3. Please Help…

@Devi1136 i found that for arduino uno board at least I had to reverse in the code 2 and 3 until it works. So what I did is wire 2 and 3 to the board’s RX and TX. Then in software I reversed the

VR myVR(3,2);    // 2:RX 3:TX, you can choose your favourite pins.

and now it works great.

@taf2 I checked in the way u told above, but still i am getting the error

Did u try uploading the code? That worked for us and we found that a lot of ppl we know didnt do this. :3

The library VoiceRecognitionV3-master.zip definitly doesn’t work for me. there was no way to get my module working with this library.

So I got working the module using accessPort (plus «CP102» connector) and the sketch by planetleak in https://www.instructables.com/Arduino-voice-control/

First of all you need to set the correct configuration in access port:
• Baud rate: 9600
• Parity bit: None
• Data bit: 8
• Stop bit: 1
• Send format: Hex
• Receive format: Char

then give the following command:
AA 33
AA 36

The first command set baud rate to 96000
!!!The last command is important because it set the response of the module in a format comprehensible for human!!!

Then recording your voice for 5 command in group 1:
AA 11
1)white
2)red
3)green
4)blu
5)off

Then give the comman AA 24 to see if the group is correctly memorized

Then you prepare Arduino with all connection to RGB led and to the vocal recognition module

You compile the skecth by planetleak and try it

I hope this is useful to someone, I have lost a lot of time tying the module working with the library VoiceRecognitionV3-master.zip and at the end the only way to use the module was with accessport and native command

голосовое управление умным домом

В этой статье я опишу процесс распознавания речи системой MajorDoMo на моей малинке.  Сейчас я оне пользуюсь этим механизмом, т.к. распознование, даже через комнату, лучше реализовано с помощью интеграции в систему умного дома яндекс станции Алиса, а именно модуля YandexHome. Подробнее можете узнать на офф. сайте MajorDoMo. Кто не в курсе о MajorDoMo читайте здесь и о моей конфигурации здесь .

Итак, общая схема физических устройств:

1  этап

Произносит ключевое слово – «Анжелика»

V3 Module распознает и ардуино передает сигнал на wi fi модуль Wemos D1 Mini, который шлет http запрос серверу («http://192.168.0.101/objects/?script=commandRPI») MajorDoMo на запуск сценария включения микрофона на raspberry Pi и записи с последующим распознованием с помощью сервиса Google Speech API

2  этап

Произносит команду – «Включи музыку»

Raspberry Pi включает микрофон и делает 10 секундную запись команды и шлет этот файл на распознование гуглу и полученный ответ вставляет в GET запрос, который выполняет скрипт с поиском шаблона системы MajorDoMo по сказанной команде (подробнее о моих шаблонах здесь).  

Имеем три устройства (ардуино , Wemos D1 Mini, raspberry Pi) которые программируются следующим образом:

    1. В ардуино заливаем скетч. В мониторе порта ардуино набираем train 0 и записываем ключевое слово (не используемое в обычной речи). Набираем train 1 и т.д. — повторяем это слово с разных расстояний (до 5 раз). Записываем в память V3  модуля (load 0 1 2 3 4)
/**
 ******************************************************************************
 * @file    vr_sample_train.ino
 * @author  JiapengLi
 * @brief   This file provides a demostration on 
 * how to train VoiceRecognitionModule to record your voice
 ******************************************************************************
 * @note:
 * Use serial command to control VoiceRecognitionModule. '
 * All commands are case insensitive. Default serial baud rate 115200.
 * 
 * COMMAND        FORMAT                        EXAMPLE                    Comment
 * 
 * train          train (r0) (r1)...            train 0 2 45               Train records
 * load           load (r0) (r1) ...            load 0 51 2 3              Load records
 * clear          clear                         clear                      remove all records in  Recognizer
 * record         record / record (r0) (r1)...  record / record 0 79       Check record train status
 * vr             vr                            vr                         Check recognizer status
 * getsig         getsig (r)                    getsig 0                   Get signature of record (r)
 * sigtrain       sigtrain (r) (sig)            sigtrain 0 ZERO            Train one record(r) with signature(sig)
 * settings       settings                      settings                   Check current system settings
 ******************************************************************************
 * @section  HISTORY
 * 
 * 2013/06/13    Initial version.
 */
#include 
#include "VoiceRecognitionV3.h"

/**        
 * Connection
 * Arduino    VoiceRecognitionModule
 * 2   ------->     TX
 * 3   ------->     RX
 */
VR myVR(2,3);    // 2:RX 3:TX, you can choose your favourite pins.

/***************************************************************************/
/** declare print functions */
void printSeperator();
void printSignature(uint8_t *buf, int len);
void printVR(uint8_t *buf);
void printLoad(uint8_t *buf, uint8_t len);
void printTrain(uint8_t *buf, uint8_t len);
void printCheckRecognizer(uint8_t *buf);
void printUserGroup(uint8_t *buf, int len);
void printCheckRecord(uint8_t *buf, int num);
void printCheckRecordAll(uint8_t *buf, int num);
void printSigTrain(uint8_t *buf, uint8_t len);
void printSystemSettings(uint8_t *buf, int len);
void printHelp(void);

/***************************************************************************/
// command analyze part
#define CMD_BUF_LEN      64+1
#define CMD_NUM     10
typedef int (*cmd_function_t)(int, int);
uint8_t cmd[CMD_BUF_LEN];
uint8_t cmd_cnt;
uint8_t *paraAddr;
int receiveCMD();
int checkCMD(int len);
int checkParaNum(int len);
int findPara(int len, int paraNum, uint8_t **addr);
int compareCMD(uint8_t *para1 , uint8_t *para2, int len);

int cmdTrain(int len, int paraNum);
int cmdLoad(int len, int paraNum);
int cmdTest(int len, int paraNum);
int cmdVR(int len, int paraNum);
int cmdClear(int len, int paraNum);
int cmdRecord(int len, int paraNum);
int cmdSigTrain(int len, int paraNum);
int cmdGetSig(int len, int paraNum);
int cmdSettings(int len, int paraNum);
int cmdHelp(int len, int paraNum);
/** cmdList, cmdLen, cmdFunction has correspondence */
const char cmdList[CMD_NUM][10] = {  // command list table
  {
    "train"  }
  ,
  {
    "load"  }
  , 
  {
    "clear"  }
  ,
  {
    "vr"  }
  ,
  {
    "record"  }
  ,
  {
    "sigtrain"  }
  ,
  {
    "getsig"  }
  ,
  {
    "Settings"  }
  ,
  {
    "test"  }
  ,
  {
    "help"  }
  ,
};
const char cmdLen[CMD_NUM]= {    // command length
  5,  //  {"train"},
  4,  //  {"load"}, 
  5,  //  {"clear"},
  2,  //  {"vr"},
  6,  //  {"record"},
  8,  //  {"sigtrain"},
  6,  //  {"getsig"},
  8,  //  {"Settings"},
  4,  //  {"test"},
  4,  //  {"help"}
};
cmd_function_t cmdFunction[CMD_NUM]={      // command handle fuction(function pointer table)
  cmdTrain,
  cmdLoad,
  cmdClear,
  cmdVR,
  cmdRecord,
  cmdSigTrain,
  cmdGetSig,
  cmdSettings,
  cmdTest,
  cmdHelp,
};

/***************************************************************************/
/** temprory data */
uint8_t buf[255];
uint8_t records[7]; // save record

// my code
const int ledPin =  13;
const boolean buttonPin = false;
#define one   (1)

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

  /** initialize */
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
  Serial.println(F("Elechouse Voice Recognition V3 Module "train" sample."));

  printSeperator();
  Serial.println(F("Usage:"));
  printSeperator();
  printHelp();
  printSeperator();
  cmd_cnt = 0;
}

void loop(void)
{
  int len, paraNum, paraLen, i;

  /** receive Serial command */
  len = receiveCMD();
  if(len>0){
    /** check if the received command is valid */
    if(!checkCMD(len)){

      /** check parameter number of the received command  */
      paraNum = checkParaNum(len);

      /** display the receved command back */
      Serial.write(cmd, len);

      /** find the first parameter */
      paraLen = findPara(len, 1, &paraAddr);

      /** compare the received command with command in the list */
      for(i=0; i<CMD_NUM; i++){
        /** compare command length */
        if(paraLen == cmdLen[i]){
          /** compare command content */
          if( compareCMD(paraAddr, (uint8_t *)cmdList[i], paraLen) == 0 ){
            /** call command function */
            if( cmdFunction[i](len, paraNum) != 0){
              printSeperator();
              Serial.println(F("Command Format Error!"));
              printSeperator();
            }
            break;
          }
        }
      }

      /** command is not supported*/
      if(i == CMD_NUM){ 
        printSeperator();
        Serial.println(F("Unkonwn command"));
        printSeperator();
      }
    }
    else{
      /** received command is invalid */
      printSeperator();
      Serial.println(F("Command format error"));
      printSeperator();
    }
  }

  /** try to receive recognize result */
  int ret;
  ret = myVR.recognize(buf, 50);
  if(ret>0){
    /** voice recognized, print result */

    switch(buf[1]){
      case 0:
        /** turn on LED */
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
        Serial.println("Motion detected1!");
        break;
        case 1:
        /** turn on LED */
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
        Serial.println("Motion detected1!");
        break;
        case 2:
        /** turn on LED */
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
        Serial.println("Motion detected1!");
        break;
        case 3:
        /** turn on LED */
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
        Serial.println("Motion detected1!");
        break;
   
             
      default:
        Serial.println("Record function undefined");
        break;
    }
    printVR(buf);
  }
}

/**
 * @brief   receive command from Serial.
 * @param   NONE.
 * @retval  command length, if no command receive return -1.
 */
int receiveCMD()
{
  int ret;
  int len;
  unsigned long start_millis;
  start_millis = millis();
  while(1){
    ret = Serial.read();
    if(ret>0){
      start_millis = millis();
      cmd[cmd_cnt] = ret;
      if(cmd[cmd_cnt] == 'n'){
        len = cmd_cnt+1;
        cmd_cnt = 0;
        return len;
      }
      cmd_cnt++;
      if(cmd_cnt == CMD_BUF_LEN){
        cmd_cnt = 0;
        return -1;
      }
    }

    if(millis() - start_millis > 100){
      cmd_cnt = 0;
      return -1;
    }
  }
}

/**
 * @brief   compare two commands, case insensitive.
 * @param   para1  -->  command buffer 1
 * para2  -->  command buffer 2
 * len    -->  buffer length
 * @retval  0  --> equal
 * -1  --> unequal
 */
int compareCMD(uint8_t *para1 , uint8_t *para2, int len)
{
  int i;
  uint8_t res;
  for(i=0; i<len; i++){
    res = para2[i] - para1[i];
    if(res != 0 && res != 0x20){
      res = para1[i] - para2[i];
      if(res != 0 && res != 0x20){
        return -1;
      }
    }
  }
  return 0;
}

/**
 * @brief   Check command format.
 * @param   len  -->  command length
 * @retval  0  -->  command is valid
 * -1  -->  command is invalid
 */
int checkCMD(int len)
{
  int i;
  for(i=0; i<len; i++){
    if(cmd[i] > 0x1F && cmd[i] < 0x7F){

    }
    else if(cmd[i] == 't' || cmd[i] == ' ' || cmd[i] == 'r' || cmd[i] == 'n'){

    }
    else{
      return -1;
    }
  }
  return 0;
}

/**
 * @brief   Check the number of parameters in the command
 * @param   len  -->  command length
 * @retval  number of parameters
 */
int checkParaNum(int len)
{
  int cnt=0, i;
  for(i=0; i<len; ){
    if(cmd[i]!='t' && cmd[i]!=' ' && cmd[i] != 'r' && cmd[i] != 'n'){
      cnt++;
      while(cmd[i] != 't' && cmd[i] != ' ' && cmd[i] != 'r' && cmd[i] != 'n'){
        i++;
      }
    }
    i++;
  }
  return cnt;
}

/**
 * @brief   Find the specified parameter.
 * @param   len       -->  command length
 * paraIndex -->  parameter index
 * addr      -->  return value. position of the parameter
 * @retval  length of specified parameter
 */
int findPara(int len, int paraIndex, uint8_t **addr)
{
  int cnt=0, i, paraLen;
  uint8_t dt;
  for(i=0; i<len; ){
    dt = cmd[i];
    if(dt!='t' && dt!=' '){
      cnt++;
      if(paraIndex == cnt){
        *addr = cmd+i;
        paraLen = 0;
        while(cmd[i] != 't' && cmd[i] != ' ' && cmd[i] != 'r' && cmd[i] != 'n'){
          i++;
          paraLen++;
        }
        return paraLen;
      }
      else{
        while(cmd[i] != 't' && cmd[i] != ' ' && cmd[i] != 'r' && cmd[i] != 'n'){
          i++;
        }
      }
    }
    else{
      i++;
    }
  }
  return -1;
}

int cmdHelp(int len, int paraNum)
{
  if(paraNum != 1){
    return -1;
  }
  printSeperator();
  printHelp();
  printSeperator();
  return 0;
}

/**
 * @brief   Handle "train" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdTrain(int len, int paraNum)
{
  int i, ret;
  if(paraNum < 2 || paraNum > 8 ){
    return -1;
  }

  for(i=2; i<=paraNum; i++){
    findPara(len, i, &paraAddr);
    records[i-2] = atoi((char *)paraAddr);
    if(records[i-2] == 0 && *paraAddr != '0'){
      return -1;
    }
  }
  printSeperator();
  ret = myVR.train(records, paraNum-1, buf);
  //  ret = myVR.train(records, paraNum-1);
  if(ret >= 0){
    printTrain(buf, ret);
  }
  else if(ret == -1){
    Serial.println(F("Train failed."));
  }
  else if(ret == -2){
    Serial.println(F("Train Timeout."));
  }
  printSeperator();
  return 0;
}

/**
 * @brief   Handle "load" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdLoad(int len, int paraNum)
{
  int i, ret;
  if(paraNum < 2 || paraNum > 8 ){
    return -1;
  }

  for(i=2; i<=paraNum; i++){
    findPara(len, i, &paraAddr);
    records[i-2] = atoi((char *)paraAddr);
    if(records[i-2] == 0 && *paraAddr != '0'){
      return -1;
    }
  }
  //  myVR.writehex(records, paraNum-1);
  ret = myVR.load(records, paraNum-1, buf);
  printSeperator();
  if(ret >= 0){
    printLoad(buf, ret);
  }
  else{
    Serial.println(F("Load failed or timeout."));
  }
  printSeperator();
  return 0;
}

/**
 * @brief   Handle "clear" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdClear(int len, int paraNum)
{
  if(paraNum != 1){
    return -1;
  }
  if(myVR.clear() == 0){
    printSeperator();
    Serial.println(F("Recognizer cleared."));
    printSeperator();
  }
  else{
    printSeperator();
    Serial.println(F("Clear recognizer failed or timeout."));
    printSeperator();
  }
  return 0;
}

/**
 * @brief   Handle "vr" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdVR(int len, int paraNum)
{
  int ret;
  if(paraNum != 1){
    return -1;
  }
  ret = myVR.checkRecognizer(buf);
  if(ret<=0){
    printSeperator();
    Serial.println(F("Check recognizer failed or timeout."));
    printSeperator();
    return 0;
  }
  printSeperator();
  printCheckRecognizer(buf);
  printSeperator();
  return 0;
}

/**
 * @brief   Handle "record" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdRecord(int len, int paraNum)
{
  int ret;
  if(paraNum == 1){
    ret = myVR.checkRecord(buf);
    printSeperator();
    if(ret>=0){
      printCheckRecordAll(buf, ret);
    }
    else{
      Serial.println(F("Check record failed or timeout."));
    }
    printSeperator();
  }
  else if(paraNum < 9){
    for(int i=2; i<=paraNum; i++){
      findPara(len, i, &paraAddr);
      records[i-2] = atoi((char *)paraAddr);
      if(records[i-2] == 0 && *paraAddr != '0'){
        return -1;
      }      
    }

    ret = myVR.checkRecord(buf, records, paraNum-1);    // auto clean duplicate records
    printSeperator();
    if(ret>=0){
      printCheckRecord(buf, ret);
    }
    else{
      Serial.println(F("Check record failed or timeout."));
    }
    printSeperator();
  }
  else{
    return -1;
  }
  return 0;
}

/**
 * @brief   Handle "sigtrain" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdSigTrain(int len, int paraNum)
{
  int ret, sig_len;
  uint8_t *lastAddr;
  if(paraNum < 2){
    return -1;
  }

  findPara(len, 2, &paraAddr);
  records[0] = atoi((char *)paraAddr);
  if(records[0] == 0 && *paraAddr != '0'){
    return -1;
  }

  findPara(len, 3, &paraAddr);
  sig_len = findPara(len, paraNum, &lastAddr);
  sig_len +=( (unsigned int)lastAddr - (unsigned int)paraAddr );

  printSeperator();
  ret = myVR.trainWithSignature(records[0], paraAddr, sig_len, buf);
  //  ret = myVR.trainWithSignature(records, paraNum-1);
  if(ret >= 0){
    printSigTrain(buf, ret);
  }
  else{
    Serial.println(F("Train with signature failed or timeout."));
  }
  printSeperator();

  return 0;
}

/**
 * @brief   Handle "getsig" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdGetSig(int len, int paraNum)
{
  int ret;
  if(paraNum != 2){
    return -1;
  }

  findPara(len, 2, &paraAddr);
  records[0] = atoi((char *)paraAddr);
  if(records[0] == 0 && *paraAddr != '0'){
    return -1;
  }

  ret = myVR.checkSignature(records[0], buf);

  printSeperator();
  if(ret == 0){
    Serial.println(F("Signature isn't set."));
  }
  else if(ret > 0){
    Serial.print(F("Signature:"));
    printSignature(buf, ret);
    Serial.println();
  }
  else{
    Serial.println(F("Get sig error or timeout."));
  }
  printSeperator();

  return 0;
}

/**
 * @brief   Handle "test" command
 * @param   len     --> command length
 * paraNum --> number of parameters
 * @retval  0 --> success
 * -1 --> Command format error
 */
int cmdTest(int len, int paraNum)
{
  printSeperator();
  Serial.println(F("TEST is not supported."));
  printSeperator();
  return 0;
}

int cmdSettings(int len, int paraNum)
{
  int ret;
  if(paraNum != 1){
    return -1;
  }
  ret = myVR.checkSystemSettings(buf);
  if( ret > 0){
    printSeperator();
    printSystemSettings(buf, ret);
    printSeperator();
  }
  else{
    printSeperator();
    Serial.println(F("Check system settings error or timeout"));
    printSeperator();
  }
  return 0;
}

/*****************************************************************************/
/**
 * @brief   Print signature, if the character is invisible, 
 * print hexible value instead.
 * @param   buf     --> command length
 * len     --> number of parameters
 */
void printSignature(uint8_t *buf, int len)
{
  int i;
  for(i=0; i<len; i++){
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    }
    else{
      Serial.print(F("["));
      Serial.print(buf[i], HEX);
      Serial.print(F("]"));
    }
  }
}

/**
 * @brief   Print signature, if the character is invisible, 
 * print hexible value instead.
 * @param   buf  -->  VR module return value when voice is recognized.
 * buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
 * buf[1]  -->  number of record which is recognized. 
 * buf[2]  -->  Recognizer index(position) value of the recognized record.
 * buf[3]  -->  Signature length
 * buf[4]~buf[n] --> Signature
 */
void printVR(uint8_t *buf)
{
  Serial.println(F("VR IndextGrouptRecordNumtSignature"));

  Serial.print(buf[2], DEC);
  Serial.print(F("tt"));

  if(buf[0] == 0xFF){
    Serial.print(F("NONE"));
  }
  else if(buf[0]&0x80){
    Serial.print(F("UG "));
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print(F("SG "));
    Serial.print(buf[0], DEC);
  }
  Serial.print(F("t"));

  Serial.print(buf[1], DEC);
  Serial.print(F("tt"));
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print(F("NONE"));
  }
  Serial.println(F("rn"));
}

/**
 * @brief   Print seperator. Print 80 '-'.
 */
void printSeperator()
{
  for(int i=0; i<80; i++){
    Serial.write('-');
  }
  Serial.println();
}

/**
 * @brief   Print recoginizer status.
 * @param   buf  -->  VR module return value when voice is recognized.
 * buf[0]     -->  Number of valid voice records in recognizer
 * buf[i+1]   -->  Record number.(0xFF: Not loaded(Nongroup mode), or not set (Group mode)) (i= 0, 1, ... 6)
 * buf[8]     -->  Number of all voice records in recognizer
 * buf[9]     -->  Valid records position indicate.
 * buf[10]    -->  Group mode indicate(FF: None Group, 0x8n: User, 0x0n:System)
 */
void printCheckRecognizer(uint8_t *buf)
{
  Serial.print(F("All voice records in recognizer: "));
  Serial.println(buf[8], DEC);
  Serial.print(F("Valid voice records in recognizer: "));
  Serial.println(buf[0], DEC);
  if(buf[10] == 0xFF){
    Serial.println(F("VR is not in group mode."));
  }
  else if(buf[10]&0x80){
    Serial.print(F("VR is in user group mode:"));
    Serial.println(buf[10]&0x7F, DEC);
  }
  else{
    Serial.print(F("VR is in system group mode:"));
    Serial.println(buf[10], DEC);
  }
  Serial.println(F("VR IndextRecordttComment"));
  for(int i=0; i<7; i++){
    Serial.print(i, DEC);
    Serial.print(F("tt"));
    if(buf[i+1] == 0xFF){
      if(buf[10] == 0xFF){
        Serial.print(F("UnloadedtNONE"));
      }
      else{
        Serial.print(F("Not SetttNONE"));
      }
    }
    else{
      Serial.print(buf[i+1], DEC);
      Serial.print(F("tt"));
      if(buf[9]&(1<<i)){
        Serial.print(F("Valid"));
      }
      else{
        Serial.print(F("Untrained"));
      }
    }

    Serial.println();
  } 
}

/**
 * @brief   Print record train status.
 * @param   buf  -->  Check record command return value
 * buf[0]     -->  Number of checked records
 * buf[2i+1]  -->  Record number.
 * buf[2i+2]  -->  Record train status. (00: untrained, 01: trained, FF: record value out of range)
 * (i = 0 ~ buf[0]-1 )
 * num  -->  Number of trained records
 */
void printCheckRecord(uint8_t *buf, int num)
{
  Serial.print(F("Check "));
  Serial.print(buf[0], DEC);
  Serial.println(F(" records."));

  Serial.print(num, DEC);
  if(num>1){
    Serial.println(F(" records trained."));
  }
  else{
    Serial.println(F(" record trained."));
  }

  for(int i=0; i<buf[0]*2; i += 2){
    Serial.print(buf[i+1], DEC);
    Serial.print(F("t-->t"));
    switch(buf[i+2]){
    case 0x01:
      Serial.print(F("Trained"));
      break;
    case 0x00:
      Serial.print(F("Untrained"));
      break;
    case 0xFF:
      Serial.print(F("Record value out of range"));
      break;
    default:
      Serial.print(F("Unknown Stauts"));
      break;
    }
    Serial.println();
  }
}

/**
 * @brief   Print record train status.
 * @param   buf  -->  Check record command return value
 * buf[0]     -->  Number of checked records
 * buf[2i+1]  -->  Record number.
 * buf[2i+2]  -->  Record train status. (00: untrained, 01: trained, FF: record value out of range)
 * (i = 0 ~ buf[0]-1 )
 * num  -->  Number of trained records
 */
void printCheckRecordAll(uint8_t *buf, int num)
{
  Serial.print(F("Check 255"));
  Serial.println(F(" records."));

  Serial.print(num, DEC);
  if(num>1){
    Serial.println(F(" records trained."));
  }
  else{
    Serial.println(F(" record trained."));
  }
  myVR.writehex(buf, 255);
  for(int i=0; i<255; i++){
    if(buf[i] == 0xF0){
      continue;
    }
    Serial.print(i, DEC);
    Serial.print(F("t-->t"));
    switch(buf[i]){
    case 0x01:
      Serial.print(F("Trained"));
      break;
    case 0x00:
      Serial.print(F("Untrained"));
      break;
    case 0xFF:
      Serial.print(F("Record value out of range"));
      break;
    default:
      Serial.print(F("Unknown Stauts"));
      break;
    }
    Serial.println();
  }
}

/**
 * @brief   Print check user group result.
 * @param   buf  -->  Check record command return value
 * buf[8i]    -->  group number.
 * buf[8i+1]  -->  group position 0 status.
 * buf[8i+2]  -->  group position 1 status.
 * ...                ...
 * buf[8i+6]  -->  group position 5 status.
 * buf[8i+7]  -->  group position 6 status.
 * (i = 0 ~ len)
 * len  -->  number of checked groups
 */
void printUserGroup(uint8_t *buf, int len)
{
  int i, j;
  Serial.println(F("Check User Group:"));
  for(i=0; i<len; i++){
    Serial.print(F("Group:"));
    Serial.println(buf[8*i]);
    for(j=0; j<7; j++){
      if(buf[8*i+1+j] == 0xFF){
        Serial.print(F("NONEt"));
      }
      else{
        Serial.print(buf[8*i+1+j], DEC);
        Serial.print(F("t"));
      }
    }
    Serial.println();
  }
}

/**
 * @brief   Print "load" command return value.
 * @param   buf  -->  "load" command return value
 * buf[0]    -->  number of records which are load successfully.
 * buf[2i+1]  -->  record number
 * buf[2i+2]  -->  record load status.
 * 00 --> Loaded 
 * FC --> Record already in recognizer
 * FD --> Recognizer full
 * FE --> Record untrained
 * FF --> Value out of range"
 * (i = 0 ~ (len-1)/2 )
 * len  -->  length of buf
 */
void printLoad(uint8_t *buf, uint8_t len)
{
  if(len == 0){
    Serial.println(F("Load Successfully."));
    return;
  }
  else{
    Serial.print(F("Load success: "));
    Serial.println(buf[0], DEC);
  }
  for(int i=0; i<len-1; i += 2){
    Serial.print(F("Record "));
    Serial.print(buf[i+1], DEC);
    Serial.print(F("t"));
    switch(buf[i+2]){
    case 0:
      Serial.println(F("Loaded"));
      break;
    case 0xFC:
      Serial.println(F("Record already in recognizer"));
      break;
    case 0xFD:
      Serial.println(F("Recognizer full"));
      break;
    case 0xFE:
      Serial.println(F("Record untrained"));
      break;
    case 0xFF:
      Serial.println(F("Value out of range"));
      break;
    default:
      Serial.println(F("Unknown status"));
      break;
    }
  }
}

/**
 * @brief   Print "train" command return value.
 * @param   buf  -->  "train" command return value
 * buf[0]    -->  number of records which are trained successfully.
 * buf[2i+1]  -->  record number
 * buf[2i+2]  -->  record train status.
 * 00 --> Trained 
 * FE --> Train Time Out
 * FF --> Value out of range"
 * (i = 0 ~ len-1 )
 * len  -->  length of buf
 */
void printTrain(uint8_t *buf, uint8_t len)
{
  if(len == 0){
    Serial.println(F("Train Finish."));
    return;
  }
  else{
    Serial.print(F("Train success: "));
    Serial.println(buf[0], DEC);
  }
  for(int i=0; i<len-1; i += 2){
    Serial.print(F("Record "));
    Serial.print(buf[i+1], DEC);
    Serial.print(F("t"));
    switch(buf[i+2]){
    case 0:
      Serial.println(F("Trained"));
      break;
    case 0xFE:
      Serial.println(F("Train Time Out"));
      break;
    case 0xFF:
      Serial.println(F("Value out of range"));
      break;
    default:
      Serial.print(F("Unknown status "));
      Serial.println(buf[i+2], HEX);
      break;
    }
  }
}

/**
 * @brief   Print "sigtrain" command return value.
 * @param   buf  -->  "sigtrain" command return value
 * buf[0]  -->  number of records which are trained successfully.
 * buf[1]  -->  record number
 * buf[2]  -->  record train status.
 * 00 --> Trained 
 * F0 --> Trained, signature truncate
 * FE --> Train Time Out
 * FF --> Value out of range"
 * buf[3] ~ buf[len-1] --> Signature.
 * len  -->  length of buf
 */
void printSigTrain(uint8_t *buf, uint8_t len)
{
  if(len == 0){
    Serial.println(F("Train With Signature Finish."));
    return;
  }
  else{
    Serial.print(F("Success: "));
    Serial.println(buf[0], DEC);
  }
  Serial.print(F("Record "));
  Serial.print(buf[1], DEC);
  Serial.print(F("t"));
  switch(buf[2]){
  case 0:
    Serial.println(F("Trained"));
    break;
  case 0xF0:
    Serial.println(F("Trained, signature truncate"));
    break;
  case 0xFE:
    Serial.println(F("Train Time Out"));
    break;
  case 0xFF:
    Serial.println(F("Value out of range"));
    break;
  default:
    Serial.print(F("Unknown status "));
    Serial.println(buf[2], HEX);
    break;
  }
  Serial.print(F("SIG: "));
  Serial.write(buf+3, len-3);
  Serial.println();
}

/**
 * @brief   Print "settings" command return value.
 * @param   buf  -->  "settings" command return value
 * buf[0]  -->  number of records which are trained successfully.
 * buf[1]  -->  record number
 * buf[2]  -->  record train status.
 * 00 --> Trained 
 * F0 --> Trained, signature truncate
 * FE --> Train Time Out
 * FF --> Value out of range"
 * buf[3] ~ buf[len-1] --> Signature.
 * len  -->  length of buf
 */

const unsigned int io_pw_tab[16]={
  10,  15,  20,  25,  30,  35,  40,  45, 
  50,  75,  100, 200, 300, 400, 500, 1000
};

void printSystemSettings(uint8_t *buf, int len)
{

  switch(buf[0]){
  case 0:
  case 3:
    Serial.println(F("Baud rate: 9600"));
    break;
  case 1:
    Serial.println(F("Baud rate: 2400"));
    break;
  case 2:
    Serial.println(F("Baud rate: 4800"));
    break;
  case 4:
    Serial.println(F("Baud rate: 19200"));
    break;
  case 5:
    Serial.println(F("Baud rate: 38400"));
    break;
  default:
    Serial.println(F("Baud rate: UNKONOWN"));
    break;
  }

  switch(buf[1]){
  case 0:
  case 0xFF:
    Serial.println(F("Outpu IO Mode: Pulse"));
    break;
  case 1:
    Serial.println(F("Outpu IO Mode: Toggle"));
    break;
  case 2:
    Serial.println(F("Outpu IO Mode: Clear(When recognized) "));
    break;
  case 3:
    Serial.println(F("Outpu IO Mode: Set(When recognized)"));
    break;
  default:
    Serial.println(F("Output IO Mode: UNKONOWN"));
    break;
  }

  if(buf[2] > 15){
    Serial.println(F("Pulse width: UNKONOWN"));
  }
  else{
    Serial.print(F("Pulse Width: "));
    Serial.print(io_pw_tab[buf[2]], DEC);
    Serial.println(F("ms"));
  }

  if(buf[3] == 0 || buf[3] == 0xFF){
    Serial.println(F("Auto Load: disable"));
  }
  else{
    Serial.println(F("Auto Load: enable"));
  }

  switch(buf[4]){
  case 0:
  case 0xFF:
    Serial.println(F("Group control by external IO: disabled"));
    break;
  case 1:
    Serial.println(F("Group control by external IO: system group selected"));
    break;
  case 2:
    Serial.println(F("Group control by external IO: user group selected"));
    break;
  default:
    Serial.println(F("Group control by external IO: UNKNOWN STATUS"));
    break;
  }
}

void printHelp(void)
{
  Serial.println(F("COMMAND        FORMAT                        EXAMPLE                    Comment"));
  printSeperator();
  //  Serial.println(F("--------------------------------------------------------------------------------------------------------------"));
  Serial.println(F("train          train (r0) (r1)...            train 0 2 45               Train records"));
  Serial.println(F("load           load (r0) (r1) ...            load 0 51 2 3              Load records"));
  Serial.println(F("clear          clear                         clear                      remove all records in  Recognizer"));
  Serial.println(F("record         record / record (r0) (r1)...  record / record 0 79       Check record train status"));
  Serial.println(F("vr             vr                            vr                         Check recognizer status"));
  Serial.println(F("getsig         getsig (r)                    getsig 0                   Get signature of record (r)"));
  Serial.println(F("sigtrain       sigtrain (r) (sig)            sigtrain 0 ZERO            Train one record(r) with signature(sig)"));
  Serial.println(F("settings       settings                      settings                   Check current system settings"));
  Serial.println(F("help           help                          help                       print this message"));
}


    1. В модуль Wemos D1 Mini заливаем скетч
//http://www.esp8266learning.com/wemos-webserver-example.php



#include 
#include 
#include 


const char ssid[] = "ИмяВашейСети";             //!!!!!!!!!!!!!!!!!!!!! modify this
const char password[] = "ВашПарольWiFi";                //!!!!!!!!!!!!!!!!!!!!!modify this
 
int ledPin = D4;          //connect led pin to d4 and ground
int turn = D5;
int buttonState = 0;  
String inputString = "";
boolean stringComplete = false;

IPAddress server(192,168,0,101);  // сервер MajorDoMo - вставьте свой локальный адрес
WiFiClient client;
 
void setup() {
  Serial.begin(115200);
  delay(10);
 
 
  pinMode(ledPin, OUTPUT);
  pinMode(turn, INPUT);
  
  digitalWrite(ledPin, HIGH);
  // digitalWrite(turn, LOW);
 
  // Connect to WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  inputString.reserve(200);
}

 
void loop() {
  
  buttonState = digitalRead(turn);
  
  
  if(buttonState==HIGH){ 
 
 if(client.connect(server,80)){
    Serial.println("conected");
    
    client.println("GET /objects/?script=commandRPI HTTP/1.0");
    client.println();
   
         
    }
  
  digitalWrite(ledPin, LOW);
  delay(1000);
  digitalWrite(ledPin, HIGH);
  }
   
}




  1. В системе MajorDoMo создаем сценарий commandRPI со строчкой кода:
exec('sudo /home/pi/script/stt.sh');

Также, если мы хотим, чтобы по команде «Включи музыку« через протоколы распберри gpio включилось реле, управляемое звукоусилителем с колонками, в системе должен быть шаблон, который включает реле и запускает плейлист:

if (getGlobal('Colonki'.'.'.'status')=='0') {
  callMethod('Colonki.turnon');
}
say("включаю музыку");
runScript("SetMusicStatusOn");

file("http://:12345@192.168.0.101:8080/requests/status.xml?command=pl_empty");
file("http://:12345@192.168.0.101:8080/requests/status.xml?command=in_play&input=/share/tancy/");  

У меня в расшаренной папке /share лежит музыка разложенная по жанрам/папкам

  1. В raspberry Pi в папке /home/pi создаем папку script и добавляем туда файл stt.sh
#!/bin/bash
export AUDIODEV="hw:0"
echo "speaking ..."
arecord -B --buffer-time=1000000 -f S16_LE -r 16000 -d 5 -D plughw:1,0 /home/pi/script/send.wav

echo "waw-flac"
flac -f  /home/pi/script/send.wav -o /home/pi/script/send.flac

echo "Converting..."
curl -X POST --data-binary @/home/pi/script/send.flac --header 'Content-Type: audio/x-flac; rate=16000;' 'https://www.google.com/speech-api/v2/recognize?output=json&lang=ru-ru&key=ПолучитеСвойКлючНаГуглАпиИВставтеЕгоСюда' |  cut -d" -f8 > stt 
value=`cat stt`
arr=("$value")
echo ${arr[@]} | cut -d ' ' --output-delimiter=' ' -f 1- > stt2
echo 'http://192.168.0.101/command.php?qry='> stt1
echo "`cat stt1``cat stt2`" > stt4
value2=`cat stt4`

curl ${value2// /%20}

Вот и все, подытожим:

Я говорю «Анжелика», v3 модуль+arduino распознает и дает команду WemosD1 Mini, который запускает скрипт распберри на включение микрофона и запись. Я озвучиваю команду «включи музыку» и распознанный гуглом ответ запускает шаблон, который выполняет код запуска скрипта включения колонок и проигрывания плейлиста. Шаблоны в MajorDoMo строятся быстро и программируются просто. Таким образом мы можем включать или выключать любые приборы в доме и за его пределами… Например у меня пока реализованы следующие шаблоны:

  • Музыка (Мантры, Релакс, Детская, Рок и др. по настроению)
  • Какая погода?
  • Что такое? Кто такой? (выдергивается и озвучивается информация с википедии)
  • Онлайн радио
  • Режим релакс (включается светодиодная лента с программируемым режимом — зеленно-желтой змейкой и музыка релакс)

arduibag

Is it possible to have an ESP32 compatible library ?
It would be awsome !

miqbal23

I got similar error with #3 , but mine when I tried to send settings command to the module

The message written can be seen in screenshot provided

5292a154-fbaf-4c79-8df3-c60436083674

I developed the code in Windows, but tried to send this command from my Ubuntu PC. The code worked well in Windows.

Could it be a problem on me changing PC or the problem in module?

newtotech

Every time I try to execute a command via serial com I keep getting an error message like «Train with signature failed or timeout.» or more like «(command) failed or timeout» but the lights indicate that it has worked. It also will not pull the any signatures or check records and when I input the settings command I get the «settings failed or timeout.» response.

am I doing something wrong?

Oh, I’m using the V3 module with my Arduino 101 board. the txd and rxd pins are connected to my tx and rx digital input pins 0 and 1.

OmarAdelShalaan

I wanna make the train on to voice recognization module v3.1 with Arduino but send me this message «Train with signature failed or timeout.»
can anybody help me to solve this problem?

mourad963

Greeting .. i have no issue with coding and train the V3 module .. I’m using it for my project and I’m totally satisfy with it but the only missing thing is the theoretical information such as
How this model is comparing the vocal commands?
Is it able to distinguish the same command but two different subjects? if yes how? if no why?
The algorithm use here?
The additional pins what for ? (OUT1-6, IN0-2)?

Thank you .. your cooperation is highly appropriated

dsssssssss9

Hi

Just got one of your voice recognition module v3 — really looking forward to using it in my projects

Hope you don’t mind but i have a couple of questions that i can’t seem to find an answer to ….

  1. many sellers are listing this and some videos are showing this as capable of storing 254 commands! But your documentation states it can only store 80 — what is the correct number please?

  2. the board has i2c / EPM / VPP / IN 0-2 pins — what are these used for & how do do we use them please — i cannot seem to see any info on this in your documentation, sorry if i have just missed it

Hope to hear from you soon

Regards

Jason

bkeschinger

Hello, I’m using the Elechouse VRv3 and have successfully trained it to work with the vr_sample_control_led program. I’m using this with an Elegoo Mega 2560 R3 Arduino board. When the board is plugged into my PC and receiving power from the USB, the program and commands work correctly! If I unplug the USB and power it via a 9V1A wall plug (USA), the program and voice commands no longer work.

Have you seen this before?

I put in a «digitalWrite(led, HIGH);» at the end of the Setup() function to ensure it’s running and it is in both the USB and wall outlet situation. I’m unsure how to debug this from here! Thanks for your time!

EDIT: Is there some code in the vr_sample_control_led program that depends on the serial connection?

ilhmfahmi

i can’t use this module with esp32

Clear recognizer failed or timeout.

how to fix that

Alejo1510

Hello.

I bought one of their speech recognition modules, for a school project, but I need to integrate it to an Arduino DUE where the SoftwareSerial libraries don’t work.

Are there libraries for Arduino DUE?

Best regards.-

seifdaad

sayakingXD

my voice recognition v3 not blinking and why ican’t load the train
image

asianplanet

Can someone describe the power on auto load command in further details please?
«| …| 03+n | 15 | BITMAP | R0 | … | Rn | .. |»

***original description ***
Set Power On Auto Load (15)
Use this command to enable or disable «Power On Auto Load» function.
Format:
| AA| 03 | 15 | 00 | 0A | (disable auto load)
| AA| 03+n | 15 | BITMAP | R0 | … | Rn | 0A | (set auto load)
Return:
| AA| 04+n | 15 | 00 |BITMAP | R0 | … | Rn | 0A | (set auto load)
BITMAP: Record bitmap.( 0-zero record, disable auto load 01-one record 03-two records 07-three records 0F-four records 1F-five records 3F-six record 7F-seven records )
R0~Rn: Record

dcuti8

I use the module with WeMos D1 R3 board, when I connect it to the computer (Win7), the light is always on. I see the light of the VR3 is blinking in the video .
And I try to use the vr_sample_train, when I press settings, It return nothing.
I also try to use Access Port to test if the module is working, but I also cannot get any return message when I send the data.

Does anyone know why this light is on all the time?

my connection:
WeMos D1 R3 VoiceRecognitionModule
GND ——-> GND
5V ——-> VCC
D0(RX) ——-> TX
D1(TX) ——-> RX

caleb221

Hello!
I see there are pins for VOC near the Analog Microphone input, as well as a space for i2c pins on the board.
Is there a way to send input data to the board using these pins and not the microphone? Any help would be greatly appreciated.
Thanks!
-Caleb

hbadotti

How can I make it work with hardware serial pin from Arduino Mega?

mkeyno

sorry to open ticket for my question, actually I’ve plan to make wifi bridge (ESP8266) between my landline phone and my smart mobile , so I could dial or receive my phone by mobile , I’m not sure about the which hardware should be selected and really appreciated to have your probably advise for that

snz007

i got problem with my voice recognition module like that

capture

baud rate and pulse width unknown cause i cant train this module.
how i solve this problem?

arduibag

Hi,

I tried your library with an Arduino Uno : everything is fine.
I want to use it with a Teensy 3.2 board but the library seems to be incompatible with it.
When I try «vr_sample_train.ino» and when I type «settings» I have this message : «Check system settings error or timeout»

Pins are ok.

I would be grateful if anyone could help me with this issue.

Thanks,

Mike

prasadbarude

I have trained the uno and uploaded the control led code. But whenever i open serial monitor, i get this error message :
Not find VoiceRecognitionModule.
Please check connection and restart Arduino

I would be grateful if anyone could help me with this issue.

chaeplin

I have an Arduino Mega clone and I haven’t used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn’t work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here’s my code:

#define distanceForward A0
#define distanceLeft A1
#define distanceRight A2
#define distanceRightAngle A3
#define distanceLeftAngle A4
#define distanceBack A5
int talk = 2;

void setup() {
  Serial.begin(9600);
  pinMode(talk, OUTPUT);
  pinMode(distanceForward, INPUT);
  // / Ir distance sensor pin for input signal to arduino, Front Facing
  pinMode(distanceLeftAngle, INPUT);
  // / Ir distance sensor pin for input signal to arduino, Left Angle
  pinMode(distanceRightAngle, INPUT);
  // / Ir distance sensor pin for input signal to arduino, Right Angle
  pinMode(distanceLeft, INPUT);
  // / Ir distance sensor pin for input signal to arduino, Left
  pinMode(distanceRight, INPUT);
  // / Ir distance sensor pin for input signal to arduino, Right
  pinMode(distanceBack, INPUT);
  // / Ir distance sensor pin for input signal to arduino, back
}

void hall_roam() {
  Serial.write("forward");
  if (analogRead(distanceLeftAngle) < 30) {
    Serial.write("right");
    if (analogRead(distanceLeftAngle) > 30) {
      Serial.write("forward");
    }
    if (analogRead(distanceRightAngle) < 30) {
      Serial.write("left");
      if (analogRead(distanceRightAngle) < 30) {
        Serial.write("forward");
      }
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("left");
          if (analogRead(distanceForward) > 60) {
            Serial.write("stop");
          }
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("right");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      } else {
        Serial.write("forward");
      }
    }
  }
}

void roam() {
  Serial.write("forward");
  if (analogRead(distanceForward) < 60) {
    Serial.write("stop");
    Serial.write("left");
    if (analogRead(distanceForward) > 60) {
      Serial.write("stop");
      Serial.write("forward");
    }
  }
}

void talkbb8() {
  pinMode(talk, HIGH);
  pinMode(talk, LOW);
}

void chill() {
  Serial.write("stop");
  talkbb8();
}

void loop() {
  if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
    hall_roam();
  } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
    Serial.write("left");
    if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
      Serial.write("stop");
      hall_roam();
    }
  } else {
    roam();
  }
}

If there’s a bracket out of place or something it’s probably nothing. I’m talking about the characters. Is there anything in the characters that would screw up the upload like the three «!!!» problem I heard about or something like that. It’s possible that the USB chip in it isn’t recognized by my iMac. If so how do I fix that?

To my humble understanding, this error arises in different scenarios:

  1. you have selected the wrong port or you haven’t at all. go to tools > ports and select the com port with your Arduino connected to.

  2. you have selected the wrong board. go to tools > board and look for the right board.

  3. Do you have one of these Arduino replicas or you don’t have the boot-loader installed on the microcontroller? I don’t know the solution to this! if you know please edit my post and add the instructions.

  4. (windows only) you don’t have the right drivers installed. you need to update them manually.

  5. sometimes when you have wires connected to the board this happens. you need to separate the board from any breadboard or wires you have installed and try uploading again. It seems pins 0 (RX) and 1 (TX), which can be used for serial communication, are problematic and better to be free while uploading the code.

  6. Sometimes it happens randomly for no specific reason!

There are all kinds of solutions all over the internet, but sometimes hard to tell the difference between magic! Maybe the Arduino team should think of better compiler errors to help users differentiate between these different causes.

The same problem happened to me and none of the solutions above worked. What happened was that I was using an Arduino UNO and everything was fine, but when I bought an Arduino Mega 2560, no matter what sketch I tried to upload I got the error:

avrdude: stk500v2_ReceiveMessage(): timeout

And it was just on one of my windows computers and the other one was just ok out of the box.

Solution:

What solved my problem was to go to tools > boards > Boards Manager... and then on the top left of the opened windows select updatable in the Type section. Then select the items in the list and press update on the right.

I’m not sure if this will solve everyone’s problem, but it at least solved mine.

Понравилась статья? Поделить с друзьями:
  • Check system power error please plug in ac adapter asus что делать
  • Check system injection ошибка р0089 на к9к дизель
  • Check system error please plug battery then press any key to flash bios
  • Check system error please plug ac power then press any key to flash bios
  • Check supplies datamax ошибка как исправить