Sensors

« Back to index

Sensors

Table of Contents:

AccelerometerSensor

Non-visible component that can detect shaking and measure acceleration approximately in three dimensions using SI units (m/s2). The components are:

  • xAccel: 0 when the phone is at rest on a flat surface, positive when the phone is tilted to the right (i.e., its left side is raised), and negative when the phone is tilted to the left (i.e., its right size is raised).
  • yAccel: 0 when the phone is at rest on a flat surface, positive when its bottom is raised, and negative when its top is raised.
  • zAccel: Equal to -9.8 (earth’s gravity in meters per second per second when the device is at rest parallel to the ground with the display facing up, 0 when perpendicular to the ground, and +9.8 when facing down. The value can also be affected by accelerating it with or against gravity.

Properties

Available
Returns whether the AccelerometerSensor hardware is available on the device.
Enabled
Specifies whether the sensor should generate events. If true, the sensor will generate events. Otherwise, no events are generated even if the device is accelerated or shaken.
LegacyMode
Prior to the release that added this property the AccelerometerSensor component passed through sensor values directly as received from the Android system. However these values do not compensate for tablets that default to Landscape mode, requiring the MIT App Inventor programmer to compensate. However compensating would result in incorrect results in Portrait mode devices such as phones. We now detect Landscape mode tablets and perform the compensation. However if your project is already compensating for the change, you will now get incorrect results. Although our preferred solution is for you to update your project, you can also just set this property to “true” and our compensation code will be deactivated. Note: We recommend that you update your project as we may remove this property in a future release.
MinimumInterval
Specifies the minimum interval required between back-to-back Shaking events, in milliseconds. Once the phone starts being shaken, all further Shaking events will be ignored until the interval has elapsed.
Sensitivity
Specifies the sensitivity of the accelerometer. Valid values are: 1 (weak), 2 (moderate), and 3 (strong).
XAccel
Returns the acceleration in the X-dimension in SI units (m/s²). The sensor must be enabled to return meaningful values.
YAccel
Returns the acceleration in the Y-dimension in SI units (m/s²). The sensor must be enabled to return meaningful values.
ZAccel
Returns the acceleration in the Z-dimension in SI units (m/s²). The sensor must be enabled to return meaningful values.

Events

AccelerationChanged(xAccel,yAccel,zAccel)
Indicates the acceleration changed in the X, Y, and/or Z dimensions.
Shaking()
Indicates the device started being shaken or continues to be shaken.

Methods

None

BarcodeScanner

Component for scanning a QR code and getting back the resulting string.

Properties

Result
Gets the text result of the previous scan.
UseExternalScanner
Set whether or not you wish to use an External Scanning program such as Bar Code Scanner. If false a version of ZXing integrated into App Inventor will be used.

Events

AfterScan(result)
Indicates that the scanner has read a (text) result and provides the result

Methods

DoScan()
Begins a barcode scan, using the camera. When the scan is complete, the AfterScan event will be raised.

Barometer

Physical world component that can measure the ambient air pressure if supported by the hardware.

Properties

AirPressure
The atmospheric pressure in hPa (millibar), if the sensor is available and enabled.
Available
Specifies whether or not the device has the hardware to support the Barometer component.
Enabled
Specifies whether the sensor should generate events. If true, the sensor will generate events. Otherwise, no events are generated.
RefreshTime
The requested minimum time in milliseconds between changes in readings being reported. Android is not guaranteed to honor the request. Setting this property has no effect on pre-Gingerbread devices.

Events

AirPressureChanged(pressure)
Called when a change is detected in the air pressure (provided in hPa).

Methods

None

Clock

Image of the Clock component

Non-visible component that provides the instant in time using the internal clock on the phone. It can fire a timer at regularly set intervals and perform time calculations, manipulations, and conversions.

Operations on dates and times, such as from DatePicker and TimePicker, are accomplished through methods in Clock. Date and Time are represented as InstantInTime and Duration.

Instants are assumed to be in the device’s local time zone. When they are converted to or from milliseconds, the milliseconds for a given Instance are calculated from January 1, 1970 in UTC (Greenwich Mean Time).

Methods to convert an Instant to text are also available. Acceptable patterns are empty string, MM/dd/YYYY HH:mm:ss a, or MMM d, yyyy HH:mm. The empty string will provide the default format, which is "MMM d, yyyy HH:mm:ss a" for FormatDateTime, "MMM d, yyyy" for FormatDate. To see all possible formats, please see here.

A note on combining date and time: In order to combine the date from one Instant and the time from another, for example from a DatePicker and TimePicker, extract the parts as text and use the text to create a new Instant. For example:

Example code blocks to combine date and time picker data

Properties

TimerAlwaysFires
Will fire even when application is not showing on the screen if true
TimerEnabled
Specifies whether the Timer event should run.
TimerInterval
Specifies the interval between subsequent Timer events.

Note: Drift may occur over time and that the system may not honor the timing specified here if the app or another process on the phone is busy.

Events

Timer()
The Timer event runs when the timer has gone off.

Methods

AddDays(instant,quantity)
Returns an instant in time some days after the given instant.
AddDuration(instant,quantity)
Returns an instant in time some duration after the argument
AddHours(instant,quantity)
Returns an instant in time some hours after the given instant.
AddMinutes(instant,quantity)
Returns an instant in time some minutes after the given instant.
AddMonths(instant,quantity)
Returns an instant in time some months after the given instant.
AddSeconds(instant,quantity)
Returns an instant in time some seconds after the given instant.
AddWeeks(instant,quantity)
Returns An instant in time some weeks after the given instant.
AddYears(instant,quantity)
Returns an instant in time some years after the given instant.
DayOfMonth(instant)
Returns the day of the month.
Duration(start,end)
Returns the milliseconds by which end follows start (+ or -)
DurationToDays(duration)
Returns the duration converted from milliseconds to days.
DurationToHours(duration)
Returns the duration converted from milliseconds to hours.
DurationToMinutes(duration)
Returns the duration converted from milliseconds to minutes.
DurationToSeconds(duration)
Returns the duration converted from milliseconds to seconds.
DurationToWeeks(duration)
Returns the duration converted from milliseconds to weeks.
FormatDate(instant,pattern)
Converts and formats an instant into a string of date with the specified pattern. To learn more about valid patterns, please see SimpleDateFormat.
FormatDateTime(instant,pattern)
Converts and formats an instant into a string of date and time with the specified pattern. To learn more about valid patterns, please see SimpleDateFormat.
FormatTime(instant)
Converts and formats the given instant into a string with the specified pattern. To learn more about valid patterns, please see SimpleDateFormat.
GetMillis(instant)
Returns the instant in time measured as milliseconds since 1970.
Hour(instant)
Returns the hours for the given date.
MakeDate(year,month,day)
Returns an instant in time specified by year, month, date in UTC. Valid values for the month field are 1-12 and 1-31 for the day field.
MakeInstant(from)
Returns an instant in time specified by MM/dd/YYYY hh:mm:ss or MM/dd/YYYY or hh:mm.
MakeInstantFromMillis(millis)
Returns an instant in time specified by the milliseconds since 1970 in UTC.
MakeInstantFromParts(year,month,day,hour,minute,second)
Returns an instant in time specified by year, month, date, hour, minute, second in UTC.
MakeTime(hour,minute,second)
Returns an instant in time specified by hour, minute, second in UTC.
Minute(instant)
Returns the minutes for the given date.
Month(instant)
Returns the number of the month for the given instant.
MonthName(instant)
Returns the name of the month for the given instant.
Now()
Returns the current instant in time read from phone’s clock.
Second(instant)
Returns the seconds for the given instant.
SystemTime()
Returns the phone’s internal time.
Weekday(instant)
Returns the weekday for the given instant.
WeekdayName(instant)
Returns the name of the weekday for the given instant.
Year(instant)
Returns the year of the given instant.

GyroscopeSensor

Component providing data from the device’s gyroscope sensor.

Properties

Available
Indicates whether a gyroscope sensor is available.
Enabled
Enabled property getter method.
XAngularVelocity
The angular velocity around the X axis, in degrees per second.
YAngularVelocity
The angular velocity around the Y axis, in degrees per second.
ZAngularVelocity
The angular velocity around the Z axis, in degrees per second.

Events

GyroscopeChanged(xAngularVelocity,yAngularVelocity,zAngularVelocity,timestamp)
Indicates that the gyroscope sensor data has changed. The timestamp parameter is the time in nanoseconds at which the event occurred.

Methods

None

Hygrometer

Physical world component that can measure the relative ambient air humidity if supported by the hardware.

Properties

Available
Specifies whether or not the device has the hardware to support the Hygrometer component.
Enabled
Specifies whether the sensor should generate events. If true, the sensor will generate events. Otherwise, no events are generated.
Humidity
Returns the relative ambient humidity as a percentage. The sensor must be enabled and available to return meaningful values.
RefreshTime
The requested minimum time in milliseconds between changes in readings being reported. Android is not guaranteed to honor the request. Setting this property has no effect on pre-Gingerbread devices.

Events

HumidityChanged(humidity)
Indicates the relative humidity changed.

Methods

None

LightSensor

Physical world component that can measure the light level.

Properties

Available
Specifies whether or not the device has the hardware to support the LightSensor component.
AverageLux
Returns the brightness in lux by averaging the previous 10 measured values. The sensor must be enabled and available to return meaningful values.
Enabled
Specifies whether the sensor should generate events. If true, the sensor will generate events. Otherwise, no events are generated.
Lux
Returns the last measured brightness in lux. The sensor must be enabled and available to return meaningful values.
RefreshTime
The requested minimum time in milliseconds between changes in readings being reported. Android is not guaranteed to honor the request. Setting this property has no effect on pre-Gingerbread devices.

Events

LightChanged(lux)
Indicates the light level changed.

Methods

None

LocationSensor

Non-visible component providing location information, including Latitude, Longitude, Altitude (if supported by the device), speed (if supported by the device), and address. This can also perform “geocoding”, converting a given address (not necessarily the current one) to a latitude (with the LatitudeFromAddress method) and a longitude (with the LongitudeFromAddress method).

In order to function, the component must have its Enabled property set to true, and the device must have location sensing enabled through wireless networks or GPS satellites (if outdoors).

Location information might not be immediately available when an app starts. You’ll have to wait a short time for a location provider to be found and used, or wait for the LocationChanged event.

The emulator does not emulate sensors on all devices. Code should be tested on a physical device.

Properties

Accuracy
The LocationSensor will be able to locate the device with a varying degree of confidence, based on the quality of satellite, cell towers, and other data used to estimate location. The Accuracy value is the radius in meters around the sensor’s detected location. The device has a 68% chance to be located within this radius. More precise location detection will result in a smaller accuracy number, which allows the app to have more confidence where the device is actually located.

If the accuracy is not known, the return value is 0.0

Altitude
Altitude of the device measured in meters, if available.

Altitude is measured from the World Geodetic System 84 reference ellipsoid, not sea level.

Note that it is difficult for devices to accurately sense altitude. Altitude reported on a phone/tablet can easily be off by 30 meters or more.

AvailableProviders
List of available service providers, such as gps or network. This information is provided as a list and in text form.
CurrentAddress
Physical street address of the device from Google’s map database.

The address might not always be available from the provider, and the address reported may not always be of the building where the device is located.

If Google has no address information available for a particular location, this will return No address available.

DistanceInterval
Determines the minimum distance interval, in meters, that the sensor will try to use for sending out location updates. For example, if this is set to 50, then the sensor will fire a LocationChanged event only after 50 meters have been traversed. However, the sensor does not guarantee that an update will be received at exactly the distance interval. It may take more than 5 meters to fire an event, for instance.

It is also useful to check against Accuracy when using this property. When your device is moving, the accuracy of the detected location is constantly changing.

Enabled
If true, the LocationSensor will attempt to read location information from GPS, WiFi location, or other means available on the device. This setting does not control whether location information is actually available. Device location must be enabled or disabled in the device settings.
HasAccuracy
If true, the device can report its accuracy level.
HasAltitude
If true, the device can report its altitude.
HasLongitudeLatitude
If true, the device can report longitude and latitude. It is always the case that either both or neither are.
Latitude
The most recently available latitude value in degrees reported to 5 decimal places. If no value is available, 0 will be returned. Latitude is a value between 90 (north) and -90 (south), where 0 marks the Equator.
Longitude
The most recent available longitude value in degrees reported to 5 decimal places. If no value is available, 0 will be returned. Longitude is a value between 180 (east) and -180 (west), where 0 marks the Prime Meridian.
ProviderLocked
The device will not change the service provider.

It is possible for a device to switch service providers when the current provider is unable to provide adequate location information. ProviderLocked is a Boolean value: true/false. Set to true to prevent providers from changing. Set to false to allow for automatic switching when necessary.

ProviderName
The current service provider. The provider will most likely be either GPS or network.
TimeInterval
Determines the minimum time interval, in milliseconds, that the sensor will try to use for sending out location updates. However, location updates will only be received when the location of the phone actually changes, and use of the specified time interval is not guaranteed. For example, if 30000 is used as the time interval, location updates will never be fired sooner than 30000ms, but they may be fired anytime after.

Values smaller than 30000ms (30 seconds) are not practical for most devices. Small values may drain battery and overwork the GPS.

Events

LocationChanged(latitude,longitude,altitude,speed)
Indicates that a new location has been detected. Speed is reported in meters/second Other values match their properties.
StatusChanged(provider,status)
Indicates that the status of the location provider service has changed, such as when a provider is lost or a new provider starts being used.

Methods

LatitudeFromAddress(locationName)
Derives latitude from the given locationName.
LongitudeFromAddress(locationName)
Derives longitude from the given locationName.

MagneticFieldSensor

Component for MagneticFieldSensor

Properties

AbsoluteStrength
Indicates the absolute strength of the field.
Available
Indicates that there is a magnetic field sensor in the device and it is available.
Enabled
Indicates whether or not the magnetic field sensor is enabled and working.
MaximumRange
Indicates the maximum range the magnetic sensor can reach.
XStrength
Indicates the field’s strength in the X-axis.
YStrength
Indicates the field’s strength in the Y-axis.
ZStrength
Indicates the field’s strength in the Z-axis.

Events

MagneticChanged(xStrength,yStrength,zStrength,absoluteStrength)
Triggers when magnetic field has changed, setting the new values in parameters.

Methods

None

NearField

Non-visible component to provide NFC capabilities. For now this component supports the reading and writing of text tags only (if supported by the device).

In order to read and write text tags, the component must have its ReadMode property set to true or false respectively.

Note: This component will only work on Screen1 of any App Inventor app.

Properties

LastMessage
Returns the content of the most recently received tag.
ReadMode
Specifies whether the NFC hardware should operate in read mode (true) or write mode (false).
TextToWrite
Specifies the content that will be written to the tag when in write mode. This method has no effect if ReadMode is true.
WriteType
Returns the write type for the NFC component. For this version of the component, it is always 1.

Events

TagRead(message)
Indicates that a new tag has been detected. Currently this is only a plain text tag, as specified in the manifest.
TagWritten()
Indicates that a tag has come into range of the NFC sensor and has been written.

Methods

None

OrientationSensor

Example of the OrientationSensor icon

Use an orientation sensor component to determine the phone’s spatial orientation.

An orientation sensor is a non-visible component that reports the following three values, in degrees:

  • Roll : 0 degree when the device is level, increasing to 90 degrees as the device is tilted up onto its left side, and decreasing to −90 degrees when the device is tilted up onto its right side.
  • Pitch : 0 degree when the device is level, increasing to 90 degrees as the device is tilted so its top is pointing down, then decreasing to 0 degree as it gets turned over. Similarly, as the device is tilted so its bottom points down, pitch decreases to −90 degrees, then increases to 0 degree as it gets turned all the way over.
  • Azimuth : 0 degree when the top of the device is pointing north, 90 degrees when it is pointing east, 180 degrees when it is pointing south, 270 degrees when it is pointing west, etc.

These measurements assume that the device itself is not moving.

Properties

Angle
Returns an angle that tells the direction in which the device is tiled. That is, it tells the direction of the force that would be felt by a ball rolling on the surface of the device.
Available
Indicates whether the orientation sensor is present on the device.
Azimuth
Returns the azimuth angle of the device. To return meaningful values the sensor must be enabled.
Enabled
Specifies whether the orientation sensor is enabled.
Magnitude
Returns a number between 0 and 1 indicating how much the device is tilted. It gives the magnitude of the force that would be felt by a ball rolling on the surface of the device. For the angle of tilt, use Angle.
Pitch
Returns the pitch angle of the device. To return meaningful values the sensor must be enabled.
Roll
Returns the roll angle of the device. To return meaningful values the sensor must be enabled.

Events

OrientationChanged(azimuth,pitch,roll)
The OrientationChanged event handler is run when the orientation has changed.

Methods

None

Pedometer

This component keeps count of steps using the accelerometer.

Properties

Distance
Returns the approximate distance traveled in meters.
ElapsedTime
Returns the time elapsed in milliseconds since the pedometer has started.
SimpleSteps
Returns the number of simple steps taken since the pedometer has started.
StopDetectionTimeout
Returns the duration of idleness (no steps detected) after which to go into a “stopped” state.
StrideLength
Returns the current estimate of stride length in meters, if calibrated, or returns the default (0.73 m) otherwise.
WalkSteps
Returns the number of walk steps taken since the pedometer has started.

Events

SimpleStep(simpleSteps,distance)
This event is run when a raw step is detected.
WalkStep(walkSteps,distance)
This event is run when a walking step is detected. A walking step is a step that appears to be involved in forward motion.

Methods

Reset()
Resets the step counter, distance measure and time running.
Save()
Saves the pedometer state to the phone. Permits permits accumulation of steps and distance between invocations of an App that uses the pedometer. Different Apps will have their own saved state.
Start()
Starts the pedometer.
Stop()
Stops the pedometer.

ProximitySensor

A sensor component that can measure the proximity of an object (in cm) relative to the view screen of a device. This sensor is typically used to determine whether a handset is being held up to a persons ear; i.e. lets you determine how far away an object is from a device. Many devices return the absolute distance, in cm, but some return only near and far values. In this case, the sensor usually reports its maximum range value in the far state and a lesser value in the near state. It reports the following value:

  • Distance: The distance from the object to the device

Properties

Available
Reports whether or not the device has a proximity sensor.
Distance
Returns the distance from the object to the device. The sensor must be enabled to return meaningful values.
Enabled
If true, the sensor will generate events. Otherwise, no events are generated.
KeepRunningWhenOnPause
Returns value of keepRunningWhenOnPause.
MaximumRange
Determines a sensor’s maximum range. Some proximity sensors return binary values that represent “near” or “far.” In this case, the sensor usually reports its maximum range value in the far state and a lesser value in the near state. Typically, the far value is a value > 5 cm, but this can vary from sensor to sensor.

Events

ProximityChanged(distance)
Triggered when distance (in cm) of the object to the device changes.

Methods

None

Thermometer

Physical world component that can measure the ambient air temperature if supported by the hardware.

Properties

Available
Specifies whether or not the device has the hardware to support the Thermometer component.
Enabled
Specifies whether the sensor should generate events. If true, the sensor will generate events. Otherwise, no events are generated.
RefreshTime
The requested minimum time in milliseconds between changes in readings being reported. Android is not guaranteed to honor the request. Setting this property has no effect on pre-Gingerbread devices.
Temperature
Returns the temperature in degrees Celsius. The sensor must be enabled and available to return meaningful values.

Events

TemperatureChanged(temperature)
Indicates a change of temperature, provided in degrees Celsius.

Methods

None