Главная » Просмотр файлов » Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008

Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 47

Файл №779888 Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (Symbian Books) 47 страницаWiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888) страница 472018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 47)

Please note, the outputmoves quickly between positive, then negative data values, indicating thetransition between acceleration and deceleration and vice versa.There are some smaller residual artifacts from this movement, seen inboth x and z, which results from testing by hand, rather than using afixed jig (as it is difficult to isolate a movement completely under suchconditions). Figure 6.12 depicts the potential for using ‘hand gestures’for the control of events within games and without the problems associated with using the camera to obtain the movement.10 However, gesturerecognition requires careful study as the variation in how the user holds12Gilbertson P., Coulton P., and Vajk T., Using Tilt as the Input for 3D MobileGames, The Third International Conference on Games Research and Development 2007(CyberGames 2007), Manchester, UK, 10–11 September 2007.202EXPLOITING THE PHONE HARDWARE6xyzAcceleration (g)420−2−4−6050100150200250300SamplesFigure 6.12Nokia 5500 accelerometer data (lateral movement of phone across the table)6xyzAcceleration (g)420−2−4−6050100150200250300SamplesFigure 6.13 Nokia 5500 accelerometer data (phone dropped)the phone could produce anomalous outputs and there is no method ofobtaining the phone’s physical position within actual space as providedby the sensor bar for the Wii.

This is because both rotation and translational acceleration affect the accelerometer’s output (essentially they canproduce the same internal forces on the accelerometer).Figure 6.13 represents the output after the phone has been dropped.The trace shows that initially the phone is held upright with the screenheld at the top and gravity is acting on x. When the phone is dropped,the effect of gravity is overcome, and all three accelerometers outputapproximately zero before the phone hits the floor with a jolt.

The aim ofthis test was to show that the phone could be used to measure activity of3D MOTION SENSORSFigure 6.14203A screenshot from Tilt Racer and an example of typical play (inset)a player within a game, such as jumping or running, whereby the phonewould simply be worn rather than held and directly controlled.Whilst there are undoubtedly many applications of 3D motion sensorsthat can be created using this novel phone interface, they could also beused to allow the phones to act as controllers for games running on largepublic displays as shown by Tilt Racer in Figure 6.14.

Tilt Racer is anovel multiplayer game developed using the Microsoft XNA frameworkrunning on PC and displayed on a large public display.10 The players’cars are controlled using Bluetooth technology.6.4.1 Using Sensors on Symbian OSAccessing the 3D motion sensors requires the use of the Symbian OS Sensor API which provides access to a wide range of sensors. These sensorscan include accelerometers, thermometers, barometers, and humiditymonitors.

In fact, it can be any type of sensor designed to be incorporatedinto a mobile phone or be accessible to the phone via Bluetooth technology.13 Sensors need only be supported by the API library to be usable.Currently, the Symbian OS Sensor API is available only from Nokia andrequires the use of the S60 3rd Edition SDK, and, as such, this section iscurrently biased towards S60, although we would expect other handsetmanufacturers to follow suit in due course.The API contains a number of key classes for retrieving sensor information and these provide the main methods for reading sensor datathrough callback functions.

They are defined in RRSensorApi.h, andthe application must link against RRSensorApi.lib.13Coulton P., Bamford W., Chehimi F., Gilbertson P., and Rashid, O. Using In-builtRFID/NFC, Cameras, and 3D Accelerometers as Mobile Phone Sensors, in Mobile PhoneProgramming [0]and its Application to Wireless Networking edited by Frank H. P. Fitzekand Frank Reichert, Springer 2007 (ISBN 1402059681), pp 381–396.204EXPLOITING THE PHONE HARDWARE• CRRSensorApi is the sensor manager class that manipulates theavailable sensors on the phone.• MRRSensorDataListener is the interface that must be implemented by the class to receive and interpret sensor data and itcontains only one function HandleDataEventL().

This functiontakes two arguments: TRRSensorInfo and TRRSensorEvent.• TRRSensorInfo is the class that holds the sensor information. Itcontains a human readable sensor name, a unique identifier for thesensor, and a category that identifies if it is internal to the device orexternal (over Bluetooth).• TRRSensorEvent is the class that contains the data obtained fromthe sensor. The current implementation provides three TInt fieldsthat contain the data.

Each sensor will provide different data in thesefields; some may provide absolute values, while others may providevalues relative to sensor events.Sensor API OverviewLibrary to link againstRRSensorApi.libHeader to includeRRSensorApi.hRequired platform security capabilities NoneClasses implementedClasses usedMRRSensorDataListenerCRRSensorApiTRRSensorInfoTRRSensorEventSince the sensor APIs are manufacturer-dependent, as with vibration,and the Nokia 5500 is the only Symbian smartphone in the Europeanmarket with a 3D sensor installed (at least at the time of writing), the codeexample we provide here for the test application, TiltMe, is thereforetested only on that phone.14 The example shown in Figure 6.15 providesFigure 6.15 Screenshots of TiltMe14Note that testing this example can only be done on Nokia 5500 hardware, as there iscurrently no Windows emulator available for the sensors.3D MOTION SENSORS205a simple text and graphical representation of the phone’s tilting positionin 3D space.As with our previous examples the sensor setup is performed in theview class of the Symbian OS application framework.

