Friday 2 September 2016

Transferring pictures with OV7670 through Arduino Uno on your Android phone




Передача картинки с OV7670 через Arduino Uno на Android телефон
В прошлой статье «Arduino Uno и камера ov7670 — пример использования» был описан способ, как получить картинку с OV7670 на компьютере через USB порт. Это хороший первый шаг, но пришло время попробовать что-то более практичное. Теперь картинка будет передана через bluetooth на Android телефон.
In the last article «Arduino Uno and ov7670 camera - an example of using" has been described by way of how to get a picture with the OV7670 a computer via a USB port. This is a good first step, but it's time to try something more practical. Now picture will be transferred via bluetooth to your Android phone.

Для передачи картинки будет использоваться модуль HC-06 из-за его широкого распространения и низкой стоимости.
To transfer images HC-06 module will be used because of its wide distribution and low cost.
1. Подключение камеры OV7670
Сначала нужно будет подключить камеру к компьютеру, как описано в прошлой статье Arduino Uno и камера ov7670 — пример использования. Это позволит понять, что камера подключена правильно и даёт картинку.
2. Настройка модуля HC-06. 
На этом шаге возникает основная проблема: несовпадение скоростей UART интерфейсов HC-06 и Arduino Uno. Эти платы имеют строго фиксированный набор допустимых значений.
HC-06: 1200 / 2400 / 4800 / 9600 / 19200 / 38400 / 57600 / 115200 / 230400 / 460800 / 921600 / 1382400
Arduino Uno: 2400 / 4800 / 9600 / 14400 / 19200 / 28800 / 38400 / 57600 / 76800 / 115200 / 230400 / 250000 / 500000 / 1000000 / 2000000
Максимальная совпадающая скорость передачи — 230400. Её и нужно выставить.  Для настройки модуля можно использовать пример и следующие параметры. Имя имеет значение, т.к. оно задано в коде Android приложения. Не пытайтесь выставить разные скорости, это приведёт к полной потери связи с HC-06.



1. OV7670 Camera Connection
First you need to connect the camera to a computer, as described in the previous article Arduino Uno and ov7670 camera - an example of use. This will realize that the camera is connected correctly and gives a picture.
2. Setting the HC-06 module.
In this step, there is a fundamental problem: a mismatch of speeds UART Interfaces HC-06, and Arduino Uno. These boards have a strictly fixed set of valid values.
HC-06: 1200/2400/4800/9600/19200/38400/57600/115200/230400/460800/921600/1382400
Arduino Uno: 2400/4800/9600/14400/19200/28800/38400/57600/76800/115200/230400/250000/500000/1000000/2000000
The maximum transfer rate matched - and 230400. It is necessary to expose. example and the following parameters can be used to configure the module. Name has the meaning as it is set in the Android application code. Do not try to set different speeds, this will lead to a complete loss of communication with the HC-06.
Параметр
Значение
Скорость
230400,8,1,n
Имя
Merl1nVision
parameter value
Speed 230400,8,1, n
Bvz Merl1nVision
После настройки остаётся только подключить модуль HC-06 к Arduino Uno.
After setting can only connect the HC-06 module for Arduino Uno.
3. Доработка кода для Arduino Uno
В примере с  ov7670 и компьютером использовалась скорость UART — 1000000. Этого было достаточно, чтоб передать картинку с камеры. Но если подключение осуществляется на скорости ниже — 230400, картинка будет приходить с сильным искажением. Поэтому нужно внести в код для Arduino изменения:
Изменить частоту UART
3. Further development of code for the Arduino Uno
In the example of the computer used and ov7670 speed UART - 1000000. This was enough to convey a picture with the camera. But if the connection is made at a speed below - 230400, the picture will come with strong distortion. Therefore, you need to make changes in the code for Arduino:
Change UART frequency
UBRR0H = 0; 
UBRR0L = 8;//230400 
UCSR0A |= 2; 
UCSR0B = (1 << RXEN0) | (1 << TXEN0); 
UCSR0C = 6;
Максимально уменьшить внутреннюю частоту. Это можно сделать, изменив значение в регистре 0x11
Minimize internal frequency. This can be done by changing the value in the 0x11 register
    wrReg(0x11, 31);
К сожалению изменение внутренней частоты не даёт возможности передать что-то на скорости 230400, поэтому картину придётся передавать в два этапа — сначала четные строки, потом нечётные.
Unfortunately the change in internal rate makes it impossible to convey something to 230,400 rate, so the picture will have to pass in two stages - first the even lines, then odd.
captureImg(320, 240, true); 
captureImg(320, 240, false); 
static void captureImg(uint16_t wg, uint16_t hg, bool firstSecond){ 
    uint16_t y, x; 
    bool flag = true; 
    StringPgm(PSTR("*RDY*")); 
    while (!(PIND & 8)); 
    while ((PIND & 8)); 
    y = hg; 
    while (y--){ 
    x = wg; 
    while (x--){ 
        flag = !flag; 
    while ((PIND & 4)); 
            if (flag == firstSecond) { 
                UDR0 = (PINC & 15) | (PIND & 240); 
            } 
            while (!(PIND & 4)); 
        while ((PIND & 4)); 
        while (!(PIND & 4)); 
    } 
    } 
   _delay_ms(100); 
}
4. Android приложение для получения картинки
Приложение для телефона должно только прочитать картинку и вывести её на экран.
5. Результаты
Изображение получить удалось. На телефоне с Bluetooth 2.1 (LG P970) кадр передавался больше минуты и был сильно искажен. Для телефона с Bluetooth 4.0 (Nexus 5) результат представлен ниже, передача картинки заняла менее 15 секунд.

4. Android app to get pictures
The application for the phone should only read the image and display it on the screen.
5. results
The image could be obtained. On the phone with Bluetooth 2.1 (LG P970) frame transmitted over a minute and was heavily distorted. For a phone with Bluetooth 4.0 (Nexus 5) results presented below, the transfer of images took less than 15 seconds.
Результаты для ov7670
 &Rcy;&iecy;&zcy;&ucy;&lcy;&softcy;&tcy;&acy;&tcy;&ycy; &dcy;&lcy;&yacy; ov7670
Из опыта получается, что передача потокового видео c камеры ov7670 через bluetooth и android невозможна ввиду низких скоростей последних, но можно получить фотографию с выдержкой в 15 секунд через bluetooth 4.0.
From the experience it turns out that the video streaming c ov7670 camera via bluetooth and android is not possible due to the low speed of the latter, but you can get a photo with an exposure of 15 seconds via bluetooth 4.0.

3 comments:

  1. sir,
    to which pins we have to connect bluetooth

    ReplyDelete
  2. hey im getting connected but no image appears

    ReplyDelete
  3. Hello! I configurated my module bluetooth, name= Merl1nVision and Uart=230400,0,0
    but when i run the app this error show me:

    Paired device: Nerl1nVision
    StackTrace:
    info.privateblog.merl1n.merl1nvision.bluetooth.exception.ConnectionBluetoothException: java.io.IOExpention: the read failed The, the socket of might closed or timeout, the read the ret: -1 at info.privateblog.merl1n.merl1nvision.bluetooth.BluetoothConnector.connect(BluetoothConector.java:48) at info.privateblog.merl1n.merl1nvision.MainActivity$2.onClick(MainActivity.java:124) at android.view.View.performClick(View.java:4439) at android.wiedget.button.performClick(Button.java:139) at android.view.View$performClick.run(Handler.java:725) at android.os.Handler.dispatchMwssage(Handler.java:92) at android.os.Looper.loop(Looper.java:176) st android.os………………..

    ReplyDelete