In the header filedeclaration of class CTiltMeAppView, we perform the following stepsas shown in the subsequent code:• include RRSensorApi.h• inherit from the interface MRRSensorDataListener• implement the interface’s only pure virtual function HandleDataEventL()• instantiate the sensor object iAccSensor, and some variables• declare the start and stop functions of the sensor.#include <RRSensorApi.h>class CTiltMeAppView : public CCoeControl, MRRSensorDataListener{public:// From MRRSensorDataListenervoid HandleDataEventL( TRRSensorInfo, TRRSensorEvent );// Starting the use of the sensorvoid StartSensor();// Stopping the use of the sensorvoid StopSensor();private:// Accelerometer sensorCRRSensorApi* iAccSensor;// Time calculating variablesTTime iFirst;TTime iSecond;// Sensor statusTBool iSensorFound;// The X,Y,Z acceleration valuesTInt iXAccl;TInt iYAccl;TInt iZAccl;};The two functions, StartSensor() and StopSensor() declaredin TiltMeView.h, are used to control the 3D sensor.

The user startsthe sensor by simply clicking the ‘Start’ item on the ‘Options’ menuof the application. This will trigger a call to StartSensor() whichconstructs and registers iAccSensor. But, before we can use the sensorhardware, we must enumerate all the sensors on the device, using functionCRRSensorApi::FindSensorsL(), and select the one needed, asthere is a possibility of having more than one sensor installed. Theresulting list of sensor(s) is stored on a TRRSensorInfo array as follows:206EXPLOITING THE PHONE HARDWARERArray<TRRSensorInfo> sensorList;CRRSensorApi::FindSensorsL(sensorList);Once this list is available, we need to iterate through it to find thesensor with the ID that matches the Nokia 5500 accelerometer sensor ID:0x10273024. Note that this is a preconfigured implementation value setfor the sensor hardware, and it is expected to be the same in future phones,to allow back/forward-compatibility.

When a match is successful, iAccSensor is constructed using the static factory function CRRSensorApi::NewL(TRRSensorInfo aSensor), with aSensor being thematching sensor found. The sensor is then registered by making a call toCRRSensorApi::AddDataListener(MRRSensorDataListener*aObserver), where aObserver is a pointer to the class implementingthe MRRSensorDataListener.The following code snippet demonstrates the sequence describedabove:void CTiltMeAppView::StartSensor(){// If the sensor is initially not foundif( !iSensorFound ){// Get list of available sensors (if any)RArray<TRRSensorInfo> sensorsList;CRRSensorApi::FindSensorsL(sensorsList);// Number of sensors availableTInt count = sensorsList.Count();for( TInt i = 0 ; i != count ; ++i ){// If the ID matches Nokia 5500if( sensorsList[i].iSensorId == 0x10273024 ){// Use the sensor foundiAccSensor = CRRSensorApi::NewL( sensorsList[i] );// Register the sensor for our appiAccSensor->AddDataListener( this );iSensorFound = ETrue;return;}}// Omitted for clarity}A call to function CRRSensorApi::RemoveDataListener() stopsthe sensor object from obtaining acceleration information from the sensorserver.

This is implemented in function StopSensor() as follows:void CTiltMeAppView::StopSensor(){// If the sensor has been registeredif( iSensorFound )VIBRATION207{iAccSensor->RemoveDataListener();iSensorFound = EFalse;// Just to clean up behind usdelete iAccSensor;iAccSensor = NULL;}}Function HandleDataEventL() is the only pure virtual functionto implement for the mixin MRRSensorDataListener. It receivescallback notifications from the 3D sensor server and stores them in theacceleration values iXAccl, iYAccl, and iZAccl of our application,which are then printed on screen.

In our example, these two operationsare performed 10 times a second, and the timing is controlled by the twoTTime member variables, iFirst and iSecond, whose microsecondinterval is checked every time new acceleration data from the server isavailable:void CTiltMeAppView::HandleDataEventL(TRRSensorInfo aSensor,TRRSensorEvent aEvent){iSecond.HomeTime();// Find the interval from the second time member var to the first.TTimeIntervalMicroSeconds interv = iSecond.MicroSecondsFrom(iFirst);TInt64 i = interv.Int64();if( i >= 100000 ) // 1/10th of a second{iXAccl = aEvent.iSensorData1;iYAccl = aEvent.iSensorData2;iZAccl = aEvent.iSensorData3;// Reset the first time to the current one.iFirst.HomeTime();// Update the screenDrawNow();}}Updating the screen is performed by a call to DrawNow(), whichcalls Draw() to display a compass-like needle arrow from the values ofiXAccl, iYAccl, and iZAccl.

The needle points at the direction of thetilting of the phone with its length indicating the tilting magnitude.6.5 VibrationMobile phones have provided vibration since the very early models, as ameans of increasing the likelihood of the user observing they are receivinga call or message, or for use in situations where sound is inappropriate.At first glance, the use of vibration may not immediately seem significant208EXPLOITING THE PHONE HARDWAREto developers, although one could imagine it being used for alerting usersin games not requiring constant interaction.

Характеристики

Тип файла
PDF-файл
Размер
2,71 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6455
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее