text,length,is_long_context,metric_val,label_metric "/* Feathers Copyright 2012-2016 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.controls.text.ITextEditorViewPort; import feathers.controls.text.TextFieldTextEditorViewPort; import feathers.core.IAdvancedNativeFocusOwner; import feathers.core.IFeathersControl; import feathers.core.IMeasureDisplayObject; import feathers.core.INativeFocusOwner; import feathers.core.IStateContext; import feathers.core.IStateObserver; import feathers.core.PopUpManager; import feathers.core.PropertyProxy; import feathers.events.FeathersEventType; import feathers.skins.IStyleProvider; import flash.geom.Point; import flash.ui.Mouse; import flash.ui.MouseCursor; import starling.display.DisplayObject; import starling.events.Event; import starling.events.KeyboardEvent; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; /** * Dispatched when the text area's text property changes. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Dispatched when the display object's state changes. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType feathers.events.FeathersEventType.STATE_CHANGE * * @see #currentState */ [Event(name=""stateChange"",type=""starling.events.Event"")] /** * A text entry control that allows users to enter and edit multiple lines * of uniformly-formatted text with the ability to scroll. * *

The following example sets the text in a text area, selects the text, * and listens for when the text value changes:

* * * var textArea:TextArea = new TextArea(); * textArea.text = ""Hello\\nWorld""; //it's multiline! * textArea.selectRange( 0, textArea.text.length ); * textArea.addEventListener( Event.CHANGE, textArea_changeHandler ); * this.addChild( textArea ); * * @see ../../../help/text-area.html How to use the Feathers TextArea component * @see feathers.controls.TextInput */ public class TextArea extends Scroller implements IAdvancedNativeFocusOwner, IStateContext { /** * @private */ private static const HELPER_POINT:Point = new Point(); /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollPolicy.AUTO. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_POLICY_AUTO:String = ""auto""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollPolicy.ON. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_POLICY_ON:String = ""on""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollPolicy.OFF. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_POLICY_OFF:String = ""off""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollBarDisplayMode.FLOAT. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_BAR_DISPLAY_MODE_FLOAT:String = ""float""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollBarDisplayMode.FIXED. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_BAR_DISPLAY_MODE_FIXED:String = ""fixed""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollBarDisplayMode.FIXED_FLOAT. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_BAR_DISPLAY_MODE_FIXED_FLOAT:String = ""fixedFloat""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollBarDisplayMode.NONE. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const SCROLL_BAR_DISPLAY_MODE_NONE:String = ""none""; /** * @private * DEPRECATED: Replaced by feathers.layout.RelativePosition.RIGHT. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const VERTICAL_SCROLL_BAR_POSITION_RIGHT:String = ""right""; /** * @private * DEPRECATED: Replaced by feathers.layout.RelativePosition.LEFT. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const VERTICAL_SCROLL_BAR_POSITION_LEFT:String = ""left""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollInteractionMode.TOUCH. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const INTERACTION_MODE_TOUCH:String = ""touch""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollInteractionMode.MOUSE. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const INTERACTION_MODE_MOUSE:String = ""mouse""; /** * @private * DEPRECATED: Replaced by feathers.controls.ScrollInteractionMode.TOUCH_AND_SCROLL_BARS. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const INTERACTION_MODE_TOUCH_AND_SCROLL_BARS:String = ""touchAndScrollBars""; /** * @private * DEPRECATED: Replaced by feathers.layout.Direction.VERTICAL. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const MOUSE_WHEEL_SCROLL_DIRECTION_VERTICAL:String = ""vertical""; /** * @private * DEPRECATED: Replaced by feathers.layout.Direction.HORIZONTAL. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const MOUSE_WHEEL_SCROLL_DIRECTION_HORIZONTAL:String = ""horizontal""; /** * @private * DEPRECATED: Replaced by feathers.controls.DecelerationRate.NORMAL. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const DECELERATION_RATE_NORMAL:Number = 0.998; /** * @private * DEPRECATED: Replaced by feathers.controls.DecelerationRate.FAST. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const DECELERATION_RATE_FAST:Number = 0.99; /** * @private * DEPRECATED: Replaced by feathers.controls.TextInputState.ENABLED. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const STATE_ENABLED:String = ""enabled""; /** * @private * DEPRECATED: Replaced by feathers.controls.TextInputState.DISABLED. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const STATE_DISABLED:String = ""disabled""; /** * @private * DEPRECATED: Replaced by feathers.controls.TextInputState.FOCUSED. * *

DEPRECATION WARNING: This constant is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public static const STATE_FOCUSED:String = ""focused""; /** * The default value added to the styleNameList of the text * editor. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_TEXT_EDITOR:String = ""feathers-text-area-text-editor""; /** * The default value added to the styleNameList of the * error callout. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_ERROR_CALLOUT:String = ""feathers-text-input-error-callout""; /** * @private */ protected static const INVALIDATION_FLAG_ERROR_CALLOUT_FACTORY:String = ""errorCalloutFactory""; /** * The default IStyleProvider for all TextArea * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * Constructor. */ public function TextArea() { super(); this._measureViewPort = false; this.addEventListener(TouchEvent.TOUCH, textArea_touchHandler); this.addEventListener(Event.REMOVED_FROM_STAGE, textArea_removedFromStageHandler); } /** * @private */ protected var textEditorViewPort:ITextEditorViewPort; /** * The TextCallout that displays the value of the * errorString property. The value may be null * if there is no current error string or if the text area doesn't have * focus. * *

For internal use in subclasses.

*/ protected var callout:TextCallout; /** * The value added to the styleNameList of the text editor. * This variable is protected so that sub-classes can * customize the text editor style name in their constructors instead of * using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_TEXT_EDITOR. * * @see feathers.core.FeathersControl#styleNameList */ protected var textEditorStyleName:String = DEFAULT_CHILD_STYLE_NAME_TEXT_EDITOR; /** * The value added to the styleNameList of the error * callout. This variable is protected so that sub-classes * can customize the prompt text renderer style name in their * constructors instead of using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_ERROR_CALLOUT. * * @see feathers.core.FeathersControl#styleNameList */ protected var errorCalloutStyleName:String = DEFAULT_CHILD_STYLE_NAME_ERROR_CALLOUT; /** * @private */ protected var _textEditorHasFocus:Boolean = false; /** * A text editor may be an INativeFocusOwner, so we need to * return the value of its nativeFocus property. If not, * then we return null. * * @see feathers.core.INativeFocusOwner */ public function get nativeFocus():Object { if(this.textEditorViewPort is INativeFocusOwner) { return INativeFocusOwner(this.textEditorViewPort).nativeFocus; } return null; } /** * @private */ protected var _isWaitingToSetFocus:Boolean = false; /** * @private */ protected var _pendingSelectionStartIndex:int = -1; /** * @private */ protected var _pendingSelectionEndIndex:int = -1; /** * @private */ protected var _textAreaTouchPointID:int = -1; /** * @private */ protected var _oldMouseCursor:String = null; /** * @private */ protected var _ignoreTextChanges:Boolean = false; /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return TextArea.globalStyleProvider; } /** * @private */ override public function get isFocusEnabled():Boolean { if(this._isEditable) { //the behavior is different when editable. return this._isEnabled && this._isFocusEnabled; } return super.isFocusEnabled; } /** * When the FocusManager isn't enabled, hasFocus * can be used instead of FocusManager.focus == textArea * to determine if the text area has focus. */ public function get hasFocus():Boolean { if(!this._focusManager) { return this._textEditorHasFocus; } return this._hasFocus; } /** * @private */ override public function set isEnabled(value:Boolean):void { super.isEnabled = value; this.refreshState(); } /** * @private */ protected var _currentState:String = TextInputState.ENABLED; /** * The current state of the text area. * * @see feathers.controls.TextInputState * @see #event:stateChange feathers.events.FeathersEventType.STATE_CHANGE */ public function get currentState():String { return this._currentState; } /** * @private */ protected var _text:String = """"; /** * The text displayed by the text area. The text area dispatches * Event.CHANGE when the value of the text * property changes for any reason. * *

In the following example, the text area's text is updated:

* * * textArea.text = ""Hello World""; * * @see #event:change * * @default """" */ public function get text():String { return this._text; } /** * @private */ public function set text(value:String):void { if(!value) { //don't allow null or undefined value = """"; } if(this._text == value) { return; } this._text = value; this.invalidate(INVALIDATION_FLAG_DATA); this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _maxChars:int = 0; /** * The maximum number of characters that may be entered. * *

In the following example, the text area's maximum characters is * specified:

* * * textArea.maxChars = 10; * * @default 0 */ public function get maxChars():int { return this._maxChars; } /** * @private */ public function set maxChars(value:int):void { if(this._maxChars == value) { return; } this._maxChars = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _restrict:String; /** * Limits the set of characters that may be entered. * *

In the following example, the text area's allowed characters are * restricted:

* * * textArea.restrict = ""0-9; * * @default null */ public function get restrict():String { return this._restrict; } /** * @private */ public function set restrict(value:String):void { if(this._restrict == value) { return; } this._restrict = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _isEditable:Boolean = true; /** * Determines if the text area is editable. If the text area is not * editable, it will still appear enabled. * *

In the following example, the text area is not editable:

* * * textArea.isEditable = false; * * @default true */ public function get isEditable():Boolean { return this._isEditable; } /** * @private */ public function set isEditable(value:Boolean):void { if(this._isEditable == value) { return; } this._isEditable = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _errorString:String = null; /** * Error text to display in a Callout when the text area * has focus. When this value is not null the text area's * state is changed to TextInputState.ERROR. * * An empty string will change the background, but no * Callout will appear on focus. * * To clear an error, the errorString property must be set * to null * *

The following example displays an error string:

* * * textArea.errorString = ""Something is wrong""; * * @default null * * @see #currentState */ public function get errorString():String { return this._errorString; } /** * @private */ public function set errorString(value:String):void { if(this._errorString === value) { return; } this._errorString = value; this.refreshState(); this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _stateToSkin:Object = {}; /** * A display object displayed behind the text area's content when it * is disabled. * *

In the following example, the text area's disabled background skin * is specified:

* * * textArea.isEnabled = false; * textArea.backgroundDisabledSkin = new Image( texture ); * * @default null */ override public function get backgroundDisabledSkin():DisplayObject { return this.getSkinForState(TextInputState.DISABLED); } /** * @private */ override public function set backgroundDisabledSkin(value:DisplayObject):void { this.setSkinForState(TextInputState.DISABLED, value); } /** * A display object displayed behind the text area's content when it * has focus. * *

In the following example, the text area's focused background skin is * specified:

* * * textArea.backgroundFocusedSkin = new Image( texture ); * * @default null */ public function get backgroundFocusedSkin():DisplayObject { return this.getSkinForState(TextInputState.FOCUSED); } /** * @private */ public function set backgroundFocusedSkin(value:DisplayObject):void { this.setSkinForState(TextInputState.FOCUSED, value); } /** * The skin used for the text area's error state. If null, * then backgroundSkin is used instead. * *

The following example gives the text area a skin for the error state:

* * * textArea.backgroundErrorSkin = new Image( texture ); * * @default null */ public function get backgroundErrorSkin():DisplayObject { return this.getSkinForState(TextInputState.ERROR); } /** * @private */ public function set backgroundErrorSkin(value:DisplayObject):void { this.setSkinForState(TextInputState.ERROR, value); } /** * @private */ protected var _stateToSkinFunction:Function; /** * DEPRECATED: Create a feathers.skins.ImageSkin instead, * and pass to the backgroundSkin property. * *

DEPRECATION WARNING: This property is deprecated * starting with Feathers 3.0. It will be removed in a future version of * Feathers according to the standard * Feathers deprecation policy.

*/ public function get stateToSkinFunction():Function { return this._stateToSkinFunction; } /** * @private */ public function set stateToSkinFunction(value:Function):void { if(this._stateToSkinFunction == value) { return; } this._stateToSkinFunction = value; this.invalidate(INVALIDATION_FLAG_SKIN); } /** * @private */ protected var _textEditorFactory:Function; /** * A function used to instantiate the text editor view port. If * null, a TextFieldTextEditorViewPort will * be instantiated. The text editor must be an instance of * ITextEditorViewPort. This factory can be used to change * properties on the text editor view port when it is first created. For * instance, if you are skinning Feathers components without a theme, * you might use this factory to set styles on the text editor view * port. * *

The factory should have the following function signature:

*
function():ITextEditorViewPort
* *

In the following example, a custom text editor factory is passed * to the text area:

* * * textArea.textEditorFactory = function():ITextEditorViewPort * { * return new TextFieldTextEditorViewPort(); * }; * * @default null * * @see feathers.controls.text.ITextEditorViewPort */ public function get textEditorFactory():Function { return this._textEditorFactory; } /** * @private */ public function set textEditorFactory(value:Function):void { if(this._textEditorFactory == value) { return; } this._textEditorFactory = value; this.invalidate(INVALIDATION_FLAG_TEXT_EDITOR); } /** * @private */ protected var _customTextEditorStyleName:String; /** * A style name to add to the text area's text editor sub-component. * Typically used by a theme to provide different styles to different * text areas. * *

In the following example, a custom text editor style name is * passed to the text area:

* * * textArea.customTextEditorStyleName = ""my-custom-text-area-text-editor""; * *

In your theme, you can target this sub-component style name to * provide different styles than the default:

* * * getStyleProviderForClass( TextFieldTextEditorViewPort ).setFunctionForStyleName( ""my-custom-text-area-text-editor"", setCustomTextAreaTextEditorStyles ); * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_TEXT_EDITOR * @see feathers.core.FeathersControl#styleNameList * @see #textEditorFactory */ public function get customTextEditorStyleName():String { return this._customTextEditorStyleName; } /** * @private */ public function set customTextEditorStyleName(value:String):void { if(this._customTextEditorStyleName == value) { return; } this._customTextEditorStyleName = value; this.invalidate(INVALIDATION_FLAG_TEXT_RENDERER); } /** * @private */ protected var _textEditorProperties:PropertyProxy; /** * An object that stores properties for the text area's text editor * sub-component, and the properties will be passed down to the * text editor when the text area validates. The available properties * depend on which ITextEditorViewPort implementation is * returned by textEditorFactory. Refer to * feathers.controls.text.ITextEditorViewPort * for a list of available text editor implementations for text area. * *

If the subcomponent has its own subcomponents, their properties * can be set too, using attribute @ notation. For example, * to set the skin on the thumb which is in a SimpleScrollBar, * which is in a List, you can use the following syntax:

*
list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);
* *

Setting properties in a textEditorFactory function * instead of using textEditorProperties will result in * better performance.

* *

In the following example, the text input's text editor properties * are specified (this example assumes that the text editor is a * TextFieldTextEditorViewPort):

* * * textArea.textEditorProperties.textFormat = new TextFormat( ""Source Sans Pro"", 16, 0x333333); * textArea.textEditorProperties.embedFonts = true; * * @default null * * @see #textEditorFactory * @see feathers.controls.text.ITextEditorViewPort */ public function get textEditorProperties():Object { if(!this._textEditorProperties) { this._textEditorProperties = new PropertyProxy(childProperties_onChange); } return this._textEditorProperties; } /** * @private */ public function set textEditorProperties(value:Object):void { if(this._textEditorProperties == value) { return; } if(!value) { value = new PropertyProxy(); } if(!(value is PropertyProxy)) { var newValue:PropertyProxy = new PropertyProxy(); for(var propertyName:String in value) { newValue[propertyName] = value[propertyName]; } value = newValue; } if(this._textEditorProperties) { this._textEditorProperties.removeOnChangeCallback(childProperties_onChange); } this._textEditorProperties = PropertyProxy(value); if(this._textEditorProperties) { this._textEditorProperties.addOnChangeCallback(childProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _customErrorCalloutStyleName:String; /** * A style name to add to the text area's error callout sub-component. * Typically used by a theme to provide different styles to different * text areas. * *

In the following example, a custom error callout style name * is passed to the text area:

* * * textArea.customErrorCalloutStyleName = ""my-custom-text-area-error-callout""; * *

In your theme, you can target this sub-component style name to * provide different styles than the default:

* * * getStyleProviderForClass( Callout ).setFunctionForStyleName( ""my-custom-text-area-error-callout"", setCustomTextAreaErrorCalloutStyles ); * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_ERROR_CALLOUT * @see feathers.core.FeathersControl#styleNameList */ public function get customErrorCalloutStyleName():String { return this._customErrorCalloutStyleName; } /** * @private */ public function set customErrorCalloutStyleName(value:String):void { if(this._customErrorCalloutStyleName == value) { return; } this._customErrorCalloutStyleName = value; this.invalidate(INVALIDATION_FLAG_ERROR_CALLOUT_FACTORY); } /** * @inheritDoc */ override public function showFocus():void { if(!this._focusManager || this._focusManager.focus != this) { return; } this.selectRange(0, this._text.length); super.showFocus(); } /** * Focuses the text area control so that it may be edited. */ public function setFocus():void { if(this._textEditorHasFocus) { return; } if(this.textEditorViewPort) { this._isWaitingToSetFocus = false; this.textEditorViewPort.setFocus(); } else { this._isWaitingToSetFocus = true; this.invalidate(INVALIDATION_FLAG_SELECTED); } } /** * Manually removes focus from the text area control. */ public function clearFocus():void { this._isWaitingToSetFocus = false; if(!this.textEditorViewPort || !this._textEditorHasFocus) { return; } this.textEditorViewPort.clearFocus(); } /** * Sets the range of selected characters. If both values are the same, * or the end index is -1, the text insertion position is * changed and nothing is selected. */ public function selectRange(startIndex:int, endIndex:int = -1):void { if(endIndex < 0) { endIndex = startIndex; } if(startIndex < 0) { throw new RangeError(""Expected start index greater than or equal to 0. Received "" + startIndex + "".""); } if(endIndex > this._text.length) { throw new RangeError(""Expected start index less than "" + this._text.length + "". Received "" + endIndex + "".""); } if(this.textEditorViewPort) { this._pendingSelectionStartIndex = -1; this._pendingSelectionEndIndex = -1; this.textEditorViewPort.selectRange(startIndex, endIndex); } else { this._pendingSelectionStartIndex = startIndex; this._pendingSelectionEndIndex = endIndex; this.invalidate(INVALIDATION_FLAG_SELECTED); } } /** * @private */ override public function dispose():void { //we don't dispose it if the text area is the parent because it'll //already get disposed in super.dispose() for(var state:String in this._stateToSkin) { var skin:DisplayObject = this._stateToSkin[state] as DisplayObject; if(skin !== null && skin.parent !== this) { skin.dispose(); } } super.dispose(); } /** * Gets the skin to be used by the text area when its * currentState property matches the specified state value. * *

If a skin is not defined for a specific state, returns * null.

* * @see #setSkinForState() * @see feathers.controls.TextInputState */ public function getSkinForState(state:String):DisplayObject { return this._stateToSkin[state] as DisplayObject; } /** * Sets the skin to be used by the text area when its * currentState property matches the specified state value. * *

If a skin is not defined for a specific state, the value of the * backgroundSkin property will be used instead.

* * @see #backgroundSkin * @see #getSkinForState() * @see feathers.controls.TextInputState */ public function setSkinForState(state:String, skin:DisplayObject):void { if(skin !== null) { this._stateToSkin[state] = skin; } else { delete this._stateToSkin[state]; } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ override protected function draw():void { var textEditorInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_TEXT_EDITOR); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); if(textEditorInvalid) { this.createTextEditor(); } if(textEditorInvalid || stylesInvalid) { this.refreshTextEditorProperties(); } if(textEditorInvalid || dataInvalid) { var oldIgnoreTextChanges:Boolean = this._ignoreTextChanges; this._ignoreTextChanges = true; this.textEditorViewPort.text = this._text; this._ignoreTextChanges = oldIgnoreTextChanges; } if(textEditorInvalid || stateInvalid) { this.textEditorViewPort.isEnabled = this._isEnabled; if(!this._isEnabled && Mouse.supportsNativeCursor && this._oldMouseCursor) { Mouse.cursor = this._oldMouseCursor; this._oldMouseCursor = null; } } super.draw(); this.doPendingActions(); } /** * Creates and adds the textEditorViewPort sub-component and * removes the old instance, if one exists. * *

Meant for internal use, and subclasses may override this function * with a custom implementation.

* * @see #textEditorViewPort * @see #textEditorFactory */ protected function createTextEditor():void { if(this.textEditorViewPort) { this.textEditorViewPort.removeEventListener(Event.CHANGE, textEditor_changeHandler); this.textEditorViewPort.removeEventListener(FeathersEventType.FOCUS_IN, textEditor_focusInHandler); this.textEditorViewPort.removeEventListener(FeathersEventType.FOCUS_OUT, textEditor_focusOutHandler); this.textEditorViewPort = null; } if(this._textEditorFactory != null) { this.textEditorViewPort = ITextEditorViewPort(this._textEditorFactory()); } else { this.textEditorViewPort = new TextFieldTextEditorViewPort(); } var textEditorStyleName:String = this._customTextEditorStyleName != null ? this._customTextEditorStyleName : this.textEditorStyleName; this.textEditorViewPort.styleNameList.add(textEditorStyleName); if(this.textEditorViewPort is IStateObserver) { IStateObserver(this.textEditorViewPort).stateContext = this; } this.textEditorViewPort.addEventListener(Event.CHANGE, textEditor_changeHandler); this.textEditorViewPort.addEventListener(FeathersEventType.FOCUS_IN, textEditor_focusInHandler); this.textEditorViewPort.addEventListener(FeathersEventType.FOCUS_OUT, textEditor_focusOutHandler); var oldViewPort:ITextEditorViewPort = ITextEditorViewPort(this._viewPort); this.viewPort = this.textEditorViewPort; if(oldViewPort) { //the view port setter won't do this oldViewPort.dispose(); } } /** * @private */ protected function createErrorCallout():void { if(this.callout) { this.callout.removeFromParent(true); this.callout = null; } if(this._errorString === null) { return; } this.callout = new TextCallout(); var errorCalloutStyleName:String = this._customErrorCalloutStyleName != null ? this._customErrorCalloutStyleName : this.errorCalloutStyleName; this.callout.styleNameList.add(errorCalloutStyleName); this.callout.closeOnKeys = null; this.callout.closeOnTouchBeganOutside = false; this.callout.closeOnTouchEndedOutside = false; this.callout.touchable = false; this.callout.text = this._errorString; this.callout.origin = this; PopUpManager.addPopUp(this.callout, false, false); } /** * @private */ protected function changeState(state:String):void { if(this._currentState === state) { return; } this._currentState = state; this.invalidate(INVALIDATION_FLAG_STATE); this.dispatchEventWith(FeathersEventType.STATE_CHANGE); } /** * @private */ protected function doPendingActions():void { if(this._isWaitingToSetFocus || (this._focusManager && this._focusManager.focus == this)) { this._isWaitingToSetFocus = false; if(!this._textEditorHasFocus) { this.textEditorViewPort.setFocus(); } } if(this._pendingSelectionStartIndex >= 0) { var startIndex:int = this._pendingSelectionStartIndex; var endIndex:int = this._pendingSelectionEndIndex; this._pendingSelectionStartIndex = -1; this._pendingSelectionEndIndex = -1; this.selectRange(startIndex, endIndex); } } /** * @private */ protected function refreshTextEditorProperties():void { this.textEditorViewPort.maxChars = this._maxChars; this.textEditorViewPort.restrict = this._restrict; this.textEditorViewPort.isEditable = this._isEditable; for(var propertyName:String in this._textEditorProperties) { var propertyValue:Object = this._textEditorProperties[propertyName]; this.textEditorViewPort[propertyName] = propertyValue; } } /** * @private */ override protected function refreshBackgroundSkin():void { var oldSkin:DisplayObject = this.currentBackgroundSkin; this.currentBackgroundSkin = this.getCurrentSkin(); if(oldSkin !== this.currentBackgroundSkin) { if(oldSkin !== null) { if(oldSkin is IStateObserver) { IStateObserver(oldSkin).stateContext = null; } this.removeChild(oldSkin, false); } if(this.currentBackgroundSkin !== null) { if(this.currentBackgroundSkin is IStateObserver) { IStateObserver(this.currentBackgroundSkin).stateContext = this; } this.addChildAt(this.currentBackgroundSkin, 0); if(this.currentBackgroundSkin is IFeathersControl) { IFeathersControl(this.currentBackgroundSkin).initializeNow(); } if(this.currentBackgroundSkin is IMeasureDisplayObject) { var measureSkin:IMeasureDisplayObject = IMeasureDisplayObject(this.currentBackgroundSkin); this._explicitBackgroundWidth = measureSkin.explicitWidth; this._explicitBackgroundHeight = measureSkin.explicitHeight; this._explicitBackgroundMinWidth = measureSkin.explicitMinWidth; this._explicitBackgroundMinHeight = measureSkin.explicitMinHeight; } else { this._explicitBackgroundWidth = this.currentBackgroundSkin.width; this._explicitBackgroundHeight = this.currentBackgroundSkin.height; this._explicitBackgroundMinWidth = this._explicitBackgroundWidth; this._explicitBackgroundMinHeight = this._explicitBackgroundHeight; } } } } /** * @private */ protected function getCurrentSkin():DisplayObject { if(this._stateToSkinFunction != null) { return DisplayObject(this._stateToSkinFunction(this, this._currentState, this.currentBackgroundSkin)); } var result:DisplayObject = this._stateToSkin[this._currentState] as DisplayObject; if(result !== null) { return result; } return this._backgroundSkin; } /** * @private */ protected function refreshState():void { if(this._isEnabled) { if(this._textEditorHasFocus) { this.changeState(TextInputState.FOCUSED); } else if(this._errorString !== null) { this.changeState(TextInputState.ERROR); } else { this.changeState(TextInputState.ENABLED); } } else { this.changeState(TextInputState.DISABLED); } } /** * @private */ protected function setFocusOnTextEditorWithTouch(touch:Touch):void { if(!this.isFocusEnabled) { return; } touch.getLocation(this.stage, HELPER_POINT); var isInBounds:Boolean = this.contains(this.stage.hitTest(HELPER_POINT)); if(!this._textEditorHasFocus && isInBounds) { this.globalToLocal(HELPER_POINT, HELPER_POINT); HELPER_POINT.x -= this._paddingLeft; HELPER_POINT.y -= this._paddingTop; //we account for the scroll position in the text editor view //port, so don't do it here! this._isWaitingToSetFocus = false; this.textEditorViewPort.setFocus(HELPER_POINT); } } /** * @private */ protected function textArea_touchHandler(event:TouchEvent):void { if(!this._isEnabled) { this._textAreaTouchPointID = -1; return; } var horizontalScrollBar:DisplayObject = DisplayObject(this.horizontalScrollBar); var verticalScrollBar:DisplayObject = DisplayObject(this.verticalScrollBar); if(this._textAreaTouchPointID >= 0) { var touch:Touch = event.getTouch(this, TouchPhase.ENDED, this._textAreaTouchPointID); if(!touch || touch.isTouching(verticalScrollBar) || touch.isTouching(horizontalScrollBar)) { return; } this.removeEventListener(Event.SCROLL, textArea_scrollHandler); this._textAreaTouchPointID = -1; if(this.textEditorViewPort.setTouchFocusOnEndedPhase) { this.setFocusOnTextEditorWithTouch(touch); } } else { touch = event.getTouch(this, TouchPhase.BEGAN); if(touch) { if(touch.isTouching(verticalScrollBar) || touch.isTouching(horizontalScrollBar)) { return; } this._textAreaTouchPointID = touch.id; if(!this.textEditorViewPort.setTouchFocusOnEndedPhase) { this.setFocusOnTextEditorWithTouch(touch); } this.addEventListener(Event.SCROLL, textArea_scrollHandler); return; } touch = event.getTouch(this, TouchPhase.HOVER); if(touch) { if(touch.isTouching(verticalScrollBar) || touch.isTouching(horizontalScrollBar)) { return; } if(Mouse.supportsNativeCursor && !this._oldMouseCursor) { this._oldMouseCursor = Mouse.cursor; Mouse.cursor = MouseCursor.IBEAM; } return; } //end hover if(Mouse.supportsNativeCursor && this._oldMouseCursor) { Mouse.cursor = this._oldMouseCursor; this._oldMouseCursor = null; } } } /** * @private */ protected function textArea_scrollHandler(event:Event):void { this.removeEventListener(Event.SCROLL, textArea_scrollHandler); this._textAreaTouchPointID = -1; } /** * @private */ protected function textArea_removedFromStageHandler(event:Event):void { if(!this._focusManager && this._textEditorHasFocus) { this.clearFocus(); } this._isWaitingToSetFocus = false; this._textEditorHasFocus = false; this._textAreaTouchPointID = -1; this.removeEventListener(Event.SCROLL, textArea_scrollHandler); if(Mouse.supportsNativeCursor && this._oldMouseCursor) { Mouse.cursor = this._oldMouseCursor; this._oldMouseCursor = null; } } /** * @private */ override protected function focusInHandler(event:Event):void { if(!this._focusManager) { return; } super.focusInHandler(event); this.setFocus(); } /** * @private */ override protected function focusOutHandler(event:Event):void { if(!this._focusManager) { return; } super.focusOutHandler(event); this.textEditorViewPort.clearFocus(); this.invalidate(INVALIDATION_FLAG_STATE); } /** * @private */ override protected function stage_keyDownHandler(event:KeyboardEvent):void { if(this._isEditable) { return; } super.stage_keyDownHandler(event); } /** * @private */ protected function textEditor_changeHandler(event:Event):void { if(this._ignoreTextChanges) { return; } this.text = this.textEditorViewPort.text; } /** * @private */ protected function textEditor_focusInHandler(event:Event):void { this._textEditorHasFocus = true; this.refreshState(); if(this._errorString !== null && this._errorString.length > 0) { this.createErrorCallout(); } this._touchPointID = -1; this.invalidate(INVALIDATION_FLAG_STATE); if(this._focusManager && this.isFocusEnabled && this._focusManager.focus !== this) { //if setFocus() was called manually, we need to notify the focus //manager (unless isFocusEnabled is false). //if the focus manager already knows that we have focus, it will //simply return without doing anything. this._focusManager.focus = this; } else if(!this._focusManager) { this.dispatchEventWith(FeathersEventType.FOCUS_IN); } } /** * @private */ protected function textEditor_focusOutHandler(event:Event):void { this._textEditorHasFocus = false; this.refreshState(); if(this.callout) { this.callout.removeFromParent(true); this.callout = null; } this.invalidate(INVALIDATION_FLAG_STATE); if(this._focusManager && this._focusManager.focus === this) { //if clearFocus() was called manually, we need to notify the //focus manager if it still thinks we have focus. this._focusManager.focus = null; } else if(!this._focusManager) { this.dispatchEventWith(FeathersEventType.FOCUS_OUT); } } } } ",12508,False,2428.5485741679067,median "CLASS zcl_odata_service_dpc_ext DEFINITION PUBLIC INHERITING FROM zcl_odata_service_dpc CREATE PUBLIC . PUBLIC SECTION. CONSTANTS gv_refresh_message TYPE string VALUE `{""action"": ""refresh""}`. CLASS-METHODS populate_db. PROTECTED SECTION. CLASS-METHODS send_refresh. METHODS categorys_get_entity REDEFINITION . METHODS categorys_get_entityset REDEFINITION . METHODS currencys_get_entity REDEFINITION . METHODS currencys_get_entityset REDEFINITION . METHODS products_create_entity REDEFINITION . METHODS products_delete_entity REDEFINITION . METHODS products_get_entity REDEFINITION . METHODS products_get_entityset REDEFINITION . METHODS products_update_entity REDEFINITION . METHODS weightunits_get_entity REDEFINITION . METHODS weightunits_get_entityset REDEFINITION . PRIVATE SECTION. ENDCLASS. CLASS zcl_odata_service_DPC_EXT IMPLEMENTATION. METHOD categorys_get_entity. DATA: ls_converted_keys LIKE er_entity, ls_source_keys TYPE zcl_odata_service_mpc=>ts_product. IF io_tech_request_context->get_source_entity_set_name( ) = 'Products'. io_tech_request_context->get_converted_source_keys( IMPORTING es_key_values = ls_source_keys ). SELECT SINGLE * FROM zdemo_epm_ws_prd AS prd INNER JOIN zdemo_epm_ws_cat AS cat ON prd~category = cat~id INTO CORRESPONDING FIELDS OF @er_entity WHERE prd~id = @ls_source_keys-id. ELSE. io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_converted_keys ). SELECT SINGLE * FROM zdemo_epm_ws_cat INTO CORRESPONDING FIELDS OF @er_entity WHERE id = @ls_converted_keys-id. ENDIF. IF sy-subrc <> 0. me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling( EXPORTING iv_subrc = sy-subrc iv_exp_message_text = 'Entity not found.'(001) ). ENDIF. ENDMETHOD. METHOD categorys_get_entityset. IF line_exists( it_filter_select_options[ property = `NAME` ] ). DATA(lt_select_opts) = it_filter_select_options[ property = `NAME` ]-select_options. SELECT * FROM zdemo_epm_ws_cat INTO CORRESPONDING FIELDS OF TABLE @et_entityset WHERE name IN @lt_select_opts. ELSE. SELECT * FROM zdemo_epm_ws_cat INTO CORRESPONDING FIELDS OF TABLE @et_entityset. ENDIF. ENDMETHOD. METHOD currencys_get_entity. DATA: ls_converted_keys LIKE er_entity, ls_source_keys TYPE zcl_odata_service_mpc=>ts_product. IF io_tech_request_context->get_source_entity_set_name( ) = 'Products'. io_tech_request_context->get_converted_source_keys( IMPORTING es_key_values = ls_source_keys ). SELECT SINGLE * FROM zdemo_epm_ws_prd AS prd INNER JOIN zdemo_epm_ws_crr AS crr ON prd~currency = crr~code INTO CORRESPONDING FIELDS OF @er_entity WHERE prd~id = @ls_source_keys-id. ELSE. io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_converted_keys ). SELECT SINGLE * FROM zdemo_epm_ws_crr INTO CORRESPONDING FIELDS OF @er_entity WHERE code = @ls_converted_keys-code. ENDIF. IF sy-subrc <> 0. me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling( EXPORTING iv_subrc = sy-subrc iv_exp_message_text = 'Entity not found.'(001) ). ENDIF. ENDMETHOD. METHOD currencys_get_entityset. IF line_exists( it_filter_select_options[ property = `CODE` ] ). DATA(lt_select_opts) = it_filter_select_options[ property = `CODE` ]-select_options. SELECT * FROM zdemo_epm_ws_crr INTO CORRESPONDING FIELDS OF TABLE @et_entityset WHERE code IN @lt_select_opts. ELSE. SELECT * FROM zdemo_epm_ws_crr INTO CORRESPONDING FIELDS OF TABLE @et_entityset. ENDIF. ENDMETHOD. METHOD populate_db. DATA: lt_cat TYPE STANDARD TABLE OF zdemo_epm_ws_cat WITH EMPTY KEY, lt_crr TYPE STANDARD TABLE OF zdemo_epm_ws_crr WITH EMPTY KEY, lt_wgu TYPE STANDARD TABLE OF zdemo_epm_ws_wgu WITH EMPTY KEY, lt_prd TYPE STANDARD TABLE OF zdemo_epm_ws_prd WITH EMPTY KEY. lt_crr = VALUE #( ( code = 'AED' description = 'United Arab Emirates Dirham' ) ( code = 'AFN' description = 'Afghanistan Afghani' ) ( code = 'ALL' description = 'Albania Lek' ) ( code = 'AMD' description = 'Armenia Dram' ) ( code = 'ANG' description = 'Netherlands Antilles Guilder' ) ( code = 'AOA' description = 'Angola Kwanza' ) ( code = 'ARS' description = 'Argentina Peso' ) ( code = 'AUD' description = 'Australia Dollar' ) ( code = 'AWG' description = 'Aruba Guilder' ) ( code = 'AZN' description = 'Azerbaijan New Manat' ) ( code = 'BAM' description = 'Bosnia and Herzegovina Convertible Marka' ) ( code = 'BBD' description = 'Barbados Dollar' ) ( code = 'BDT' description = 'Bangladesh Taka' ) ( code = 'BGN' description = 'Bulgaria Lev' ) ( code = 'BHD' description = 'Bahrain Dinar' ) ( code = 'BIF' description = 'Burundi Franc' ) ( code = 'BMD' description = 'Bermuda Dollar' ) ( code = 'BND' description = 'Brunei Darussalam Dollar' ) ( code = 'BOB' description = 'Bolivia Boliviano' ) ( code = 'BRL' description = 'Brazil Real' ) ( code = 'BSD' description = 'Bahamas Dollar' ) ( code = 'BTN' description = 'Bhutan Ngultrum' ) ( code = 'BWP' description = 'Botswana Pula' ) ( code = 'BYR' description = 'Belarus Ruble' ) ( code = 'BZD' description = 'Belize Dollar' ) ( code = 'CAD' description = 'Canada Dollar' ) ( code = 'CDF' description = 'Congo/Kinshasa Franc' ) ( code = 'CHF' description = 'Switzerland Franc' ) ( code = 'CLP' description = 'Chile Peso' ) ( code = 'CNY' description = 'China Yuan Renminbi' ) ( code = 'COP' description = 'Colombia Peso' ) ( code = 'CRC' description = 'Costa Rica Colon' ) ( code = 'CUC' description = 'Cuba Convertible Peso' ) ( code = 'CUP' description = 'Cuba Peso' ) ( code = 'CVE' description = 'Cape Verde Escudo' ) ( code = 'CZK' description = 'Czech Republic Koruna' ) ( code = 'DJF' description = 'Djibouti Franc' ) ( code = 'DKK' description = 'Denmark Krone' ) ( code = 'DOP' description = 'Dominican Republic Peso' ) ( code = 'DZD' description = 'Algeria Dinar' ) ( code = 'EGP' description = 'Egypt Pound' ) ( code = 'ERN' description = 'Eritrea Nakfa' ) ( code = 'ETB' description = 'Ethiopia Birr' ) ( code = 'EUR' description = 'Euro Member Countries' ) ( code = 'FJD' description = 'Fiji Dollar' ) ( code = 'FKP' description = 'Falkland Islands (Malvinas) Pound' ) ( code = 'GBP' description = 'United Kingdom Pound' ) ( code = 'GEL' description = 'Georgia Lari' ) ( code = 'GGP' description = 'Guernsey Pound' ) ( code = 'GHS' description = 'Ghana Cedi' ) ( code = 'GIP' description = 'Gibraltar Pound' ) ( code = 'GMD' description = 'Gambia Dalasi' ) ( code = 'GNF' description = 'Guinea Franc' ) ( code = 'GTQ' description = 'Guatemala Quetzal' ) ( code = 'GYD' description = 'Guyana Dollar' ) ( code = 'HKD' description = 'Hong Kong Dollar' ) ( code = 'HNL' description = 'Honduras Lempira' ) ( code = 'HRK' description = 'Croatia Kuna' ) ( code = 'HTG' description = 'Haiti Gourde' ) ( code = 'HUF' description = 'Hungary Forint' ) ( code = 'IDR' description = 'Indonesia Rupiah' ) ( code = 'ILS' description = 'Israel Shekel' ) ( code = 'IMP' description = 'Isle of Man Pound' ) ( code = 'INR' description = 'India Rupee' ) ( code = 'IQD' description = 'Iraq Dinar' ) ( code = 'IRR' description = 'Iran Rial' ) ( code = 'ISK' description = 'Iceland Krona' ) ( code = 'JEP' description = 'Jersey Pound' ) ( code = 'JMD' description = 'Jamaica Dollar' ) ( code = 'JOD' description = 'Jordan Dinar' ) ( code = 'JPY' description = 'Japan Yen' ) ( code = 'KES' description = 'Kenya Shilling' ) ( code = 'KGS' description = 'Kyrgyzstan Som' ) ( code = 'KHR' description = 'Cambodia Riel' ) ( code = 'KMF' description = 'Comoros Franc' ) ( code = 'KPW' description = 'Korea (North) Won' ) ( code = 'KRW' description = 'Korea (South) Won' ) ( code = 'KWD' description = 'Kuwait Dinar' ) ( code = 'KYD' description = 'Cayman Islands Dollar' ) ( code = 'KZT' description = 'Kazakhstan Tenge' ) ( code = 'LAK' description = 'Laos Kip' ) ( code = 'LBP' description = 'Lebanon Pound' ) ( code = 'LKR' description = 'Sri Lanka Rupee' ) ( code = 'LRD' description = 'Liberia Dollar' ) ( code = 'LSL' description = 'Lesotho Loti' ) ( code = 'LYD' description = 'Libya Dinar' ) ( code = 'MAD' description = 'Morocco Dirham' ) ( code = 'MDL' description = 'Moldova Leu' ) ( code = 'MGA' description = 'Madagascar Ariary' ) ( code = 'MKD' description = 'Macedonia Denar' ) ( code = 'MMK' description = 'Myanmar (Burma) Kyat' ) ( code = 'MNT' description = 'Mongolia Tughrik' ) ( code = 'MOP' description = 'Macau Pataca' ) ( code = 'MRO' description = 'Mauritania Ouguiya' ) ( code = 'MUR' description = 'Mauritius Rupee' ) ( code = 'MVR' description = 'Maldives (Maldive Islands) Rufiyaa' ) ( code = 'MWK' description = 'Malawi Kwacha' ) ( code = 'MXN' description = 'Mexico Peso' ) ( code = 'MYR' description = 'Malaysia Ringgit' ) ( code = 'MZN' description = 'Mozambique Metical' ) ( code = 'NAD' description = 'Namibia Dollar' ) ( code = 'NGN' description = 'Nigeria Naira' ) ( code = 'NIO' description = 'Nicaragua Cordoba' ) ( code = 'NOK' description = 'Norway Krone' ) ( code = 'NPR' description = 'Nepal Rupee' ) ( code = 'NZD' description = 'New Zealand Dollar' ) ( code = 'OMR' description = 'Oman Rial' ) ( code = 'PAB' description = 'Panama Balboa' ) ( code = 'PEN' description = 'Peru Nuevo Sol' ) ( code = 'PGK' description = 'Papua New Guinea Kina' ) ( code = 'PHP' description = 'Philippines Peso' ) ( code = 'PKR' description = 'Pakistan Rupee' ) ( code = 'PLN' description = 'Poland Zloty' ) ( code = 'PYG' description = 'Paraguay Guarani' ) ( code = 'QAR' description = 'Qatar Riyal' ) ( code = 'RON' description = 'Romania New Leu' ) ( code = 'RSD' description = 'Serbia Dinar' ) ( code = 'RUB' description = 'Russia Ruble' ) ( code = 'RWF' description = 'Rwanda Franc' ) ( code = 'SAR' description = 'Saudi Arabia Riyal' ) ( code = 'SBD' description = 'Solomon Islands Dollar' ) ( code = 'SCR' description = 'Seychelles Rupee' ) ( code = 'SDG' description = 'Sudan Pound' ) ( code = 'SEK' description = 'Sweden Krona' ) ( code = 'SGD' description = 'Singapore Dollar' ) ( code = 'SHP' description = 'Saint Helena Pound' ) ( code = 'SLL' description = 'Sierra Leone Leone' ) ( code = 'SOS' description = 'Somalia Shilling' ) ( code = 'SPL' description = 'Seborga Luigino' ) ( code = 'SRD' description = 'Suriname Dollar' ) ( code = 'STD' description = 'São Tomé and Príncipe Dobra' ) ( code = 'SVC' description = 'El Salvador Colon' ) ( code = 'SYP' description = 'Syria Pound' ) ( code = 'SZL' description = 'Swaziland Lilangeni' ) ( code = 'THB' description = 'Thailand Baht' ) ( code = 'TJS' description = 'Tajikistan Somoni' ) ( code = 'TMT' description = 'Turkmenistan Manat' ) ( code = 'TND' description = 'Tunisia Dinar' ) ( code = 'TOP' description = 'Tonga Pa`anga' ) ( code = 'TRY' description = 'Turkey Lira' ) ( code = 'TTD' description = 'Trinidad and Tobago Dollar' ) ( code = 'TVD' description = 'Tuvalu Dollar' ) ( code = 'TWD' description = 'Taiwan New Dollar' ) ( code = 'TZS' description = 'Tanzania Shilling' ) ( code = 'UAH' description = 'Ukraine Hryvnia' ) ( code = 'UGX' description = 'Uganda Shilling' ) ( code = 'USD' description = 'United States Dollar' ) ( code = 'UYU' description = 'Uruguay Peso' ) ( code = 'UZS' description = 'Uzbekistan Som' ) ( code = 'VEF' description = 'Venezuela Bolivar' ) ( code = 'VND' description = 'Viet Nam Dong' ) ( code = 'VUV' description = 'Vanuatu Vatu' ) ( code = 'WST' description = 'Samoa Tala' ) ( code = 'XAF' description = 'CFA Franc BEAC' ) ( code = 'XCD' description = 'East Caribbean Dollar' ) ( code = 'XDR' description = 'International Monetary Fund Special Drawing Rights' ) ( code = 'XOF' description = 'BCEAO Franc' ) ( code = 'XPF' description = 'CFP Franc' ) ( code = 'YER' description = 'Yemen Rial' ) ( code = 'ZAR' description = 'South Africa Rand' ) ( code = 'ZMW' description = 'Zambia Kwacha' ) ( code = 'ZWD' description = 'Zimbabwe Dollar' ) ). DELETE FROM zdemo_epm_ws_crr. INSERT zdemo_epm_ws_crr FROM TABLE lt_crr. lt_wgu = VALUE #( ( symbol = 't' description = 'tonne' ) ( symbol = 'kg' description = 'kilogram' ) ( symbol = 'hg' description = 'hectogram' ) ( symbol = 'g ' description = 'gram' ) ( symbol = 'dg' description = 'decigram' ) ( symbol = 'cg' description = 'centigram' ) ( symbol = 'mg' description = 'milligram' ) ( symbol = 'µg' description = 'microgram' ) ( symbol = 'carat' description = 'carat' ) ( symbol = 'grain' description = 'grain' ) ( symbol = 'oz' description = 'ounce' ) ( symbol = 'lb' description = 'pound' ) ). DELETE FROM zdemo_epm_ws_wgu. INSERT zdemo_epm_ws_wgu FROM TABLE lt_wgu. lt_cat = VALUE #( ( id = 1 name = 'Projector' ) ( id = 2 name = 'Graphics Card' ) ( id = 3 name = 'Accessory' ) ( id = 4 name = 'Printer' ) ( id = 5 name = 'Monitor' ) ( id = 6 name = 'Laptop' ) ( id = 7 name = 'Keyboard ' ) ). DELETE FROM zdemo_epm_ws_cat. INSERT zdemo_epm_ws_cat FROM TABLE lt_cat. lt_prd = VALUE #( ( id = 1 name = 'Power Projector 4713' category = 1 description = 'A very powerful projector with special features for Internet usability, USB 1467' weight = '1467' price = '856.49' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'g' ) ( id = 2 name = 'Gladiator MX' category = 2 description = 'Gladiator MX: DDR2 RoHS 128MB Supporting 512MB Clock rate: 350 MHz Memory Clock: 533 MHz, Bus Type: PCI-Express, Memory Type: DDR2 Memory Bus: 32-bit' weight = '4234' price = '343.39' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'g' ) ( id = 3 name = 'Hurricane GX' category = 2 description = 'Hurricane GX: DDR2 RoHS 512MB Supporting 1024MB Clock rate: 550 MHz Memory Clock: 933 MHz, Bus Type: PCI-Express, Memory Type: DDR2 Memory Bus: 64-bit' weight = '35' price = '645.49' pictureurl = 'HT-6100.jpg' currency = 'EUR' weightunit = 'g' ) ( id = 4 name = 'Webcam' category = 3 description = 'Web camera, color, High-Speed USB' weight = '464' price = '756.49' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'cg' ) ( id = 5 name = 'Monitor Locking Cable' category = 3 description = 'Lock for Monitor' weight = '567' price = '86.49' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'kg' ) ( id = 6 name = 'Laptop Case' category = 3 description = 'Laptop Case with room for pencils and other items' weight = '686' price = '55.49' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'g' ) ( id = 7 name = 'USB Stick 16 GByte' category = 3 description = 'USB 2.0 HighSpeed 16GB' weight = '353' price = '46.99' pictureurl = 'HT-6100.jpg' currency = 'EUR' weightunit = 'g' ) ( id = 8 name = 'Deskjet Super Highspeed' category = 4 description = '1200 dpi x 1200 dpi - up to 25 ppm (mono) / up to 24 ppm (colour)' weight = '234' price = '46.49' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'g' ) ( id = 9 name = 'Laser Allround Pro' category = 4 description = ' up to 25 ppm letter and 24 ppm A4 color or monochrome, with a first-page-out-time of less than 13 seconds for monochrome and less than 15 seconds for color' weight = '131' price = '26.49' pictureurl = 'HT-6100.jpg' currency = 'USD' weightunit = 'kg' ) ). DELETE FROM zdemo_epm_ws_prd. INSERT zdemo_epm_ws_prd FROM TABLE lt_prd. COMMIT WORK. send_refresh( ). ENDMETHOD. METHOD products_create_entity. DATA ls_data LIKE er_entity. io_data_provider->read_entry_data( IMPORTING es_data = ls_data ). DATA(ls_record) = CORRESPONDING zdemo_epm_ws_prd( ls_data ). SELECT MAX( id ) FROM zdemo_epm_ws_prd INTO @ls_record-id. ADD 1 TO ls_record-id. INSERT INTO zdemo_epm_ws_prd VALUES @ls_record. ENDMETHOD. METHOD products_delete_entity. DATA ls_converted_keys TYPE zcl_odata_service_mpc=>ts_product. io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_converted_keys ). DELETE FROM zdemo_epm_ws_prd WHERE id = @ls_converted_keys-id. IF sy-subrc <> 0. me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling( EXPORTING iv_subrc = sy-subrc iv_exp_message_text = 'Entity not found.'(001) ). ELSE. COMMIT WORK. send_refresh( ). ENDIF. ENDMETHOD. METHOD products_get_entity. DATA ls_converted_keys LIKE er_entity. io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_converted_keys ). SELECT SINGLE * FROM zdemo_epm_ws_prd INTO CORRESPONDING FIELDS OF @er_entity WHERE id = @ls_converted_keys-id. IF sy-subrc <> 0. me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling( EXPORTING iv_subrc = sy-subrc iv_exp_message_text = 'Entity not found.'(001) ). ENDIF. ENDMETHOD. METHOD products_get_entityset. IF line_exists( it_filter_select_options[ property = `NAME` ] ). DATA(lt_select_opts) = it_filter_select_options[ property = `NAME` ]-select_options. SELECT * FROM zdemo_epm_ws_prd INTO CORRESPONDING FIELDS OF TABLE @et_entityset WHERE name IN @lt_select_opts. ELSE. SELECT * FROM zdemo_epm_ws_prd INTO CORRESPONDING FIELDS OF TABLE @et_entityset. ENDIF. ENDMETHOD. METHOD products_update_entity. DATA: ls_converted_keys LIKE er_entity, ls_data LIKE er_entity. io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_converted_keys ). io_data_provider->read_entry_data( IMPORTING es_data = ls_data ). UPDATE zdemo_epm_ws_prd SET description = @ls_data-description, price = @ls_data-price, pictureurl = @ls_data-pictureurl, weight = @ls_data-weight WHERE id = @ls_converted_keys-id. IF sy-subrc <> 0. me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling( EXPORTING iv_subrc = sy-subrc iv_exp_message_text = 'Entity not found.'(001) ). ENDIF. ENDMETHOD. METHOD send_refresh. DATA: lo_producer TYPE REF TO if_amc_message_producer_text. TRY. lo_producer ?= cl_amc_channel_manager=>create_message_producer( i_application_id = 'Zdemo_EPM_WS_MC' i_channel_id = '/epm' ). lo_producer->send( i_message = gv_refresh_message ). CATCH cx_amc_error INTO DATA(lx_amc_error). MESSAGE lx_amc_error->get_text( ) TYPE 'E'. CATCH cx_apc_error INTO DATA(lx_apc_error). MESSAGE lx_apc_error->get_text( ) TYPE 'E'. ENDTRY. ENDMETHOD. METHOD weightunits_get_entity. DATA: ls_converted_keys LIKE er_entity, ls_source_keys TYPE zcl_odata_service_mpc=>ts_product. IF io_tech_request_context->get_source_entity_set_name( ) = 'Products'. io_tech_request_context->get_converted_source_keys( IMPORTING es_key_values = ls_source_keys ). SELECT SINGLE * FROM zdemo_epm_ws_prd AS prd INNER JOIN zdemo_epm_ws_wgu AS wgu ON prd~weightunit = wgu~symbol INTO CORRESPONDING FIELDS OF @er_entity WHERE prd~id = @ls_source_keys-id. ELSE. io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_converted_keys ). SELECT SINGLE * FROM zdemo_epm_ws_wgu INTO CORRESPONDING FIELDS OF @er_entity WHERE symbol = @ls_converted_keys-symbol. ENDIF. IF sy-subrc <> 0. me->/iwbep/if_sb_dpc_comm_services~rfc_exception_handling( EXPORTING iv_subrc = sy-subrc iv_exp_message_text = 'Entity not found.'(001) ). ENDIF. ENDMETHOD. METHOD weightunits_get_entityset. IF line_exists( it_filter_select_options[ property = `SYMBOL` ] ). DATA(lt_select_opts) = it_filter_select_options[ property = `SYMBOL` ]-select_options. SELECT * FROM zdemo_epm_ws_wgu INTO CORRESPONDING FIELDS OF TABLE @et_entityset WHERE symbol IN @lt_select_opts. ELSE. SELECT * FROM zdemo_epm_ws_wgu INTO CORRESPONDING FIELDS OF TABLE @et_entityset. ENDIF. ENDMETHOD. ENDCLASS.",6622,False,1676.3565819791536,median "report ZTEST message-id id. *---------------------------------------------------------------------* * Type pools *---------------------------------------------------------------------* type-pools : slis. *---------------------------------------------------------------------* * Tables *---------------------------------------------------------------------* tables: t616u , vbpa , vbap , vbak , mara , t005t , t604t . *---------------------------------------------------------------------* * Internal Tables *---------------------------------------------------------------------* * To store first line contents of report data : begin of it_output occurs 0, vbeln like vbap-vbeln, "" Sales order number posnr like vbap-posnr, "" Sales order line matnr like vbap-matnr, "" Material Number arktx like vbap-arktx, "" Description of material herkl like vbap-zzherkl, "" Country of origin landx like t005t-landx, "" Country Description stawn like vbap-zzstawn, "" HTS Commodity code text1 like t604t-text1, "" HTS Description check, "" Check box for selection line_color(4), "" Line color vbpos(17), "" Key for Hier List end of it_output. * To store second line contents of report data: begin of it_output2 occurs 0, herkl like vbap-zzherkl, "" Country of origin stawn like vbap-zzstawn, "" HTS Commodity code vbpos(17), "" Key for Hier List end of it_output2. * Internal table to store details of sales order data : begin of it_material occurs 0, vbeln like vbap-vbeln, "" Sales order number posnr like vbap-posnr, "" Sales order line matnr like vbap-matnr, "" Material Number werks like vbap-werks, "" Plant arktx like vbap-arktx, "" Description of material herkl like vbap-zzherkl, "" Country of origin stawn like vbap-zzstawn, "" HTS Commodity code end of it_material. * Internal table to store error messages data : begin of it_errmsgs occurs 0, vbeln like vbap-vbeln, "" Sales order number posnr like vbap-posnr, "" Sales order line message(100) type c, "" Error Message end of it_errmsgs. * WORKING STORAGE FOR BAPI INTERFACE data: begin of it_bapiparex occurs 0. include structure bapiparex. ""1710 data: end of it_bapiparex. data: begin of it_bape. data: structure like bapiparex-structure. ""len 30 include structure bape_vbap. ""len 261 data: filler(1419) type c. ""len 1419 data: end of it_bape. data: begin of it_bapex. data: structure like bapiparex-structure. ""len 30 include structure bape_vbapx. ""len 22 data: filler(1658) type c. data: end of it_bapex. *Internal Tables to capture BapirETURN messages data: it_bapireturn1 like bapiret2 occurs 0 with header line, it_bapireturn2 like bapiret2 occurs 0 with header line. data: x_orderitemx like bapisdh1x. data: v_export type c. data: begin of itmupd occurs 0. include structure bapisditmx. data: end of itmupd. data: begin of itmfld occurs 0. include structure bapisditm. data: end of itmfld. * Internal table for field catalog data : it_fieldcat type slis_t_fieldcat_alv with header line, * Internal table for Events it_events type slis_t_event with header line. *---------------------------------------------------------------------* * Global Variables *---------------------------------------------------------------------* data: v_tabix like sy-tabix, "" Line index v_repid like sy-repid, "" Program name x_layout type slis_layout_alv, "" Output layout v_herkl(6), v_stawn(34). *---------------------------------------------------------------------* * Selection Screen *---------------------------------------------------------------------* selection-screen : begin of block blk1 with frame title text-001. "" Geography-Receipt select-options : * Country s_land1 for vbpa-land1, * Ship-to-Party s_kunnr for vbpa-kunnr. selection-screen : end of block blk1. selection-screen : begin of block blk2 with frame title text-002 . "" Geography-Export select-options : * Sales Organization s_vkorg for vbak-vkorg, * Shipping Point / Receiving Point s_vstel for vbap-vstel, * Plant s_werks for vbap-werks. selection-screen : end of block blk2. selection-screen : begin of block blk3 with frame title text-003."" Further Doc.Data select-options : * Created on s_erdat for vbak-erdat. selection-screen :begin of line. *-Sales document Radiobutton - Select-Option parameters : r_select radiobutton group grp1 . selection-screen comment 4(25) text-015 for field r_select. *-Select Option for Sales Order select-options : s_vbeln for vbap-vbeln. selection-screen :end of line. selection-screen :begin of line. *-Sales document Radiobutton - Parameter parameters : r_parmtr radiobutton group grp1 . selection-screen comment 4(28) text-015 for field r_parmtr. parameters: p_vbeln like vbak-vbeln. selection-screen :end of line. selection-screen :begin of line. *-Item selection-screen comment 3(26) text-016 for field s_posnr. select-options: s_posnr for vbap-posnr. selection-screen :end of line. select-options : * Created By s_ernam for vbak-ernam, * Sales Order Type s_auart for vbak-auart, * Material s_matnr for vbap-matnr, * Material Group s_matkl for vbap-matkl. selection-screen : end of block blk3. selection-screen begin of block blk4 with frame . *To Display error record only parameters p_errors as checkbox . selection-screen end of block blk4. *---------------------------------------------------------------------* * Start of Selection *---------------------------------------------------------------------* start-of-selection. * Selecting data depending on selection criteria perform select_data. *---------------------------------------------------------------------* * End of Selection *---------------------------------------------------------------------* end-of-selection. *Display report output perform display_output. *&---------------------------------------------------------------------* *& Form SELECT_DATA *&---------------------------------------------------------------------* * Select data based on selection criteria *----------------------------------------------------------------------* form select_data. *Refresh & clear internal tables before populating data refresh : it_output , it_output2, it_material. clear : it_output, it_material, it_output2. *Fetching data from VBAP *-Sales Order - Select-Option if r_select = 'X'. select vbap~vbeln vbap~posnr vbap~matnr vbap~werks vbap~arktx vbap~zzherkl vbap~zzstawn into table it_material from vbap inner join vbak on vbap~vbeln = vbak~vbeln where vbak~vkorg in s_vkorg and vbap~vstel in s_vstel and vbap~werks in s_werks and vbak~erdat in s_erdat and vbak~vbeln in s_vbeln and vbak~ernam in s_ernam and vbak~auart in s_auart and vbap~matnr in s_matnr and vbap~matkl in s_matkl. *-Sales Order - Parameter & Item - Select-Option elseif r_parmtr = 'X'. select vbap~vbeln vbap~posnr vbap~matnr vbap~werks vbap~arktx vbap~zzherkl vbap~zzstawn into table it_material from vbap inner join vbak on vbap~vbeln = vbak~vbeln where vbak~vkorg in s_vkorg and vbap~vstel in s_vstel and vbap~werks in s_werks and vbak~erdat in s_erdat and vbak~vbeln = p_vbeln and vbak~ernam in s_ernam and vbak~auart in s_auart and vbap~posnr in s_posnr and vbap~matnr in s_matnr and vbap~matkl in s_matkl. endif. * If sy-subrc is not equal to zero exit if sy-subrc <> 0 . exit. endif. * Else Excluding records loop at it_material. v_tabix = sy-tabix. select single kunnr from vbpa into vbpa-vbeln where vbeln = it_material-vbeln and posnr = it_material-posnr and parvw = 'WE' and kunnr in s_kunnr and land1 in s_land1. if sy-subrc <> 0. select single kunnr from vbpa into vbpa-vbeln where vbeln = it_material-vbeln and posnr = '000000' and parvw = 'WE' and kunnr in s_kunnr and land1 in s_land1. if sy-subrc <> 0. delete it_material index v_tabix. continue. endif. endif. * Delete recods that are not export relevant. call function 'Z_DETER_EXPORT_REL' exporting salesorder = it_material-vbeln lineitem = it_material-posnr importing flag = v_export. if v_export = ' '. delete it_material index v_tabix. continue. endif. * Populating IT_OUTPUT from IT_MATERIAL. move-corresponding it_material to it_output. *Populating SecondLine In the Output select single herkl stawn from marc into (it_output2-herkl, it_output2-stawn) where matnr = it_material-matnr and werks = it_material-werks . if sy-subrc = 0. shift it_material-vbeln left deleting leading '0'. concatenate it_material-vbeln it_material-posnr into it_output2-vbpos separated by '/'. append it_output2. endif. * If Errors Only Check Box is checked. if p_errors = 'X'. clear : v_herkl, v_stawn. concatenate : it_output2-herkl it_material-herkl into v_herkl, it_output2-stawn it_material-stawn into v_stawn. condense : v_herkl, v_stawn. if v_herkl is initial or v_stawn is initial. else. delete it_material index v_tabix. continue. endif. endif. * Country Description select single landx from t005t into it_output-landx where spras = 'EN' and land1 = it_material-herkl. * HTS Description select single text1 from t604t into it_output-text1 where spras = 'EN' and land1 = it_material-herkl and stawn = it_material-stawn. *VBELN/POSNR shift it_material-vbeln left deleting leading '0'. concatenate it_material-vbeln it_material-posnr into it_output-vbpos separated by '/'. append it_output. clear it_output. endloop. endform. "" SELECT_DATA *&---------------------------------------------------------------------* *& Form DISPLAY_OUTPUT *&---------------------------------------------------------------------* * Display Report *----------------------------------------------------------------------* form display_output. data : l_pf_formname type slis_formname value 'PF_STATUS', l_user_formname type slis_formname value 'USER_COMMAND', keyinfo type slis_keyinfo_alv. v_repid = sy-repid. * populate fieldcatalog perform build_fieldcatalog. * Populate events internal table perform build_events. * Layout initialization. perform layout using x_layout. x_layout-info_fieldname = 'LINE_COLOR'. * Specifying KeyFields for List. keyinfo-header01 = 'VBPOS'. keyinfo-item01 = 'VBPOS'. call function 'REUSE_ALV_HIERSEQ_LIST_DISPLAY' exporting i_callback_program = v_repid i_callback_pf_status_set = l_pf_formname i_callback_user_command = l_user_formname is_layout = x_layout it_fieldcat = it_fieldcat[] it_events = it_events[] i_tabname_header = 'IT_OUTPUT' i_tabname_item = 'IT_OUTPUT2' is_keyinfo = keyinfo tables t_outtab_header = it_output t_outtab_item = it_output2 exceptions program_error = 1 others = 2. endform. "" DISPLAY_OUTPUT *&---------------------------------------------------------------------* *& Form TOP-OF-LIST *&---------------------------------------------------------------------* * For Top of list *----------------------------------------------------------------------* form top-of-list. * Display Steelcase header call function 'Z_HEADER'. endform. "" TOP-OF-LIST *---------------------------------------------------------------------* * FORM LAYOUT * *---------------------------------------------------------------------* form layout using l_layout type slis_layout_alv. l_layout-box_fieldname = 'CHECK'. l_layout-box_tabname = 'IT_OUTPUT'. l_layout-colwidth_optimize = 'X'. endform. *---------------------------------------------------------------------* *& Form USER_COMMAND *&---------------------------------------------------------------------* * Processing User command *----------------------------------------------------------------------* * -->P_UCOMM Screens, function code triggered by PAI * -->P_SELFIELD information cursor position ALV *----------------------------------------------------------------------* form user_command using p_ucomm like sy-ucomm p_selfield type slis_selfield. data : l_index like sy-tabix. l_index = p_selfield-tabindex. case p_ucomm. when 'SAVE'. perform validate_input. perform save_sales_docu. p_selfield-refresh = 'X'. *Display Messages if it_errmsgs[] is initial. message s899 with 'Record(s) Successfully Updated'. else. perform display_errors. endif. when '&IC1'. * On Double click display the sales order. read table it_output index l_index. set parameter id 'AUN' field it_output-vbeln. call transaction 'VA03' and skip first screen. endcase. endform. "" USER_COMMAND *---------------------------------------------------------------------* * FORM pf_status * *---------------------------------------------------------------------* * Set pf status *----------------------------------------------------------------------* * --> p_extab excluding Fcode table *---------------------------------------------------------------------* form pf_status using p_extab type slis_t_extab. data : l_extab type slis_extab. set pf-status 'STANDARD' excluding p_extab. endform. "" PF_STATUS_SET *&---------------------------------------------------------------------* *& Form SAVE_SALES_DOCU *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* form save_sales_docu. data v_tabix like sy-tabix. refresh it_errmsgs. clear it_errmsgs. *Setting the flag field as update x_orderitemx-updateflag = 'U'. loop at it_output. v_tabix = sy-tabix. refresh : it_bapireturn1, it_bapireturn2, it_bapiparex, itmfld, itmupd. clear : it_bapireturn1, it_bapireturn2, it_bapiparex, itmfld, itmupd, it_bape, it_bapex. if it_output-check = ' '. continue. endif. * if the sales order is checked populate IT_BAPIREX. it_bape-structure = 'BAPE_VBAP'. it_bape-vbeln = it_output-vbeln. it_bape-posnr = it_output-posnr. it_bape-zzherkl = it_output-herkl. it_bape-zzstawn = it_output-stawn. append it_bape to it_bapiparex. it_bapex-structure = 'BAPE_VBAPX'. it_bapex-vbeln = it_output-vbeln. it_bapex-posnr = it_output-posnr. it_bapex-zzherkl = 'X'. it_bapex-zzstawn = 'X'. append it_bapex to it_bapiparex. itmfld-itm_number = it_output-posnr. append itmfld. itmupd-itm_number = it_output-posnr. itmupd-updateflag = 'U'. append itmupd. call function 'BAPI_SALESORDER_CHANGE' exporting salesdocument = it_output-vbeln order_header_inx = x_orderitemx tables return = it_bapireturn1 order_item_in = itmfld order_item_inx = itmupd extensionin = it_bapiparex. *Store the error messages in internal table loop at it_bapireturn1 where type = 'E'. it_errmsgs-vbeln = it_output-vbeln. it_errmsgs-posnr = it_output-posnr. it_errmsgs-message = it_bapireturn1-message. append it_errmsgs. clear it_errmsgs. it_output-line_color = 'C600'. endloop. *Commit the bapi transaction if no error messages are there. if sy-subrc <> 0. refresh it_bapireturn2. clear it_bapireturn2. call function 'BAPI_TRANSACTION_COMMIT' exporting wait = 'X' importing return = it_bapireturn2. *If commit is not succesful capture the error messages. if not it_bapireturn2 is initial. it_errmsgs-vbeln = it_output-vbeln. it_errmsgs-posnr = it_output-posnr. it_errmsgs-message = it_bapireturn2-message. append it_errmsgs. clear it_errmsgs. it_output-line_color = 'C600'. else. *If salesOrder is updated refresh the data from the database. it_output-line_color = ' '. select single zzherkl zzstawn from vbap into (it_output-herkl , it_output-stawn) where vbeln = it_output-vbeln and posnr = it_output-posnr. endif. endif. * Make the checkboxes unchecked after updating the salesorder. it_output-check = ' '. modify it_output index v_tabix. endloop. endform. "" SAVE_SALES_DOCU *&---------------------------------------------------------------------* *& Form VALIDATE_INPUT *&---------------------------------------------------------------------* * To Validate Input Fields *----------------------------------------------------------------------* form validate_input. loop at it_output. v_tabix = sy-tabix. * check if the Country of origin exists. if not it_output-herkl is initial. select single landx from t005t into t005t-landx where spras = 'EN' and land1 = it_output-herkl. if sy-subrc <> 0. message e899 with it_output-herkl text-011 . exit. endif. * Move country description to display field move t005t-landx to it_output-landx. else. move space to it_output-landx. endif. * check if the Commodity code exists. if not it_output-stawn is initial. select single text1 from t604t into t604t-text1 where spras = 'EN' and land1 = it_output-herkl and stawn = it_output-stawn. if sy-subrc <> 0. message e899 with it_output-stawn text-012 . exit. endif. * Move commodity description to display field move t604t-text1 to it_output-text1. else . move space to it_output-text1. endif. modify it_output index v_tabix. endloop. endform. "" VALIDATE_INPUT *&---------------------------------------------------------------------* *& Form DISPLAY_ERRORS *&---------------------------------------------------------------------* * Display PopUp Messages *----------------------------------------------------------------------* form display_errors. *variables data : l_pos(1) type n value 1. "" Field pos * Fieldcatalog for popup data : it_fieldcat_pop type slis_t_fieldcat_alv with header line. * Sales Order # it_fieldcat_pop-fieldname = 'VBELN'. it_fieldcat_pop-tabname = 'IT_ERRMSGS'. it_fieldcat_pop-col_pos = l_pos. it_fieldcat_pop-seltext_m = 'Sales Order# '. it_fieldcat_pop-ddictxt = 'M'. it_fieldcat_pop-outputlen = 10. it_fieldcat_pop-no_zero = 'X'. append it_fieldcat_pop. clear it_fieldcat_pop. l_pos = l_pos + 1. * Message it_fieldcat_pop-fieldname = 'MESSAGE'. it_fieldcat_pop-tabname = 'IT_ERRMSGS'. it_fieldcat_pop-col_pos = l_pos. it_fieldcat_pop-seltext_m = 'Message'. it_fieldcat_pop-ddictxt = 'M'. it_fieldcat_pop-outputlen = 255. it_fieldcat_pop-no_zero = 'X'. append it_fieldcat_pop. clear it_fieldcat_pop. call function 'REUSE_ALV_POPUP_TO_SELECT' exporting i_title = 'Errors' i_tabname = 'IT_ERRMSGS' it_fieldcat = it_fieldcat_pop[] tables t_outtab = it_errmsgs exceptions program_error = 1 others = 2. endform. "" DISPLAY_ERRORS *&---------------------------------------------------------------------* *& Form BUILD_FIELDCATALOG *&---------------------------------------------------------------------* * Builds FieldCatalog *----------------------------------------------------------------------* form build_fieldcatalog. data : l_pos(2) type n value 1. refresh it_fieldcat. clear it_fieldcat. * Field Catalog for first line in Output. * Order/Line it_fieldcat-fieldname = 'VBPOS'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 17. it_fieldcat-seltext_m = text-013. ""Order/Line append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * Material# it_fieldcat-fieldname = 'MATNR'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 18. it_fieldcat-seltext_m = text-006. ""Material# append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * Material Desc it_fieldcat-fieldname = 'ARKTX'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 40. it_fieldcat-seltext_m = text-007. ""Material Desc append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * Cnty of Origin it_fieldcat-fieldname = 'HERKL'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-input = 'X'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 3. it_fieldcat-seltext_m = text-008. ""Cnty of Origin append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * Country Description it_fieldcat-fieldname = 'LANDX'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 15. it_fieldcat-seltext_m = text-009. ""Description append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * HTS Code it_fieldcat-fieldname = 'STAWN'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-input = 'X'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 17. it_fieldcat-seltext_m = text-010. ""HTS Code append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * HTS Description it_fieldcat-fieldname = 'TEXT1'. it_fieldcat-tabname = 'IT_OUTPUT'. it_fieldcat-col_pos = l_pos. it_fieldcat-outputlen = 15. it_fieldcat-seltext_m = text-009. ""Description append it_fieldcat. clear it_fieldcat. * Field Catalog for second line in Output. * Cnty of Origin l_pos = 1. it_fieldcat-fieldname = 'HERKL'. it_fieldcat-tabname = 'IT_OUTPUT2'. it_fieldcat-col_pos = '1'. it_fieldcat-outputlen = 18. it_fieldcat-seltext_m = text-014. ""Cnty of Origin append it_fieldcat. clear it_fieldcat. l_pos = l_pos + 1. * HTS Code it_fieldcat-fieldname = 'STAWN'. it_fieldcat-tabname = 'IT_OUTPUT2'. it_fieldcat-col_pos = '2'. it_fieldcat-outputlen = 17. it_fieldcat-seltext_m = text-010. ""HTS Code append it_fieldcat. clear it_fieldcat. endform. "" BUILD_FIELDCATALOG *&---------------------------------------------------------------------* *& Form BUILD_EVENTS *&---------------------------------------------------------------------* * Populate Events Table *----------------------------------------------------------------------* form build_events. refresh it_events. clear it_events. *ADD Top of Page event. it_events-name = 'TOP_OF_PAGE'. it_events-form = 'TOP_OF_PAGE'. append it_events. clear it_events. *ADD Top of LIST event. it_events-name = 'TOP_OF_LIST'. it_events-form = 'TOP-OF-LIST'. append it_events. clear it_events. endform. "" BUILD_EVENTS ",6417,False,1159.09917548901,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. * * Changes 2010-02-10 jason@vonnieda.org * * Changed BigInteger(value, radix, unsigned) to properly handle radix in Strings by * calling fromRadix. * * Changed toString(radix) to handle radix other than 2, 4, 8, 16, 32 by * calling toRadix. * * Fixed fromRadix by fixing intAt which was not checking for NaN causing * all negative numbers to become positive. * * Fixed compareTo(v) which was failing the test case * new BigInteger(""-1"", 10).compareTo(new BigInteger(""-9223372036854775808"", 10)) by * returning -3. Function was improperly comparing number of chunks in the * case of like signs. */ package com.hurlant.math { import com.hurlant.util.Hex; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1<0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-->0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { if (s==-1) { return -negate().valueOf(); } var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return s < 0 ? r * -1 : r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int, unsigned:Boolean = false):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } if (!unsigned && (value[0]&0x80)==0x80) { s = -1; if (sh > 0) { a[t-1] |= ((1<<(DB-sh))-1)<0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { var x:Number = parseInt(str.charAt(index), 36); return isNaN(x) ? -1 : x; } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-->0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12501,True,2662.1250722298123,median "/* Devanagari.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2019, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This example shows how to print Devanagari glyphs. A new function ""u8g2_draw_unifont_devanagari"" is introduced here, which will modify the glyph position for proper display of a word. This function is incomplete and will not work for all available gylphs. Please extend the function by yourself. I would be happy to hear about new, improved versions of ""u8g2_draw_unifont_devanagari"". */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list /* draw unicode for https://en.wikipedia.org/wiki/Devanagari Adjust the glyph position as good as possible for the unicode font. Report missing or wrong glyph adjustments here: https://github.com/olikraus/u8g2/issues/584 precondition: u8g2_SetFont(&u8g2, u8g2_font_unifont_t_devanagari); u8g2_SetFontMode(&u8g2, 1); Font direction command is NOT supported */ u8g2_uint_t u8g2_draw_unifont_devanagari(u8g2_uint_t x, u8g2_uint_t y, const char *str) { uint16_t e; u8g2_uint_t delta, sum; u8g2.getU8g2()->u8x8.next_cb = u8x8_utf8_next; u8x8_utf8_init(u8g2.getU8x8()); sum = 0; for(;;) { e = u8g2.getU8g2()->u8x8.next_cb(u8g2.getU8x8(), (uint8_t)*str); if ( e == 0x0ffff ) break; str++; if ( e != 0x0fffe ) { switch(e) { /* many more glyphs and corrections are missing */ /* please report to https://github.com/olikraus/u8g2/issues/584 */ case 0x093e: x-= 12; break; case 0x093f: x-= 19; break; case 0x0941: x-= 10; y+=3; break; // move down case 0x0947: x-= 12; break; case 0x094d: x-= 10; break; } delta = u8g2.drawGlyph(x, y, e); switch(e) { case 0x0941: x-= 3; y -=3; break; // revert the y shift case 0x094d: x-= 8; break; } x += delta; sum += delta; } } return sum; } void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); } void loop(void) { /* Set the unifont with Devanagari glyphs */ u8g2.setFont(u8g2_font_unifont_t_devanagari); /* Important: do not write background pixel */ u8g2.setFontMode(1); u8g2.firstPage(); do { u8g2_draw_unifont_devanagari(0,24,""नमस्ते दुनिया""); // Hello World } while ( u8g2.nextPage() ); //delay(1000); } ",16313,True,4848.800584275935,median " /* * Projekt: Wordclock * Version: 1.01 * Datum: 27.10.2021 * Autor: SPSundTechnik * * * Changelog: * - Testdurchlauf der LED's während die WLAN-Verbindung hergestellt wird * - NTP-Server wird im Setup abgefragt * - Uhrzeit wird durch den Millis()-Timer berechnet * - NTP-Server wird nur noch stündlich abgefragt * - Ausgabe der Wörter mit neuem Array, welches die Zustandsänderung speichert * - Wörter werden hoch- bzw. herunter""gedimmt"" * - LED's können in einem definierten Zeitfenster ausgeschaltet werden (Nachtmodus) * - korrekte Sommer-/Winterzeitumstellung bei Neustart der Uhr * - Uhr startet auch ohne WLAN-Verbindung * - Wort-Adressen werden bei Änderungam Layout korrekt zurückgesetzt * - Schnittstelle zum User-Interface * - UDP-Daten für NTP/UI können zusammen empfangen werden * - Stromaufnahme im Debug-Monitor * - Uhr wird ohne WLAN-Verbindung zum Access Point * */ //Bibliotheken #include #include #include #include //Anzahl LED's und Ausgang vom ESP festlegen #define PIN D6 #define NUMBERS 121 // --> SF geändert //******************************************************** PARAMETER ******************************************************** //********************************************************** WLAN *********************************************************** //Zugangsdaten zum eigenen WLAN //SSID char Ssid_Sta[] = """"; //Passwort char Password_Sta[] = """"; //Zugangsdaten WordClock Access Point //SSID char Ssid_Ap[] = ""Wortuhr""; // --> SF geändert //Passwort char Password_Ap[] = ""Wortuhr""; // --> SF geändert //*************************************************************************************************************************** //******************************************* FARBWERTE UND HELLIGKEIT DER LED's ******************************************** //Beispiel: RGB-Farbschema Rot = 50; Grün = 50; Blau = 50 => ergibt einen weißen Farbton. //Tipp: Der blaue Anteil muss bei den WS2812B-LED's etwas reduziert werden, da dieser dominanter ausfällt. //Helligkeit der LED's kann mit Werten zwischen 0 - 255 eingestellt werden. //Beispiel 1: Rot = 255; Grün = 255; Blau = 255 => weißer Farbton mit maximaler Helligkeit aller LED's //Beispiel 2: Rot = 0; Grün = 0; Blau = 255 => blauer Farbton mir maximaler Helligkeit der blauen LED //Beispiel 3: Rot = 127; Grün = 127; Blau = 127 => weißer Farbton mit 50% der Helligkeit aller LED's //Farbwert ROT const unsigned int rgbvaluered = 50; // --> SF geändert //Farbwert GRÜN const unsigned int rgbvaluegreen = 50; // --> SF geändert //Farbwert BLAU const unsigned int rgbvalueblue = 30; // --> SF geändert //*************************************************************************************************************************** //******************************************************** NACHTMODUS ******************************************************* //Display kann in einem definiertem Zeitfenster (24h-Format) ausgeschalten werden. //Enable Display On/Off => Freigabe der Funktion //Display Off => Uhrzeit wann das Display wieder ausgeschaltet werden soll //Display On => Uhrzeit wann das Display wieder eingeschaltet werden soll //Freigabe der Funktion unsigned int enableDisplayOnOff = 0; //Uhrzeit Display ausschalten unsigned int displayOff = 0; //Uhrzeit Display einschalten unsigned int displayOn = 0; //*************************************************************************************************************************** //***************************************************** LOKALE UHRZEIT ****************************************************** //Wird die Uhr ohne eine WLAN-Verbindung gestartet, kann mit den folgenden Parametern eine Uhrzeit eingestellt werden. //Die Uhrzeit wird als UTC-Zeit eingestellt. Sommerzeit (UTC+2) oder Winterzeit (UTC+1) können eingestellt werden. //Stundenzahl in UTC (24h-Format) const unsigned int localutcaktstunde = 12; //Minutenzahl in UTC const unsigned int localutcaktminute = 30; //Sekundenzahl in UTC const unsigned int localutcaktsekunde = 0; //Einstellung Sommer-/Winterzeit const unsigned int localutcx = 1; //*************************************************************************************************************************** //******************************************************** DIAGNOSE ********************************************************* //Serielle Schnittstelle für die Diagnose öffnen const bool debug = LOW; //*************************************************************************************************************************** //******************************************************* KONSTANTEN ******************************************************** //Lokale Portnummer für das UDP-Paket const unsigned int localPort = 2390; //Adresse des NTP-Serverpools const char* NtpServerName = ""de.pool.ntp.org""; //Größe des NTP-Datenpaket const unsigned int NtpPaketSize = 48; byte NtpPaketBuffer[NtpPaketSize]; //Größe des UserInterface-Datenpaket const unsigned int UserInterfacePaketSize = 12; byte UserInterfacePaketBuffer[UserInterfacePaketSize]; //ID-Nummern const int UdpIdHandshakeRequest = 100; const int UdpIdHandshakeAnswer = 101; const int UdpIdRgb = 102; const int UdpIdTime = 103; const int UdpIdDate = 104; const int UdpIdDisplay = 105; //Zeitintervalle in Millisekunden const unsigned long secondperday = 86400; const unsigned long secondperhour = 3600; const unsigned long secondperminute = 60; const unsigned long minuteperhour = 60; const unsigned long millisecondpersecond = 1000; const unsigned long IntervallUdp = 20; const unsigned long intervallDebug = 60000; const unsigned long intervallFade = 4; //Anzahl der Tage im Monat unsigned int tageImMonat[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //Adresse der ersten und letzten LED const int ersteLED = 0; const int letzteLED = 120; // --> SF geändert //Faktor zur Berechnung der Stromaufnahme const float currentPerRgbValue = 0.079; //Adressen der Stundenzahlen // --> SF geändert const int STUNDENADR[12][2] = { {110, 115}, //Zwöufi {51, 53}, //Eis {62, 65}, //Zwöi {58, 60}, //Drü {67, 71}, //Vieri {73, 76}, //Füfi {82, 87}, //Sächsi {77, 81}, //Sibni {88, 92}, //Achti {94, 97}, //Nüni {106, 109}, //Zäni {99, 102} //Eufi }; //Adressen der Minutenzahlen // --> SF geändert const int MINUTENADR[9][2] = { {19, 21}, //Füf {30, 32}, //Zää {11, 16}, //Viertu {22, 27}, //Zwänzg {44, 48}, //Haubi {37, 38}, //ab {41, 43}, //vor {8, 10}, //gli {117, 119} //gsi }; //*************************************************************************************************************************** //******************************************************** VARIABLEN ******************************************************** //Zähler for-Schleifen int i = 0; int z = 0; int x = 0; int y = 0; unsigned long newsecsSince1900 = 0; unsigned long oldsecsSince1900 = 0; unsigned int oldstunde = 99; unsigned int oldmezstunde = 0; unsigned int oldminute = 0; unsigned int utcaktstunde = 0; unsigned int utcaktminute = 0; unsigned int utcaktsekunde = 0; unsigned int mezaktstunde = 0; unsigned int mezaktstunde24 = 0; unsigned int mezaktminute = 0; unsigned int mezaktsekunde = 0; unsigned long newtageSeit1900 = 0; unsigned long oldtageSeit1900 = 0; unsigned int newschaltTage = 0; unsigned int wochenTag = 0; unsigned int datumTag = 0; unsigned int datumMonat = 0; unsigned int datumJahr = 0; unsigned int tagNummer = 0; unsigned int utcx = 0; unsigned int oldschaltTage = 0; bool schaltJahr = LOW; bool sonderFall366 = LOW; unsigned long lastmillisDebug = 0; unsigned long lastmillisSecond = 0; unsigned long lastmillisdifferenz = 0; unsigned long lastmillisFade = 0; unsigned long LastMillisUdp = 0; unsigned int UdpId = 0; unsigned int UdpRgbRed = 0; unsigned int UdpRgbGreen = 0; unsigned int UdpRgbBlue = 0; unsigned int UdpHour = 0; unsigned int UdpMinute = 0; unsigned int UdpSecond = 0; unsigned int UdpDay = 0; unsigned int UdpMonth = 0; unsigned int UdpYear = 0; unsigned int UdpEnableDisplay = 0; unsigned int UdpDisplayOn = 0; unsigned int UdpDisplayOff = 0; unsigned int red = 0; unsigned int green = 0; unsigned int blue = 0; float newredminus = 0.0; float newgreenminus = 0.0; float newblueminus = 0.0; float newredplus = 0.0; float newgreenplus = 0.0; float newblueplus = 0.0; float fadevaluered = 1.0; float fadevaluegreen = 1.0; float fadevalueblue = 1.0; unsigned int currentPerLed = 0; unsigned int startadresse = 0; unsigned int endadresse = 0; unsigned int pointer = 0; unsigned int newletter[110]; unsigned int showletter[110]; unsigned int changeletter[110]; bool newdisplay = LOW; bool setDisplayOff = LOW; bool NoWifi = LOW; //*************************************************************************************************************************** //Objekte anlegen //IP-Adressen IPAddress TimeServerIp; IPAddress UserInterfaceIp; //Wifi UDP WiFiUDP udp; //Neopixel Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMBERS, PIN, NEO_GRB + NEO_KHZ800); //SETUP void setup() { //Serielle Schnittstelle für Debuging öffen if(debug == HIGH) { Serial.begin(9600); } //Leds initialisieren pixels.begin(); //Array initialisieren for(i = ersteLED; i <= letzteLED; i++) { newletter[i] = 0; } //Array initialisieren for(i = ersteLED; i <= letzteLED; i++) { showletter[i] = 0; } //Array initialisieren for(i = ersteLED; i <= letzteLED; i++) { changeletter[i] = 2; } //Start: Farbwerte zum Dimmen der LED's berechnen fadevaluered = FadeValueRed(rgbvaluered,rgbvaluegreen,rgbvalueblue); fadevaluegreen = FadeValueGreen(rgbvaluered,rgbvaluegreen,rgbvalueblue); fadevalueblue = FadeValueBlue(rgbvaluered,rgbvaluegreen,rgbvalueblue); //Farbwerte um x Nachkommastellen verschieben for(i = 0; i <= 10; i++) { if(fadevaluered < 1.0 && fadevaluegreen < 1.0 && fadevalueblue < 1.0){ break; } fadevaluered = fadevaluered / 10.0; fadevaluegreen = fadevaluegreen / 10.0; fadevalueblue = fadevalueblue / 10.0; } //Ende: Farbwerte zum Dimmen der LED's berechnen //Start: Aufbau der WLAN-Verbindung //Wifi Verbindung aufbauen WiFi.mode(WIFI_STA); WiFi.begin(Ssid_Sta, Password_Sta); //Wartezeit damit die Verbindung aufgebaut wird delay(3000); //Kontrolle ob die Verbindung aufgebaut wurde do{ //Keine WLAN-Verbindung, Uhr mit lokaler Zeit starten if(x >= 2){ NoWifi = HIGH; break; } //Start: Test alle LEDs bei Neustart der Uhr //Farbwerte übernehmen red = rgbvaluered; green = rgbvaluegreen; blue = rgbvalueblue; //Testdurchlauf => alle LEDs nacheinander einschalten for(i = ersteLED; i <= letzteLED; i++) { pixels.setPixelColor(i, pixels.Color(red,green,blue)); pixels.show(); delay(50); } //Testdurchlauf => alle LEDs umgekehrt ausschalten for(i = letzteLED; i >= ersteLED; i--) { //Farbwerte übernehmen red = 0; green = 0; blue = 0; // --> SF geändert //Wörter ""ES"" und ""ISCH"" schreiben if (i == 0 || i == 1 || i == 3 || i == 4 || i == 5 || i == 6) { //Farbwerte übernehmen red = rgbvaluered; green = rgbvaluegreen; blue = rgbvalueblue; //""ES"" newletter[0] = 1; newletter[1] = 1; //""ISCH"" newletter[3] = 1; newletter[4] = 1; newletter[5] = 1; newletter[6] = 6; } pixels.setPixelColor(i, pixels.Color(red,green,blue)); pixels.show(); delay(50); } //Ende: Test alle LEDs bei Neustart der Uhr //Anzahl der Durchläufe zählen x++; }while(WiFi.status() != WL_CONNECTED); //Ende: Aufbau der WLAN-Verbindung //Keine WLAN-Verbindung gefunden //Eigenen Access Point starten if(NoWifi == HIGH){ //Wifi Verbindung aufbauen WiFi.softAP(Ssid_Ap, Password_Ap); //Lokale Uhrzeit als Startzeit setzen utcaktstunde = localutcaktstunde; utcaktminute = localutcaktminute; utcaktsekunde = localutcaktsekunde; utcx = localutcx; //UDP-Protokoll udp.begin(localPort); } //WLAN-Verbindung aufgebaut else{ //UDP-Protokoll udp.begin(localPort); //Start: NTP-Anfrage und NTP-Antwort //Zeitwerte vom NTP-Server abrufen do{ SendNtpRequest(); UdpDataReceive(); }while(newsecsSince1900 == 0); //Ende: NTP-Anfrage und NTP-Antwort //Systemzeit speichern für den nächsten Vergleich lastmillisSecond = millis(); //Berechnung der Jahreszahl datumJahr = datumJahr_calc(newsecsSince1900); //Berechnung der Anzahl der Schalttage seit dem 1. Januar 1900 for(i = 1900; i < datumJahr; i++){ //Aufruf der Funktion zur Erkennung ob ein Schaltjahr vorliegt schaltJahr = schaltJahrJN(i); if(schaltJahr == HIGH){ newschaltTage++; } } newschaltTage = newschaltTage - 1; } //Arrays kopieren for(i = ersteLED; i <= letzteLED; i++) { showletter[i] = newletter[i]; } //Farbwerte übernehmen newredminus = rgbvaluered; newgreenminus = rgbvaluegreen; newblueminus = rgbvalueblue; UdpRgbRed = rgbvaluered; UdpRgbGreen = rgbvaluered; UdpRgbBlue = rgbvalueblue; //Lokale Einstellungen übernehmen UdpEnableDisplay = enableDisplayOnOff; UdpDisplayOn = displayOn; UdpDisplayOff = displayOff; } //LOOP void loop() { //Start: UDP-Datenpakete empfangen //UDP-Daten in einem festen Zeitintervall abfragen if(millis() - LastMillisUdp > IntervallUdp && newdisplay == LOW){ //Systemzeit speichern für den nächsten Vergleich LastMillisUdp = millis(); UdpDataReceive(); } //Ende: UDP-Datenpakete empfangen //Start: NTP-Anfrage //Zeitwerte bei jedem Stundenwechsel aktualisieren if (mezaktstunde != oldmezstunde && newdisplay == LOW && NoWifi == LOW) { //Zeit für den nächsten Vergleich speichern oldmezstunde = mezaktstunde; //Zeitwerte vom NTP-Server anfragen SendNtpRequest(); } //Ende: NTP-Anfrage //Start: Datum und Uhrzeit ermitteln //Kontrolle ob eine Änderung bei dem Zeitstempel stattgefunden hat if(newsecsSince1900 > oldsecsSince1900) { //Änderung abspeichern für den nächsten Vergleich oldsecsSince1900 = newsecsSince1900; //Tage seit dem 1. Januar 1900; 00:00:00 Uhr newtageSeit1900 = newsecsSince1900 / secondperday; //Start: Datum ermitteln //Kontrolle ob eine Änderung bei den Tagen seit dem 1. Januar 1900 stattgefunden hat if(newtageSeit1900 > oldtageSeit1900) { //Änderung abspeichern für den nächsten Vergleich oldtageSeit1900 = newtageSeit1900; //Aufruf der Funktion zur Berechnung des Wochentages wochenTag = wochenTag_calc(newtageSeit1900); //Berechnug der Jahreszahl datumJahr = ((newtageSeit1900 - newschaltTage) / 365.002f) + 1900; //Aufruf der Funktion zur Erkennung ob ein Schaltjahr vorliegt schaltJahr = schaltJahrJN(datumJahr); //Funktion fürs Schaltjahr if(schaltJahr == HIGH) { tageImMonat[2] = 29; //Anzahl der Schalttage seit dem 1. Januar 1900 !ERST! am Ende des jeweiligen Schaltjahres hochzählen //Sonderfall: Zur Berechnung des 366. Tages wird der ""alte"" Wert der Schalttage benötigt, die Berechnung // der Jahreszahl am 366. Tag muss aber mit dem neuen Wert durchgeführt werden //Berechnung der Anzahl der Schalttage seit dem 1. Januar 1900 if(datumMonat == 12 && datumTag == 30) { oldschaltTage = newschaltTage; newschaltTage = newschaltTage + 1; sonderFall366 = HIGH; } } else { tageImMonat[2] = 28; } //Berechnung der wieviele Tag im Jahr //Sonderfall: Die Berechnung des 366. Tages im Schaltjahr muss mit dem ""alten"" Wert der Schalttage (seit 1900) berechnet werden if(sonderFall366 == HIGH) { tagNummer = (newtageSeit1900 - ((datumJahr - 1900) * 365) - oldschaltTage); sonderFall366 = LOW; } //Ansonsten muss mit dem aktuellen Wert der Schalttage (seit 1900) gerechnet werden else { tagNummer = (newtageSeit1900 - ((datumJahr - 1900) * 365) - newschaltTage); } //Aufruf der Funktion zur Berechnung des Monates datumMonat = welcherMonat(tagNummer, schaltJahr); datumTag = 0; //Berechnung der bereits vergangenen Tagen im Jahr for(i = 0; i < datumMonat; i++) { datumTag = datumTag + tageImMonat[i]; } //Tag-Nummer minus bereits vergangener Tage im Jahr = aktueller Tag datumTag = tagNummer - datumTag; } //Ende: Datum ermitteln //Start: Sommer-/ Winterzeit einstellen //am letzten Sonntag im März (03) wird von UTC+1 auf UTC+2 umgestellt; 02:00 -> 03:00 //am letzten Sonntag im Oktober (10) wird von UTC+2 auf UTC+1 umgestellt; 03:00 -> 02:00 //Aufruf jeden Sonntag im März if(datumMonat == 3 && wochenTag == 7) { //Letzter Sonntag im März if((tageImMonat[3] - datumTag) < 7) { //Umstellung auf Sommerzeit UTC+2 utcx = 2; } } //Aufruf jeden Sonntag im Oktober if(datumMonat == 10 && wochenTag == 7) { //Letzter Sonntag im Oktober if((tageImMonat[10] - datumTag) < 7) { //Umstellung auf Winterzeit UTC+1 utcx = 1; } } //Sommer-/Winterzeit bei Neustart bestimmen if(utcx == 0){ //Neustart im Monat März if(datumMonat == 3){ //Neustart in der letzten Woche im März if((tageImMonat[3] - datumTag) < 7){ //Beispiel Jahr 2020: März 31 Tage; Neustart 26. März 2020 (Donnerstag = Wochentag = 4); 5 Tage Rest; Letzter Sonntag 29. März 2020 //Berechnung: 31 - 26 = 5; 5 + 4 = 9; //Ergebnis: Letzter Tag im März ist ein Dienstag. Es folgt noch ein weiterer Sonntag im Oktober => Winterzeit einstellen //Beispiel Jahr 2021: März 31 Tage; Neustart 30. März 2021 (Dienstag = Wochentag = 2); 1 Tage Rest; Letzter Sonntag 28. März 2021 //Berechnung: 31 - 30 = 1; 1 + 2 = 3; //Ergebnis: Letzter Tag im März ist ein Mittwoch. Umstellung auf Sommerzeit bereits erfolgt => Sommerzeit einstellen //Es folgt innerhalb der letzten Woche im März noch ein weiterer Sonntag => Winterzeit einstellen if(((tageImMonat[3] - datumTag) + wochenTag) >= 7){ utcx = 1; } //Letzter Sonntag im März bereits vergangen => Sommerzeit einstellen else{ utcx = 2; } } //Neustart in den ersten drei Wochen im März => Winterzeit einstellen else{ utcx = 1; } } //Neustart im Monat Oktober if(datumMonat == 10){ //Neustart in der letzten Woche im Oktober if((tageImMonat[10] - datumTag) < 7){ //Beispiel Jahr 2020: Oktober 31 Tage; Neustart 26. Oktober 2020 (Montag = Wochentag = 1); 5 Tage Rest; Letzter Sonntag 25. Oktober 2020 //Berechnung: 31 - 26 = 5; 5 + 1 = 6; //Ergebnis: Letzter Tag im Oktober ist ein Samstag. Umstellung auf Winterzeit bereits erfolgt => Winterzeit einstellen //Beispiel Jahr 2021: Oktober 31 Tage; Neustart 26. Oktober 2021 (Dienstag = Wochentag = 2); 5 Tage Rest; Letzter Sonntag 31. Oktober 2021 //Berechnung: 31 - 26 = 5; 5 + 2 = 7; //Ergebnis: Letzter Tag im Oktober ist ein Sonntag. Es folgt noch ein weiterer Sonntag im Oktober => Sommerzeit einstellen //Es folgt innerhalb der letzten Woche im Oktober noch ein weiterer Sonntag => Sommerzeit einstellen if(((tageImMonat[10] - datumTag) + wochenTag) >= 7){ utcx = 2; } //Letzter Sonntag im Oktober bereits vergangen => Winterzeit einstellen else{ utcx = 1; } } //Neustart in den ersten drei Wochen im Oktober => Sommerzeit einstellen else{ utcx = 2; } } //Falls Neustart der Uhr innerhalb der Sommerzeit (Ausnahme März/Oktober) if(datumMonat > 3 && datumMonat < 10) { utcx = 2; } //Falls Neustart der Uhr innerhalb der Winterzeit (Ausnahme März/Oktober) if(datumMonat < 3 || datumMonat > 10) { utcx = 1; } } //Ende: Sommer-/ Winterzeit einstellen //Start: Aktuelle Uhrzeit hh:mm:ss aus dem NTP-Paket ermitteln //Beispiel: Berechnung der aktuellen Stunde //Sekunden seit dem 1. Januar 1900 (3812811794) / Sekunden pro Tag (86400) = 44129 volle Tage seit dem 1. Januar 1900 //Tage seit dem 1. Januar (44129) * Sekunden pro Tag (86400) = 3812745600 Sekunden der vollen Tage seit dem 1. Januar 1900 //Sekunden seit dem 1. Januar 1900 (3812811794) - Sekunden der vollen Tage (3812745600) = 66194 Sekunden am aktuellen Tag vergangen //Sekunden des aktuellen Tages (66194) / Sekunden pro Stunde (3600) = 18 Stunden am aktuellen Tag vergangen => Aktuelle Uhrzeit 18:mm:ss //Berechnung der aktuellen Stunde utcaktstunde = ((newsecsSince1900 % secondperday) / secondperhour); //Berechnung der aktuellen Minute utcaktminute = (newsecsSince1900 % secondperhour) / secondperminute; //Berechnung der aktuellen Sekunde utcaktsekunde = (newsecsSince1900 % secondperminute); //Ende: Aktuelle Uhrzeit hh:mm:ss aus dem NTP-Paket ermitteln } //Ende: Datum und Uhrzeit ermitteln //Start: Uhrzeit über den millis()-Timer berechnen //Alle 1000 ms die Sekunden hochzählen if (millis() - lastmillisSecond > millisecondpersecond){ //Zeitdifferenz lastmillisdifferenz = lastmillisdifferenz + ((millis() - lastmillisSecond) - millisecondpersecond); if(lastmillisdifferenz > millisecondpersecond){ lastmillisdifferenz = 0; utcaktsekunde++; } //Systemzeit speichern für den nächsten Vergleich lastmillisSecond = millis(); utcaktsekunde++; } //Alle 60 s den Minutenzähler hochzählen if(utcaktsekunde >= secondperminute){ //Sekunden zurücksetzen utcaktsekunde = 0; //Minuten hochzählen utcaktminute++; } //Alle 60 min den Stundenzähler hochzählen if(utcaktminute >= minuteperhour){ //Minuten zurücksetzen utcaktminute = 0; //Stunden hochzählen utcaktstunde++; //Wechsel von 24 Uhr zu 1 Uhr if(utcaktstunde == 25){ utcaktstunde = 1; } } //Ende: Uhrzeit über den millis()-Timer berechnen //Start: Von UTC nach MEZ //Sekunden und Minuten unverändert von UTC übernehmen mezaktminute = utcaktminute; mezaktsekunde = utcaktsekunde; //Umrechnung von UTC nach MEZ mittels Zeitverschiebung mezaktstunde = utcaktstunde + utcx; //Aktuelle Stundenzahl in MEZ als 24h Format speichern mezaktstunde24 = mezaktstunde; //Nach ""Halb"" Stundenzahl erhöhen => Beispiel: 16:25:00 => Fünf vor halb Fünf if(mezaktminute >= 23 && mezaktminute <= 59) { mezaktstunde = mezaktstunde + 1; } //Beispiel: UTC = 22:15:00 // MEZ (Winter +1) = 23:15:00 => 23:15:00 => 11:15:00 => viertel nach Elf // MEZ (Sommer +2) = 24:15:00 => 00:15:00 => viertel nach Zwölf //Beispiel: UTC = 23:15:00 // MEZ (Winter +1) = 24:15:00 => 00:15:00 => viertel nach Zwölf // MEZ (Sommer +2) = 25:15:00 => 01:15:00 => viertel nach Eins //Problemstellung 1: Stundenzahlen über 23 abfangen if(mezaktstunde >= 24){ mezaktstunde = mezaktstunde - 24; } //Beispiel: UTC = 10:47:00 // MEZ (Winter +1) = 11:15:00 => 11:15:00 => viertel nach Elf // MEZ (Sommer +2) = 12:15:00 => 00:15:00 => viertel nach Zwölf //Beispiel: UTC = 11:47:00 // MEZ (Winter +1) = 12:15:00 => 00:15:00 => viertel nach Zwölf // MEZ (Sommer +2) = 13:15:00 => 01:15:00 => viertel nach Eins //Problemstellung 2: Stundenzahlen auf den Bereich ""Eins"" bis ""Zwölf"" begrenzen if(mezaktstunde >= 12){ mezaktstunde = mezaktstunde - 12; } //Ende: Von UTC nach MEZ //Start: Stundenzahl ausgeben if(mezaktstunde != oldstunde) { //Stundenzahl für den nächsten Vergleich speichern oldstunde = mezaktstunde; //Bereich für Stundenzahlen auf Null setzen for(i = 0; i <= 11; i++) { startadresse = STUNDENADR[i][0]; endadresse = STUNDENADR[i][1]; for(y = startadresse; y <= endadresse; y++) { newletter[y] = 0; } } //Start- und Endadresse für Ausgabe bestimmen startadresse = STUNDENADR[mezaktstunde][0]; endadresse = STUNDENADR[mezaktstunde][1]; //Neues Wort schreiben for(i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } } //Ende: Stundenzahl ausgeben //Start: Minutenzahl ausgeben if(mezaktminute != oldminute) { //Pointer zurücksetzen pointer = 99; //Minutenzahl für den nächsten Vergleich speichern oldminute = mezaktminute; //Bereich für Minutenzahlen auf Null setzen for(i = 0; i <= 9; i++) { startadresse = MINUTENADR[i][0]; endadresse = MINUTENADR[i][1]; for(y = startadresse; y <= endadresse; y++) { newletter[y] = 0; } } //Wort ""gli"" zurücksetzen // --> SF geändert newletter[8] = 0; newletter[9] = 0; newletter[10] = 0; //Wort ""gsi"" zurücksetzen // --> SF geändert newletter[117] = 0; newletter[118] = 0; newletter[119] = 0; //Füf if(mezaktminute >= 3 && mezaktminute <= 7 || mezaktminute >= 53 && mezaktminute <= 57) { pointer = 0; } //Zää if(mezaktminute >= 8 && mezaktminute <= 12 || mezaktminute >= 48 && mezaktminute <= 52) { pointer = 1; } //Viertu if(mezaktminute >= 13 && mezaktminute <= 17 || mezaktminute >= 43 && mezaktminute <= 47) { pointer = 2; } //Zwänzg if(mezaktminute >= 18 && mezaktminute <= 22 || mezaktminute >= 38 && mezaktminute <= 42) { pointer = 3; } //Haubi if(mezaktminute >= 28 && mezaktminute <= 32) { pointer = 4; } //Ausgabe der aktuellen Minutenzahl if(pointer >= 0 && pointer <= 4) { startadresse = MINUTENADR[pointer][0]; endadresse = MINUTENADR[pointer][1]; for(i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } } //Füf vor/ab Haubi if(mezaktminute >= 23 && mezaktminute <= 27 || mezaktminute >= 33 && mezaktminute <= 37) { //Füf pointer = 0; startadresse = MINUTENADR[pointer][0]; endadresse = MINUTENADR[pointer][1]; for(i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } //Haubi pointer = 4; startadresse = MINUTENADR[pointer][0]; endadresse = MINUTENADR[pointer][1]; for(i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } } //Wort ""ab"" if(mezaktminute >= 3 && mezaktminute <= 22 || mezaktminute >= 33 && mezaktminute <= 37) { pointer = 5; } //Wort ""vor"" if(mezaktminute >= 23 && mezaktminute <= 27 || mezaktminute >= 38 && mezaktminute <= 57) { pointer = 6; } //Wort ""gli"" if (mezaktminute >= 3 && mezaktminute <= 4 || mezaktminute >= 8 && mezaktminute <= 9 || mezaktminute >= 13 && mezaktminute <= 14 || mezaktminute >= 18 && mezaktminute <= 19 || mezaktminute >= 23 && mezaktminute <= 24 || mezaktminute >= 28 && mezaktminute <= 29 || mezaktminute >= 33 && mezaktminute <= 34 || mezaktminute >= 38 && mezaktminute <= 39 || mezaktminute >= 43 && mezaktminute <= 44 || mezaktminute >= 48 && mezaktminute <= 49 || mezaktminute >= 53 && mezaktminute <= 54 || mezaktminute >= 58 && mezaktminute <= 59) { //gli pointer = 7; startadresse = MINUTENADR[pointer][0]; endadresse = MINUTENADR[pointer][1]; //Wort ""ab"" if (mezaktminute >= 3 && mezaktminute <= 22 || mezaktminute >= 33 && mezaktminute <= 37) { pointer = 5; } //Wort ""vor"" if (mezaktminute >= 23 && mezaktminute <= 27 || mezaktminute >= 38 && mezaktminute <= 57) { pointer = 6; } for (i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } } //Wort ""gsi"" if (mezaktminute >= 1 && mezaktminute <= 2 || mezaktminute >= 6 && mezaktminute <= 7 || mezaktminute >= 11 && mezaktminute <= 12 || mezaktminute >= 16 && mezaktminute <= 17 || mezaktminute >= 21 && mezaktminute <= 22 || mezaktminute >= 26 && mezaktminute <= 27 || mezaktminute >= 31 && mezaktminute <= 32 || mezaktminute >= 36 && mezaktminute <= 37 || mezaktminute >= 41 && mezaktminute <= 42 || mezaktminute >= 46 && mezaktminute <= 47 || mezaktminute >= 51 && mezaktminute <= 52 || mezaktminute >= 56 && mezaktminute <= 57) { //gsi pointer = 8; startadresse = MINUTENADR[pointer][0]; endadresse = MINUTENADR[pointer][1]; //Wort ""ab"" if (mezaktminute >= 3 && mezaktminute <= 22 || mezaktminute >= 33 && mezaktminute <= 37) { pointer = 5; } //Wort ""vor"" if (mezaktminute >= 23 && mezaktminute <= 27 || mezaktminute >= 38 && mezaktminute <= 57) { pointer = 6; } for (i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } } //Ausgabe der aktuellen Minutenzahl if(pointer == 5 || pointer == 6) { startadresse = MINUTENADR[pointer][0]; endadresse = MINUTENADR[pointer][1]; for(i = startadresse; i <= endadresse; i++) { newletter[i] = 1; } } // --> SF geändert braucht es in Berndeutsch nicht //Wort ""Uhr"" // // if(mezaktminute == 58 || mezaktminute == 59 || mezaktminute == 0 || mezaktminute == 1 || mezaktminute == 2) { // pointer = 7; // startadresse = MINUTENADR[pointer][0]; // endadresse = MINUTENADR[pointer][1]; // // for(i = startadresse; i <= endadresse; i++) { // newletter[i] = 1; // } // // //Sonderfall: Ein / Ein(s) // if(mezaktstunde == 1) { // endadresse = STUNDENADR[1][0]; // newletter[endadresse] = 0; // } // } // // //Sonderfall: Ein / Ein(s) // if(mezaktminute >= 3 && mezaktminute <= 22) { // // if(mezaktstunde == 1) { // endadresse = STUNDENADR[1][0]; // newletter[endadresse] = 1; // } // } // } //Ende: Minutenzahl ausgeben //Start: Altes Bild mit neuem Bild vergleichen for(i = ersteLED; i <= letzteLED; i++){ //showletter = 1; newletter = 0 => Wort ausschalten if(showletter[i] > newletter[i]){ newdisplay = HIGH; changeletter[i] = 0; } //showletter = 0; newletter = 1 => Wort einschalten if(showletter[i] < newletter[i]){ newdisplay = HIGH; changeletter[i] = 1; } if(showletter[i] == newletter[i]){ changeletter[i] = 2; } } //Ende: Altes Bild mit neuem Bild vergleichen //Start: LED-Display in einem definierten Zeitfenster ausschalten if(UdpEnableDisplay == 1){ //Beispiel: Display On: 5 Uhr; Display Off: 2 Uhr if(UdpDisplayOff < UdpDisplayOn){ if(mezaktstunde24 >= UdpDisplayOff && mezaktstunde24 < UdpDisplayOn){ for(i = ersteLED; i <= letzteLED; i++){ //Angezeigte Wörter im ersten Aufruf ausschalten if(setDisplayOff == LOW){ if(showletter[i] == 1 || newletter[i] == 1){ changeletter[i] = 0; newdisplay = HIGH; } } //Display im Zeitfenster ausgeschaltet lassen else{ changeletter[i] = 2; showletter[i] = 0; newdisplay = LOW; } } } else{ setDisplayOff = LOW; } } //Beispiel: Display On: 6 Uhr; Display Off: 23 Uhr else{ if(mezaktstunde24 >= UdpDisplayOff || mezaktstunde24 < UdpDisplayOn){ for(i = ersteLED; i <= letzteLED; i++){ //Angezeigte Wörter im ersten Aufruf ausschalten if(setDisplayOff == LOW){ if(showletter[i] == 1 || newletter[i] == 1){ changeletter[i] = 0; newdisplay = HIGH; } } //Display im Zeitfenster ausgeschaltet lassen else{ changeletter[i] = 2; showletter[i] = 0; newdisplay = LOW; } } } else{ setDisplayOff = LOW; } } } else{ setDisplayOff = LOW; } //Ende: LED-Display in einem definierten Zeitfenster ausschalten //Start: Ausgabe des Bildes if(newdisplay == HIGH) { //Farbwerte in dem eingestellten Intervall dimmen if (millis() - lastmillisFade > intervallFade) { //Systemzeit speichern für den nächsten Vergleich lastmillisFade = millis(); //Farbwerte reduzieren ""herunterdimmen"" if(newredminus > 0.0){ newredminus = newredminus - fadevaluered; if(newredminus <= 0.0){ newredminus = 0.0; newgreenminus = 0.0; newblueminus = 0.0; } } //Farbwerte reduzieren ""herunterdimmen"" if(newgreenminus > 0.0){ newgreenminus = newgreenminus - fadevaluegreen; if(newgreenminus <= 0.0){ newredminus = 0.0; newgreenminus = 0.0; newblueminus = 0.0; } } //Farbwerte reduzieren ""herunterdimmen"" if(newblueminus > 0.0){ newblueminus = newblueminus - fadevalueblue; if(newblueminus <= 0.0){ newredminus = 0.0; newgreenminus = 0.0; newblueminus = 0.0; } } //Farbwerte erhöhen ""hochdimmen"" if(newredplus < UdpRgbRed){ newredplus = newredplus + fadevaluered; if(newredplus >= UdpRgbRed){ newredplus = UdpRgbRed; newgreenplus = UdpRgbGreen; newblueplus = UdpRgbBlue; } } //Farbwerte erhöhen ""hochdimmen"" if(newgreenplus < UdpRgbGreen){ newgreenplus = newgreenplus + fadevaluegreen; if(newgreenplus >= UdpRgbGreen){ newredplus = UdpRgbRed; newgreenplus = UdpRgbGreen; newblueplus = UdpRgbBlue; } } //Farbwerte erhöhen ""hochdimmen"" if(newblueplus < UdpRgbBlue){ newblueplus = newblueplus + fadevalueblue; if(newblueplus >= UdpRgbBlue){ newredplus = UdpRgbRed; newgreenplus = UdpRgbGreen; newblueplus = UdpRgbBlue; } } //Neue Farbwerte an die LED's übermitteln for(i = ersteLED; i <= letzteLED; i++){ red = newredminus; green = newgreenminus; blue = newblueminus; if(changeletter[i] == 0){ pixels.setPixelColor(i, pixels.Color(red,green,blue)); } red = newredplus; green = newgreenplus; blue = newblueplus; if(changeletter[i] == 1){ pixels.setPixelColor(i, pixels.Color(red,green,blue)); } } //LED's aktualisieren pixels.show(); } //Bild wurde komplett aktualisiert if(newredminus <= 0.0 && newgreenminus <= 0.0 && newblueminus <= 0.0 && newredplus >= UdpRgbRed && newgreenplus >= UdpRgbGreen && newblueplus >= UdpRgbBlue){ //Arrays kopieren für den nächsten Vergleich for(i = ersteLED; i <= letzteLED; i++) { showletter[i] = newletter[i]; } //Start: Aktuelle Stromaufnahme ermitteln currentPerLed = 0; //Aktuelle Stromfaufnahme mittels RGB-Wert und Anzahl der aktiven LED's ermitteln //Die Stromaufnahme wird dabei nicht gemessen, sondern mit einem Faktor und der Anzahl der aktiven LED's berechnet for(i = ersteLED; i <= letzteLED; i++){ if(showletter[i] == 1){ currentPerLed = currentPerLed + round((float)(currentPerRgbValue * (red + green + blue))); } } //Ende: Aktuelle Stromaufnahme ermitteln //Aktualisierung des Bildes beenden newdisplay = LOW; setDisplayOff = HIGH; //Farbwerte für die nächste Aktualisierung zurücksetzen newredminus = UdpRgbRed; newgreenminus = UdpRgbGreen; newblueminus = UdpRgbBlue; newredplus = 0.0; newgreenplus = 0.0; newblueplus = 0.0; } } //Ende: Ausgabe des Bildes //Start: Ausgabe fürs Debuging if(debug == HIGH && newdisplay == LOW) { if (millis() - lastmillisDebug > intervallDebug) { //Systemzeit speichern für den nächsten Vergleich lastmillisDebug = millis(); Serial.print(""lokale IP-Adresse: ""); Serial.println(WiFi.localIP()); Serial.print(""NTP-Paket: ""); Serial.println(newsecsSince1900); Serial.print(""Zeitdifferenz: ""); Serial.print(lastmillisdifferenz); Serial.println(""ms""); Serial.print(""Uhrzeit UTC: ""); Serial.print(utcaktstunde); Serial.print("":""); Serial.print(utcaktminute); Serial.print("":""); Serial.println(utcaktsekunde); Serial.print(""Zeitverschiebung: ""); Serial.println(utcx); Serial.print(""Uhrzeit MEZ: ""); Serial.print(mezaktstunde24); Serial.print("":""); Serial.print(mezaktminute); Serial.print("":""); Serial.println(mezaktsekunde); Serial.print(""Datum: ""); Serial.print(datumTag); Serial.print("".""); Serial.print(datumMonat); Serial.print("".""); Serial.println(datumJahr); Serial.print(""Wochentag: ""); Serial.println(wochenTag); Serial.print(""Schaltjahr: ""); Serial.println(schaltJahr); Serial.print(""Anzahl Schalttage: ""); Serial.println(newschaltTage); Serial.print(""Nachtmodus aktiv: ""); Serial.println(UdpEnableDisplay); Serial.print(""Display ausschalten um: ""); Serial.print(UdpDisplayOff); Serial.println("" Uhr""); Serial.print(""Display einschalten um: ""); Serial.print(UdpDisplayOn); Serial.println("" Uhr""); Serial.print(""Display Aus: ""); Serial.println(setDisplayOff); Serial.print(""RGB-Farbwert Rot: ""); Serial.print(UdpRgbRed); Serial.println(""/255""); Serial.print(""RGB-Farbwert Grün: ""); Serial.print(UdpRgbGreen); Serial.println(""/255""); Serial.print(""RGB-Farbwert Blau: ""); Serial.print(UdpRgbBlue); Serial.println(""/255""); Serial.print(""Faktor Dimmen Rot: ""); Serial.println(fadevaluered); Serial.print(""Faktor Dimmen Grün: ""); Serial.println(fadevaluegreen); Serial.print(""Faktor Dimmen Blau: ""); Serial.println(fadevalueblue); Serial.print(""Stromaufnahme: ""); Serial.print(currentPerLed); Serial.println(""mA""); Serial.println(); } } //Ende: Ausgabe fürs Debuging } //Funktion UDP-Daten empfangen void UdpDataReceive(){ unsigned int PaketSize = 0; PaketSize = udp.parsePacket(); if(PaketSize != 0){ if(PaketSize == NtpPaketSize){ udp.read(NtpPaketBuffer, NtpPaketSize); newsecsSince1900 = GetNtpTimestamp(NtpPaketBuffer); } else if(PaketSize == UserInterfacePaketSize){ udp.read(UserInterfacePaketBuffer, UserInterfacePaketSize); UserInterface(UserInterfacePaketBuffer); } else{ //Nothing to do here } } } //Funktion Nutzerdaten aus UDP-Daten auslesen int UserInterfaceGetValue(byte Data[], int PointerStart, int PointerEnd){ int Value = 0; Value = Data[PointerStart]; Value |= Data[PointerEnd] << 8; return Value; } //Funktion Handshake bool HandshakeOk(byte Data[]){ bool HandshakeOk = HIGH; int HandshakeOkCount = 0; for(HandshakeOkCount = 2; HandshakeOkCount < 12; HandshakeOkCount++){ if(Data[HandshakeOkCount] != 0){ HandshakeOk = LOW; } } return HandshakeOk; } //Funktion Nutzerdaten übergeben void UserInterface(byte UserInterfaceData[]) { //ID-Nummer UdpId = UserInterfaceGetValue(UserInterfaceData,0,1); switch(UdpId){ case UdpIdHandshakeRequest: if(HandshakeOk(UserInterfaceData)){ UserInterfaceData[0] = UdpIdHandshakeAnswer; UserInterfaceIp = udp.remoteIP(); udp.beginPacket(UserInterfaceIp, localPort); udp.write(UserInterfaceData, 12); udp.endPacket(); } break; case UdpIdRgb: UdpRgbRed = UserInterfaceGetValue(UserInterfaceData,2,3); UdpRgbGreen = UserInterfaceGetValue(UserInterfaceData,4,5); UdpRgbBlue = UserInterfaceGetValue(UserInterfaceData,6,7); newredminus = UdpRgbRed; newgreenminus = UdpRgbGreen; newblueminus = UdpRgbBlue; fadevaluered = FadeValueRed(UdpRgbRed,UdpRgbGreen,UdpRgbBlue); fadevaluegreen = FadeValueGreen(UdpRgbRed,UdpRgbGreen,UdpRgbBlue); fadevalueblue = FadeValueBlue(UdpRgbRed,UdpRgbGreen,UdpRgbBlue); //Farbwerte um x Nachkommastellen verschieben for(i = 0; i <= 10; i++) { if(fadevaluered < 1.0 && fadevaluegreen < 1.0 && fadevalueblue < 1.0){ break; } fadevaluered = fadevaluered / 10.0; fadevaluegreen = fadevaluegreen / 10.0; fadevalueblue = fadevalueblue / 10.0; } //Arrays kopieren für den nächsten Vergleich for(i = ersteLED; i <= letzteLED; i++) { if(showletter[i] == 1){ pixels.setPixelColor(i, pixels.Color(UdpRgbRed,UdpRgbGreen,UdpRgbBlue)); } } //LED's aktualisieren pixels.show(); break; case UdpIdTime: UdpHour = UserInterfaceGetValue(UserInterfaceData,2,3); UdpMinute = UserInterfaceGetValue(UserInterfaceData,4,5); UdpSecond = UserInterfaceGetValue(UserInterfaceData,6,7); if(NoWifi == HIGH){ utcaktstunde = UdpHour; utcaktminute = UdpMinute; utcaktsekunde = UdpSecond; utcx = 0; } break; case UdpIdDate: UdpDay = UserInterfaceGetValue(UserInterfaceData,2,3); UdpMonth = UserInterfaceGetValue(UserInterfaceData,4,5); UdpYear = UserInterfaceGetValue(UserInterfaceData,6,7); break; case UdpIdDisplay: UdpEnableDisplay = UserInterfaceGetValue(UserInterfaceData,2,3); UdpDisplayOn = UserInterfaceGetValue(UserInterfaceData,4,5); UdpDisplayOff = UserInterfaceGetValue(UserInterfaceData,6,7); setDisplayOff = LOW; break; } } //Funktion Dimmwerte Rot berechnen float FadeValueRed(int Red, int Green, int Blue){ float Value = 1.0; if(Red == 0){ Value = 0.0; return Value; } //Ab hier hat Rot einen Wert //Drei Werte vorhanden if(Green > 0 && Blue > 0){ if(Green <= Red && Green <= Blue){ Value = (float)Red / Green; } if(Blue <= Red && Blue <= Green){ Value = (float)Red / Blue; } return Value; } //Ab hier haben entweder Grün oder Blau eine Null oder Beide //Rot und Grün mit Werten; Blau muss Null sein if(Green > 0 && Green < Red){ Value = (float)Red / Green; return Value; } //Ab hier hat Grün eine Null und Blau fraglich //Rot und Blau if(Blue > 0 && Blue < Red){ Value = (float)Red / Blue; return Value; } //Ab hier nur Rot vorhanden oder Rot ist kleinster Wert return Value; } //Funktion Dimmwerte Grün berechnen float FadeValueGreen(int Red, int Green, int Blue){ float Value = 1.0; if(Green == 0){ Value = 0.0; return Value; } //Ab hier hat Grün einen Wert //Drei Werte vorhanden if(Red > 0 && Blue > 0){ if(Red <= Green && Red <= Blue){ Value = (float)Green / Red; } if(Blue <= Green && Blue <= Red){ Value = (float)Green / Blue; } return Value; } //Ab hier haben entweder Rot oder Blau eine Null oder Beide //Grün und Rot mit Werten; Blau muss Null sein if(Red > 0 && Red < Green){ Value = (float)Green / Red; return Value; } //Ab hier hat Rot eine Null und Blau fraglich //Grün und Blau if(Blue > 0 && Blue < Green){ Value = (float)Green / Blue; return Value; } //Ab hier nur Grün vorhanden oder Grün ist kleinster Wert return Value; } //Funktion Dimmwerte Blau berechnen float FadeValueBlue(int Red, int Green, int Blue){ float Value = 1.0; if(Blue == 0){ Value = 0.0; return Value; } //Ab hier hat Blau einen Wert //Drei Werte vorhanden if(Red > 0 && Green > 0){ if(Red <= Blue && Red <= Green){ Value = (float)Blue / Red; } if(Green <= Blue && Green <= Red){ Value = (float)Blue / Green; } return Value; } //Ab hier haben entweder Rot oder Grün eine Null oder Beide //Blau und Rot mit Werten; Grün muss Null sein if(Red > 0 && Red < Blue){ Value = (float)Blue / Red; return Value; } //Ab hier hat Rot eine Null und Grün fraglich //Blau und Grün if(Green > 0 && Green < Blue){ Value = (float)Blue / Green; return Value; } //Ab hier nur Blau vorhanden oder Blau ist kleinster Wert return Value; } //Funktion NTP-Daten abrufen void SendNtpRequest() { //Verbindung zu einem NTP-Server aus dem Pool aufbauen WiFi.hostByName(NtpServerName, TimeServerIp); //NTP-Anfrage an den Server stellen SendNtpPaket(TimeServerIp); delay(50); } //Funktion NTP-Zeitstempel auslesen long GetNtpTimestamp(byte NtpData[]){ unsigned long NtpTimestamp = 0; //Der Zeitstempel befindet sich im Byte 40, 41, 42, 43 //Zeitstempel aus den vier Bytes auslesen => Ergebnis: Sekunden seit dem 1. Januar 1900, 00:00:00 Uhr NtpTimestamp = word(NtpData[40], NtpData[41]) << 16 | word(NtpData[42], NtpData[43]); return NtpTimestamp; } //Funktion zur Anfrage eines NTP-Paketes void SendNtpPaket(IPAddress& address) { memset(NtpPaketBuffer, 0, NtpPaketSize); //Erstes Byte //Leap Indicator: Bit 0, 1 => 11 => 3 => Schaltsekunde wird nicht synchronisiert //Version: Bit Bit 2, 3, 4 => 000 => 0 => Version xy? //Mode: Bit 5, 6, 7 => 111 => 7 => für den Privaten Gebrauch NtpPaketBuffer[0] = 0b11100011; //Zweites Byte //Stratum: Bit 0 - 7 => 00000000 => 0 => nicht angegeben NtpPaketBuffer[1] = 0; //Drittes Byte //Poll: Bit 0 - 7 => 00000110 => 6 => Abfrageintervall NtpPaketBuffer[2] = 6; //Viertes Byte //Precision: Bit 0 - 7 => 0xEC => Taktgenauigkeit NtpPaketBuffer[3] = 0xEC; //Die nächsten 8 Byte haben nur für Servernaachrichten eine Bedeutung //8 Bytes => 0 NtpPaketBuffer[12] = 49; NtpPaketBuffer[13] = 0x4E; NtpPaketBuffer[14] = 49; NtpPaketBuffer[15] = 52; udp.beginPacket(address, 123); udp.write(NtpPaketBuffer, NtpPaketSize); udp.endPacket(); } //Funktion zur Berechnung des Wochentages //Montag = 1, Dienstag = 2, Mittwoch = 3, Donnerstag = 4, Freitag = 5, Samstag = 6, Sonntag = 7 unsigned int wochenTag_calc(unsigned long tage1900) { //Der 1. Januar 1900 war ein Montag unsigned int ergebnis = 1; int for_i = 0; for(for_i = 0; for_i < tage1900; for_i++) { if(ergebnis < 7) { ergebnis = ergebnis + 1; } else { ergebnis = 1; } } return ergebnis; } //Funktion zur Berechnung der Jahreszahl unsigned int datumJahr_calc(unsigned long sec1900) { //NTP beginnt am 1. Januar 1900 unsigned int ergebnis = 1900; unsigned int tageimjahr = 0; unsigned int tage = 0; unsigned int tage1900 = 0; int for_i = 0; bool schaltjahr = LOW; tage1900 = sec1900 / 86400; for(for_i = 0; for_i < tage1900; for_i++){ schaltjahr = schaltJahrJN(ergebnis); if(schaltjahr){ tageimjahr = 366; } else{ tageimjahr = 365; } tage++; if(tage >= tageimjahr){ ergebnis++; tage = 0; } } return ergebnis; } //Funktion zur Erkennung ob ein Schaltjahr vorliegt bool schaltJahrJN(unsigned int jahr) { bool ergebnis_jn = LOW; //Erkennung von Schaltjahren if((jahr % 4) == 0) { ergebnis_jn = HIGH; if((jahr % 100) == 0) { ergebnis_jn = LOW; if((jahr % 400) == 0) { ergebnis_jn = HIGH; } } } else { ergebnis_jn = LOW; } return ergebnis_jn; } //Funktion zur Berechnung des Monates int welcherMonat(int tg_nr, bool schaltjn) { //Monatsanfänge int monatMin[13] = {0, 1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}; //Monatsenden int monatMax[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; int datum = 0; int y = 0; //Berechnung des Anfang und Ende jeden Montas im Schaltjahr if(schaltjn == HIGH) { for(y = 3; y < 13; y++) { monatMin[y] = monatMin[y] + 1; } for(y = 2; y < 13; y++) { monatMax[y] = monatMax[y] + 1; } } //Monat Januar if(tg_nr >= monatMin[1] && tg_nr <= monatMax[1]) { datum = 1; } //Monat Februar if(tg_nr >= monatMin[2] && tg_nr <= monatMax[2]) { datum = 2; } //Monat März if(tg_nr >= monatMin[3] && tg_nr <= monatMax[3]) { datum = 3; } //Monat April if(tg_nr >= monatMin[4] && tg_nr <= monatMax[4]) { datum = 4; } //Monat Mai if(tg_nr >= monatMin[5] && tg_nr <= monatMax[5]) { datum = 5; } //Monat Juni if(tg_nr >= monatMin[6] && tg_nr <= monatMax[6]) { datum = 6; } //Monat Juli if(tg_nr >= monatMin[7] && tg_nr <= monatMax[7]) { datum = 7; } //Monat August if(tg_nr >= monatMin[8] && tg_nr <= monatMax[8]) { datum = 8; } //Monat September if(tg_nr >= monatMin[9] && tg_nr <= monatMax[9]) { datum = 9; } //Monat Oktober if(tg_nr >= monatMin[10] && tg_nr <= monatMax[10]) { datum = 10; } //Monat November if(tg_nr >= monatMin[11] && tg_nr <= monatMax[11]) { datum = 11; } //Monat Dezember if(tg_nr >= monatMin[12] && tg_nr <= monatMax[12]) { datum = 12; } return datum; } ",16218,True,3022.1917120215717,median "REPORT /ctac/alv_template. "" <<< DO CHANGE *Source: Template for an ALV Report, Enhancing the Quality of ABAP Development *$*$----------------------------------------------------------------* *$*$ Company : Ctac Nederland *$*$ Author : Wouter Heuvelmans / Ben Meijs *$*$ Date : May 2004 *$*$ SAP rel. : 6.20 *$*$ Transport: *$*$ Purpose : Template For ALV Reports *$*$ This template can be used as a basis for ALV Reports. *$*$ After copying this template, you need to implement the *$*$ following components: *$*$ - Copy status STANDARD of function group SALV to the *$*$ program and adjust the status to your needs *$*$ - implement the selectionscreen as needed *$*$ - implement subroutine A001_SELECTION *$*$ - add the ALV structure with all displayfields to the *$*$ Dictionary *$*$ - adjust the TYPE-definition for *$*$ - ta_list (ALV output table); *$*$ - adjust the VALUE-declaration for the constants *$*$ - co_struc = name of the DDIC ALV structure used *$*$ - implement your own GUI functions in subroutine *$*$ defined in constant CO_ROUT_UCOMM. *$*$ - implement the headertexts in subroutine BUILD_COMMENT *$*$ - if you need a second ALV list which is activated by *$*$ one of your own GUI functions, you'll have to *$*$ implement the following subroutines: *$*$ * BUILD_SEC_LIST *$*$ * DISPLAY_SEC_LIST *$*$ * MODIFY_FIELDCAT_SEC *$*$ * CHANGE_LAYOUT_SEC *$*$ *$*$----------------------------------------------------------------* *$*$----------------------------------------------------------------* *$*$ M O D I F I C A T I O N S * *$*$----------------------------------------------------------------* *& Changed By : *& Date : *& SAP rel. : *& Transport : *& Purpose : *&------------------------------------------------------------------* *$*$----------------------------------------------------------------* *$*$ G L O B A L D A T A D E C L A R A T I O N * *$*$----------------------------------------------------------------* *$*$----------------------------------------------------------------* *$*$ Type pool declarations *$*$----------------------------------------------------------------* TYPE-POOLS: slis, ""ALV types / constants sdydo, abap, ""ABAP reporting types / constants icon. ""Possible icons *$*$----------------------------------------------------------------* *-- Constants *$*$----------------------------------------------------------------* CONSTANTS: co_background_alv TYPE sdydo_key VALUE 'ALV_WALLPAPER', co_save TYPE c VALUE 'A', co_msgty_inf TYPE symsgty VALUE 'I'. *----------------------------------------------------------------------* * Constants for interactive functions of an ALV *----------------------------------------------------------------------* CONSTANTS: co_double_click TYPE syucomm VALUE '&IC1', ""CHOOSE / F2 *----------------------------------------------------------------------* * Customer interactive functions for the ALV *----------------------------------------------------------------------* co_sec_list TYPE syucomm VALUE 'SEC_LIST'. ""Secundary list *----------------------------------------------------------------------* * Names of the routines to be called dynamically from the ALV function *----------------------------------------------------------------------* CONSTANTS: co_rout_pf_stat TYPE char30 VALUE 'R0_SET_PF_STATUS', co_rout_ucomm TYPE char30 VALUE 'R1_PROCESS_USER_COMMAND', co_rout_top_of_page TYPE char30 VALUE 'R2_SET_TOP_OF_PAGE', co_rout_html_top TYPE char30 VALUE 'R3_SET_HTML_TOP_OF_PAGE', co_rout_html_end TYPE char30 VALUE 'R4_SET_HTML_END_OF_LIST', co_rout_pf_stat_sec TYPE char30 VALUE 'R5_SET_PF_STATUS_SEC', co_rout_ucomm_sec TYPE char30 VALUE 'R6_PROCESS_UCOMM_SEC', co_rout_top_page_sec TYPE char30 VALUE 'R7_SET_TOP_OF_PAGE_SEC'. CONSTANTS: co_struc TYPE tabname VALUE '/CTAC/S_ALV_STRUCTURE', co_struc_sec TYPE tabname VALUE '/CTAC/S_ALV_STRUC_SEC'. *$*$----------------------------------------------------------------* *$*$ Data definitions *$*$----------------------------------------------------------------* *TYPES: . *$*$----------------------------------------------------------------* *$*$ Data declarations *-- Internal Tables *$*$----------------------------------------------------------------* * TA_LIST is the internal table containing the data to be outputted * by ALV *----------------------------------------------------------------------* DATA: ta_list TYPE TABLE OF /ctac/s_alv_structure. *----------------------------------------------------------------------* * Internal tables, needed for ALV formatting *----------------------------------------------------------------------* DATA: ta_comment TYPE slis_t_listheader. ""Top of page of the ALV *$*$----------------------------------------------------------------* *-- Work areas / records *$*$----------------------------------------------------------------* DATA: st_s_variant TYPE disvariant, ""Display Variant (Ext. Use) st_s_var_usr TYPE disvariant. *$*$----------------------------------------------------------------* *-- Temporary Fields / Variables *$*$----------------------------------------------------------------* DATA: tp_repid_this TYPE syrepid. * *$*$----------------------------------------------------------------* *$*$ S E L E C T I O N S C R E E N * *$*$----------------------------------------------------------------* *$*$ Define your selection-criteria here * *$*$----------------------------------------------------------------* SELECTION-SCREEN: BEGIN OF BLOCK s01 WITH FRAME TITLE text-s01. *SELECT-OPTIONS: FOR . *PARAMETERS: TYPE . SELECTION-SCREEN: END OF BLOCK s01. *$*$----------------------------------------------------------------* *$*$ This block is meant for giving the user the possibility to * *$*$ define whether the output should be printed directly. * *$*$----------------------------------------------------------------* SELECTION-SCREEN: BEGIN OF BLOCK immed WITH FRAME TITLE text-imm. SELECTION-SCREEN: BEGIN OF LINE. SELECTION-SCREEN: COMMENT 1(31) text-c01. "" Output directly to printer? PARAMETERS: pa_print AS CHECKBOX. SELECTION-SCREEN: END OF LINE. SELECTION-SCREEN: END OF BLOCK immed. *$*$----------------------------------------------------------------* *$*$ This block is meant for giving the user the possibility to * *$*$ choose an ALV variant on the selection-screen * *$*$----------------------------------------------------------------* SELECTION-SCREEN: BEGIN OF BLOCK variant WITH FRAME TITLE text-var. PARAMETERS: pa_varia TYPE slis_vari. SELECTION-SCREEN: END OF BLOCK variant. *&------------------------------------------------------------------* *$*$----------------------------------------------------------------* *$*$ I N I T I A L I Z A T I O N * *$*$----------------------------------------------------------------* *INITIALIZATION. *$*$----------------------------------------------------------------* *$*$ A T S E L E C T I O N S C R E E N * *$*$----------------------------------------------------------------* *-- Selection screen output *AT SELECTION-SCREEN OUTPUT. *-- Selection screen processing AT SELECTION-SCREEN. PERFORM process_output_variant USING pa_varia CHANGING st_s_variant st_s_var_usr. AT SELECTION-SCREEN ON VALUE-REQUEST FOR pa_varia. *----------------------------------------------------------------------* * Handling possible values for the ALV Display Variant *----------------------------------------------------------------------* PERFORM get_possible_variants CHANGING pa_varia st_s_variant st_s_var_usr. *$*$----------------------------------------------------------------* *$*$ M A I N P R O C E S S I N G * *$*$----------------------------------------------------------------* START-OF-SELECTION. PERFORM init_report. *----------------------------------------------------------------------* * Select the data that is going to be displayed in the ALV *----------------------------------------------------------------------* PERFORM select_data TABLES ta_list. END-OF-SELECTION. *----------------------------------------------------------------------* * Finish the internal table that is going to be displayed in the ALV. *----------------------------------------------------------------------* PERFORM process_data TABLES ta_list. *----------------------------------------------------------------------* * Call the correct function to display the ALV data. *----------------------------------------------------------------------* PERFORM display_data TABLES ta_list. *$*$----------------------------------------------------------------* *$*$ F O R M R O U T I N E S * *$*$----------------------------------------------------------------* *&---------------------------------------------------------------------* *& Form init_report *&---------------------------------------------------------------------* * One time actions that are required at this moment. *----------------------------------------------------------------------* FORM init_report . tp_repid_this = sy-repid. ""or sy-cprog ENDFORM. "" init_report *&--------------------------------------------------------------------* *& Form select_data *&--------------------------------------------------------------------* * Build internal table TA_LIST *---------------------------------------------------------------------* FORM select_data TABLES tta_list STRUCTURE /ctac/s_alv_structure. *---------------------------------------------------------------------* * For example, build the internal table from the purchase header database. *---------------------------------------------------------------------* * SELECT * FROM ekko * INTO TABLE tta_list * WHERE ebeln IN so_ebeln. ENDFORM. "" select_data *&--------------------------------------------------------------------* *& Form process_data *&--------------------------------------------------------------------* * Process the selected data so that it can be used in the ALV. *---------------------------------------------------------------------* FORM process_data TABLES tta_list STRUCTURE /ctac/s_alv_structure. SORT tta_list. ENDFORM. "" process_data *&--------------------------------------------------------------------* *& Form display_data *&--------------------------------------------------------------------* * Prepare the ALV output. * Display output in ALV format. * If SAPGUI is available, the GRID will be displayed. * In other situations, the LIST will be displayed. *---------------------------------------------------------------------* FORM display_data TABLES tta_list STRUCTURE /ctac/s_alv_structure. *---------------------------------------------------------------------* * Comment: * Define all data locally, except when you explicitly need it globally! *---------------------------------------------------------------------* DATA: lta_fcat TYPE slis_t_fieldcat_alv. ""Field Catalog DATA: lta_extab TYPE slis_t_extab. ""Excl. Functions DATA: lta_spec_groups TYPE slis_t_sp_group_alv. ""Spec. groups DATA: lta_sort_alv TYPE slis_t_sortinfo_alv. DATA: lta_filter TYPE slis_t_filter_alv. DATA: lta_events TYPE slis_t_event. DATA: lta_event_exit TYPE slis_t_event_exit. DATA: lta_alv_graphics TYPE dtc_t_tc. DATA: lta_add_fieldcat TYPE slis_t_add_fieldcat. DATA: lta_hyperlink TYPE lvc_t_hype. DATA: lst_layout TYPE slis_layout_alv, ""Layout Settings lst_is_print TYPE slis_print_alv, lst_sel_hide TYPE slis_sel_hide_alv, lst_exit_user TYPE slis_exit_by_user. DATA: ltp_title TYPE lvc_title, ltp_gui_active TYPE boolean, ltp_tdline TYPE tdline, ltp_reprep_id TYPE slis_reprep_id, ltp_html_hght_top TYPE i, ltp_html_hght_end TYPE i, ltp_exit_caller(1) TYPE c. *----------------------------------------------------------------------* * First we build the field catalog. * This internal table is required to determine which fields of the internal * table are to be displayed and how they should be displayed. *----------------------------------------------------------------------* PERFORM build_fieldcatalog USING co_struc CHANGING lta_fcat[]. *----------------------------------------------------------------------* * After building the field catalog (e.g., from a DDIC structure), we can * modify these settings in the following subroutine. *----------------------------------------------------------------------* PERFORM modify_fieldcatalog CHANGING lta_fcat[]. *----------------------------------------------------------------------* * Also, we can modify the layout settings. *----------------------------------------------------------------------* PERFORM change_layout_settings CHANGING lst_layout. *----------------------------------------------------------------------* * Set title *----------------------------------------------------------------------* ltp_title = sy-title. *----------------------------------------------------------------------* * Table ta_comment is used to display header information in the * top-of-page of the ALV output. *----------------------------------------------------------------------* PERFORM build_comment CHANGING ta_comment[]. *----------------------------------------------------------------------* * Determine whether the report is executed within a SAPGUI environment. * We need to know whether GUI-controls are accessible. * If not, we use function module REUSE_ALV_LIST_DISPLAY (without * controls) instead of function module REUSE_ALV_GRID_DISPLAY. *----------------------------------------------------------------------* CALL FUNCTION 'GUI_IS_AVAILABLE' IMPORTING return = ltp_gui_active. *----------------------------------------------------------------------* * If we send the output directly to the printer, we can * deactivate the GUI-setting and select the LIST-variant of the ALV. *----------------------------------------------------------------------* IF pa_print = abap_true. lst_is_print-print = 'X'. CLEAR ltp_gui_active. ENDIF. IF ltp_gui_active = abap_true. *----------------------------------------------------------------------* * GUI active -> Activate the ALV GRID (control enabled) *----------------------------------------------------------------------* CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING i_callback_program = tp_repid_this i_callback_pf_status_set = co_rout_pf_stat i_callback_user_command = co_rout_ucomm i_callback_top_of_page = co_rout_top_of_page * i_callback_html_top_of_page = co_rout_html_top "" * i_callback_html_end_of_list = co_rout_html_end "" i_background_id = co_background_alv * i_structure_name = co_struc "" i_grid_title = ltp_title is_layout = lst_layout it_fieldcat = lta_fcat[] * it_excluding = lta_extab[] "" * it_special_groups = lta_spec_groups[] "" * it_sort = lta_sort_alv[] "" * it_filter = lta_filter[] "" * is_sel_hide = lst_sel_hide "" i_default = abap_true i_save = co_save is_variant = st_s_variant * it_events = lta_events[] "" * it_event_exit = lta_event_exit[] "" is_print = lst_is_print * is_reprep_id = ltp_reprep_id "" * i_screen_start_column = 0 "" * i_screen_start_line = 0 "" * i_screen_end_column = 0 "" * i_screen_end_line = 0 "" * it_alv_graphics = lta_alv_graphics[] "" * it_add_fieldcat = lta_add_fieldcat[] "" * it_hyperlink = lta_hyperlink[] "" * i_html_height_top = ltp_html_hght_top "" * i_html_height_end = ltp_html_hght_end "" * IMPORTING "" * e_exit_caused_by_caller = ltp_exit_caller "" * es_exit_caused_by_user = lst_exit_user "" TABLES t_outtab = ta_list EXCEPTIONS program_error = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ELSE. *----------------------------------------------------------------------* * GUI not active -> ALV LIST displayed in Background. * All parameters for interactive processing need not be supplied. *----------------------------------------------------------------------* CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY' EXPORTING * i_interface_check = space "" * i_bypassing_buffer = space "" * i_buffer_active = space "" i_callback_program = tp_repid_this * i_callback_pf_status_set = co_rout_pf_stat "" * i_callback_user_command = co_rout_ucomm "" * i_structure_name = co_struc "" is_layout = lst_layout it_fieldcat = lta_fcat[] * it_excluding = lta_extab[] "" * it_special_groups = lta_spec_groups[] "" * it_sort = lta_sort_alv[] "" * it_filter = lta_filter[] "" * is_sel_hide = lst_sel_hide "" i_default = abap_true * i_save = co_save "" is_variant = st_s_variant * it_events = lta_events[] "" * it_event_exit = lta_event_exit[] "" is_print = lst_is_print * is_reprep_id = ltp_reprep_id "" * i_screen_start_column = 0 "" * i_screen_start_line = 0 "" * i_screen_end_column = 0 "" * i_screen_end_line = 0 "" * IMPORTING * e_exit_caused_by_caller = ltp_exit_caller "" * es_exit_caused_by_user = lst_exit_user "" TABLES t_outtab = tta_list EXCEPTIONS program_error = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDIF. ENDFORM. "" display_data *&--------------------------------------------------------------------* *& Form get_possible_variants *&--------------------------------------------------------------------* * Handle request for possible values on the output variant. *---------------------------------------------------------------------* FORM get_possible_variants CHANGING ctp_varia TYPE slis_vari cst_s_variant TYPE disvariant cst_s_var_usr TYPE disvariant. DATA: ltp_exit(1) TYPE c. PERFORM init_variant USING sy-repid CHANGING cst_s_variant. CALL FUNCTION 'REUSE_ALV_VARIANT_F4' EXPORTING is_variant = cst_s_variant i_save = co_save IMPORTING e_exit = ltp_exit es_variant = cst_s_var_usr EXCEPTIONS not_found = 1 program_error = 2 OTHERS = 3. CASE sy-subrc. WHEN 0. IF ltp_exit = abap_false. ctp_varia = st_s_var_usr-variant. ENDIF. WHEN 1. MESSAGE ID sy-msgid TYPE co_msgty_inf NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. WHEN 2. MESSAGE ID sy-msgid TYPE co_msgty_inf NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. WHEN 3. MESSAGE ID sy-msgid TYPE co_msgty_inf NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDCASE. ENDFORM. "" get_possible_variants *&--------------------------------------------------------------------* *& Form init_variant *&--------------------------------------------------------------------* * Initialize the output variant *---------------------------------------------------------------------* FORM init_variant USING utp_repid_this TYPE syrepid CHANGING cst_s_variant TYPE disvariant. CLEAR cst_s_variant. cst_s_variant-report = utp_repid_this. ENDFORM. "" init_variant *&--------------------------------------------------------------------* *& Form r0_set_pf_status *&--------------------------------------------------------------------* * If you need additional GUI functions, copy status STANDARD * from function group SALV and add your own functions to this status. * In this routine, you specify that you want to use your own GUI * status instead of the basic GUI status. *---------------------------------------------------------------------* * -->UTA_EXTAB text *---------------------------------------------------------------------* FORM r0_set_pf_status USING uta_extab TYPE slis_t_extab. ""#EC CALLED *---------------------------------------------------------------------* * Copy GUI status 'STANDARD' from functiongroup 'SALV'. * After copy, reactivate function '&RNT_PREV' and place this function * in the 1st position of the menu bar. *---------------------------------------------------------------------* SET PF-STATUS 'STANDARD'. ENDFORM. ""R0_SET_PF_STATUS *&--------------------------------------------------------------------* *& Form r1_process_user_command *&--------------------------------------------------------------------* * This routine deals with the ""non-standard"" GUI-functions. * It enables you to do the following: * - Double-click or click on a hotspotted field * - Implement your own GUI-functions * You'll find some predefined examples in this routine. *---------------------------------------------------------------------* FORM r1_process_user_command ""#EC CALLED USING utp_ucomm TYPE syucomm utp_selfield TYPE slis_selfield. DATA: lta_list_sec TYPE TABLE OF /ctac/s_alv_struc_sec. DATA: ltp_repid TYPE syrepid. * DATA: ltp_ebeln_num(10) TYPE n. * DATA: ltp_ebeln TYPE ebeln. * DATA: ltp_matnr TYPE matnr. * DATA: ltp_matnr_char(18) TYPE c. * *----------------------------------------------------------------------* * Handle the specific user-commands. * *----------------------------------------------------------------------* CASE utp_ucomm. *----------------------------------------------------------------------* * Handle double click or hotspot on a specific field. * * These are some examples * *----------------------------------------------------------------------* WHEN co_double_click. CASE utp_selfield-fieldname. * WHEN 'EBELN'. * * ltp_ebeln_num = utp_selfield-value. * ltp_ebeln = ltp_ebeln_num. * CALL FUNCTION 'MR_PO_DISPLAY' * EXPORTING * i_ebeln = ltp_ebeln. * * WHEN 'LIFNR'. * * SET PARAMETER ID 'LIF' FIELD utp_selfield-value. * CALL TRANSACTION 'MK03' AND SKIP FIRST SCREEN. * WHEN 'TABNAME'. * * REFRESH bdcdata. * PERFORM bdc_dynpro USING 'SAPMSRD0' '0102'. * PERFORM bdc_field USING 'BDC_OKCODE' '=SHOW'. * PERFORM bdc_field USING 'RSRD1-TBMA' abap_true. * PERFORM bdc_field USING 'RSRD1-TBMA_VAL' utp_selfield-value. * * CALL TRANSACTION 'SE11' USING bdcdata MODE 'E'. * WHEN OTHERS. ENDCASE. *---------------------------------------------------------------------* * Handle your own GUI functions here * * For example, handle a secondary ALV List * *---------------------------------------------------------------------* WHEN co_sec_list. PERFORM build_sec_list TABLES lta_list_sec. PERFORM display_sec_list TABLES lta_list_sec CHANGING utp_selfield. *---------------------------------------------------------------------* * Or some other GUI-functions * *---------------------------------------------------------------------* * WHEN 'OKCODE_01'. * Actions for this okcode WHEN OTHERS. ENDCASE. ENDFORM. ""R1_PROCESS_USER_COMMAND *---------------------------------------------------------------------* * FORM R2_SET_TOP_OF_PAGE * *---------------------------------------------------------------------* * Put the content of table TA_COMMENT on the top of the ALV * *---------------------------------------------------------------------* FORM r2_set_top_of_page. ""#EC CALLED CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE' EXPORTING it_list_commentary = ta_comment EXCEPTIONS OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDFORM. ""R2_SET_TOP_OF_PAGE *&--------------------------------------------------------------------* *& Form build_comment *&--------------------------------------------------------------------* * Create the internal table that is going to be the TOP-OF-PAGE * of the ALV grid or list. *---------------------------------------------------------------------* FORM build_comment CHANGING cta_top_of_page TYPE slis_t_listheader. DATA: lwa_line TYPE slis_listheader. REFRESH cta_top_of_page. *---------------------------------------------------------------------* * LIST HEADING LINE: TYPE H *---------------------------------------------------------------------* CLEAR lwa_line. lwa_line-typ = 'H'. *---------------------------------------------------------------------* * LLINE-KEY: NOT USED FOR THIS TYPE *---------------------------------------------------------------------* lwa_line-info = text-100. APPEND lwa_line TO cta_top_of_page. *---------------------------------------------------------------------* * STATUS LINE: TYPE S *---------------------------------------------------------------------* CLEAR lwa_line. lwa_line-typ = 'S'. lwa_line-key = text-101. lwa_line-info = text-102. APPEND lwa_line TO cta_top_of_page. lwa_line-key = text-103. lwa_line-info = text-104. APPEND lwa_line TO cta_top_of_page. *---------------------------------------------------------------------* * ACTION LINE: TYPE A *---------------------------------------------------------------------* CLEAR lwa_line. lwa_line-typ = 'A'. *---------------------------------------------------------------------* * LLINE-KEY: NOT USED FOR THIS TYPE *---------------------------------------------------------------------* lwa_line-info = text-105. APPEND lwa_line TO cta_top_of_page. ENDFORM. "" build_comment *&--------------------------------------------------------------------* *& Form build_fieldcatalog *&--------------------------------------------------------------------* * Build a field catalog from the DDIC structure specified. *---------------------------------------------------------------------* FORM build_fieldcatalog USING utp_struc TYPE tabname CHANGING cta_fcat TYPE slis_t_fieldcat_alv. *----------------------------------------------------------------------* * Build a field catalog for ALV, based on a DDIC structure. *----------------------------------------------------------------------* CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE' EXPORTING i_program_name = tp_repid_this i_structure_name = utp_struc i_bypassing_buffer = abap_true CHANGING ct_fieldcat = cta_fcat[] EXCEPTIONS inconsistent_interface = 1 program_error = 2 OTHERS = 3. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDFORM. "" build_fieldcatalog *&--------------------------------------------------------------------* *& Form change_layout_settings *&--------------------------------------------------------------------* * Set some layout attributes. *---------------------------------------------------------------------* FORM change_layout_settings CHANGING cst_layout TYPE slis_layout_alv. *----------------------------------------------------------------------* * Modify layout settings. *----------------------------------------------------------------------* cst_layout-zebra = abap_true. cst_layout-colwidth_optimize = abap_true. ENDFORM. "" change_layout_settings *&--------------------------------------------------------------------* *& Form modify_fieldcatalog *&--------------------------------------------------------------------* * Modify the field catalog for the primary list, if needed! * You can set attributes for every column in the ALV output by * selecting the fieldname belonging to the column. * For an overview of the attributes available, see the * online documentation of function module REUSE_ALV_GRID_DISPLAY. *---------------------------------------------------------------------* FORM modify_fieldcatalog CHANGING cta_fcat TYPE slis_t_fieldcat_alv. DATA: lwa_fcat TYPE slis_fieldcat_alv. *----------------------------------------------------------------------* * Modify the field catalog according to the requirements. * Some examples are shown below. *----------------------------------------------------------------------* LOOP AT cta_fcat INTO lwa_fcat. CASE lwa_fcat-fieldname. * WHEN 'EBELN'. * lwa_fcat-key = abap_true. * lwa_fcat-hotspot = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'BUKRS' OR 'EKORG' OR 'EKGRP' OR 'EBELP'. * lwa_fcat-key = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'LIFNR' or 'BELNR'. * lwa_fcat-hotspot = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'NETPR' OR 'DMBTR' OR 'MENGE'. * lwa_fcat-no_zero = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'ZGR_REQ' OR 'SHKZG'. * lwa_fcat-just = 'C'. * MODIFY cta_fcat FROM lwa_fcat. WHEN OTHERS. ENDCASE. ENDLOOP. ENDFORM. "" modify_fieldcatalog *&--------------------------------------------------------------------* *& Form modify_fieldcat_SEC *&--------------------------------------------------------------------* * Modify the field catalog for the secondary list, if needed! * As you could for the field catalog of the primary list, you * can set attributes for every column by selecting the corresponding * field name. Look at the examples. *---------------------------------------------------------------------* FORM modify_fieldcat_sec CHANGING cta_fcat TYPE slis_t_fieldcat_alv. DATA: lwa_fcat TYPE slis_fieldcat_alv. *----------------------------------------------------------------------* * Modify the field catalog according to the requirements. * Some examples are shown below. *----------------------------------------------------------------------* LOOP AT cta_fcat INTO lwa_fcat. CASE lwa_fcat-fieldname. * WHEN 'EBELN'. * lwa_fcat-key = abap_true. * lwa_fcat-hotspot = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'BUKRS' OR 'EKORG' OR 'EKGRP' OR 'EBELP'. * lwa_fcat-key = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'LIFNR' or 'BELNR'. * lwa_fcat-hotspot = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'NETPR' OR 'DMBTR' OR 'MENGE'. * lwa_fcat-no_zero = abap_true. * MODIFY cta_fcat FROM lwa_fcat. * WHEN 'ZGR_REQ' OR 'SHKZG'. * lwa_fcat-just = 'C'. * MODIFY cta_fcat FROM lwa_fcat. WHEN OTHERS. ENDCASE. ENDLOOP. ENDFORM. "" modify_fieldcat_sec *&--------------------------------------------------------------------* *& Form build_sec_list *&--------------------------------------------------------------------* * Build internal table for second ALV list *---------------------------------------------------------------------* FORM build_sec_list TABLES tta_list STRUCTURE /ctac/s_alv_struc_sec. ENDFORM. "" build_sec_list *&--------------------------------------------------------------------* *& Form display_sec_list *&--------------------------------------------------------------------* * This form builds a second ALV list with another field catalog * based on a second DDIC-structure (change this name!!!) * Fill in the right structure name for constant CO_STRUC_SEC! * . *---------------------------------------------------------------------* FORM display_sec_list TABLES tta_list STRUCTURE /ctac/s_alv_struc_sec CHANGING ctp_selfield TYPE slis_selfield. DATA: lta_fcat TYPE slis_t_fieldcat_alv. DATA: lta_sort_alv TYPE slis_t_sortinfo_alv. DATA: lst_s_variant TYPE disvariant, lst_layout TYPE slis_layout_alv, lst_exit_by_user TYPE slis_exit_by_user. DATA: lwa_fcat TYPE slis_fieldcat_alv. PERFORM build_fieldcatalog USING co_struc_sec CHANGING lta_fcat[]. PERFORM modify_fieldcat_sec CHANGING lta_fcat[]. PERFORM change_layout_settings CHANGING lst_layout. PERFORM init_variant USING tp_repid_this CHANGING lst_s_variant. CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING i_callback_program = tp_repid_this i_callback_pf_status_set = co_rout_pf_stat_sec i_callback_user_command = co_rout_ucomm_sec i_callback_top_of_page = co_rout_top_page_sec is_layout = lst_layout it_fieldcat = lta_fcat i_save = co_save is_variant = lst_s_variant it_sort = lta_sort_alv * is_print = wa_is_print IMPORTING es_exit_caused_by_user = lst_exit_by_user TABLES t_outtab = tta_list EXCEPTIONS program_error = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. *----------------------------------------------------------------------* * If field wa_exit_by_user is filled, the user has indicated that he/she wants * to quit. * In that case, enter value 'X' in field utp_selfield_exit in order to * cause the ALV function to stop and not return to the first ALV list shown. *----------------------------------------------------------------------* IF NOT lst_exit_by_user IS INITIAL. ctp_selfield-exit = abap_true. ENDIF. ENDFORM. "" display_sec_list *&--------------------------------------------------------------------* *& Form set_sort_criteria *&--------------------------------------------------------------------* * Determine the sort order and/or the subtotalling of the basic list. *---------------------------------------------------------------------* FORM set_sort_criteria CHANGING cta_sort_alv TYPE slis_t_sortinfo_alv. ENDFORM. "" set_sort_criteria_sec *&--------------------------------------------------------------------* *& Form process_output_variant *&--------------------------------------------------------------------* * Process the selected output variant *---------------------------------------------------------------------* FORM process_output_variant USING utp_varia TYPE slis_vari CHANGING cst_s_variant TYPE disvariant cst_s_var_usr TYPE disvariant. *----------------------------------------------------------------------* * If display-variant entered on the selection-screen, we need to check * whether this variant exists. *----------------------------------------------------------------------* IF NOT utp_varia IS INITIAL. MOVE: cst_s_variant TO cst_s_var_usr, sy-repid TO cst_s_var_usr-report, utp_varia TO cst_s_var_usr-variant. CALL FUNCTION 'REUSE_ALV_VARIANT_EXISTENCE' EXPORTING i_save = co_save CHANGING cs_variant = cst_s_var_usr EXCEPTIONS wrong_input = 1 not_found = 2 program_error = 3 OTHERS = 4. IF sy-subrc <> 0. CLEAR cst_s_variant. ELSE. cst_s_variant = cst_s_var_usr. ENDIF. ELSE. PERFORM init_variant USING sy-repid CHANGING cst_s_variant. ENDIF. ENDFORM. "" process_output_variant ",7754,False,1516.5552378753018,median "/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * ""Products""), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC ""AS IS"" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ package spine { import spine.animation.*; import spine.attachments.*; import flash.utils.ByteArray; public class SkeletonJson { public var attachmentLoader : AttachmentLoader; public var scale : Number = 1; private var linkedMeshes : Vector. = new Vector.(); public function SkeletonJson(attachmentLoader : AttachmentLoader = null) { this.attachmentLoader = attachmentLoader; } /** @param object A String or ByteArray. */ public function readSkeletonData(object : *, name : String = null) : SkeletonData { if (object == null) throw new ArgumentError(""object cannot be null.""); var root : Object; if (object is String) root = JSON.parse(String(object)); else if (object is ByteArray) root = JSON.parse(ByteArray(object).readUTFBytes(ByteArray(object).length)); else if (object is Object) root = object; else throw new ArgumentError(""object must be a String, ByteArray or Object.""); var skeletonData : SkeletonData = new SkeletonData(); skeletonData.name = name; // Skeleton. var skeletonMap : Object = root[""skeleton""]; if (skeletonMap) { skeletonData.hash = skeletonMap[""hash""]; skeletonData.version = skeletonMap[""spine""]; skeletonData.x = skeletonMap[""x""] || 0; skeletonData.y = skeletonMap[""y""] || 0; skeletonData.width = skeletonMap[""width""] || 0; skeletonData.height = skeletonMap[""height""] || 0; skeletonData.fps = skeletonMap[""fps""] || 0; skeletonData.imagesPath = skeletonMap[""images""]; } // Bones. var boneData : BoneData; for each (var boneMap : Object in root[""bones""]) { var parent : BoneData = null; var parentName : String = boneMap[""parent""]; if (parentName) { parent = skeletonData.findBone(parentName); if (!parent) throw new Error(""Parent bone not found: "" + parentName); } boneData = new BoneData(skeletonData.bones.length, boneMap[""name""], parent); boneData.length = Number(boneMap[""length""] || 0) * scale; boneData.x = Number(boneMap[""x""] || 0) * scale; boneData.y = Number(boneMap[""y""] || 0) * scale; boneData.rotation = (boneMap[""rotation""] || 0); boneData.scaleX = getNumber(boneMap, ""scaleX"", 1); boneData.scaleY = getNumber(boneMap, ""scaleY"", 1); boneData.shearX = Number(boneMap[""shearX""] || 0); boneData.shearY = Number(boneMap[""shearY""] || 0); boneData.transformMode = TransformMode[boneMap[""transform""] || ""normal""]; boneData.skinRequired = getValue(boneMap, ""skin"", false); color = boneMap[""color""]; if (color) boneData.color.setFromString(color); skeletonData.bones.push(boneData); } // Slots. for each (var slotMap : Object in root[""slots""]) { var slotName : String = slotMap[""name""]; var boneName : String = slotMap[""bone""]; boneData = skeletonData.findBone(boneName); if (!boneData) throw new Error(""Slot bone not found: "" + boneName); var slotData : SlotData = new SlotData(skeletonData.slots.length, slotName, boneData); var color : String = slotMap[""color""]; if (color) slotData.color.setFromString(color); var dark : String = slotMap[""dark""]; if (dark) slotData.darkColor = Color.fromString(dark); slotData.attachmentName = slotMap[""attachment""]; slotData.blendMode = BlendMode[slotMap[""blend""] || ""normal""]; skeletonData.slots.push(slotData); } // IK constraints. for each (var constraintMap : Object in root[""ik""]) { var ikData : IkConstraintData = new IkConstraintData(constraintMap[""name""]); ikData.order = constraintMap[""order""] || 0; ikData.skinRequired = getValue(constraintMap, ""skin"", false); for each (boneName in constraintMap[""bones""]) { var bone : BoneData = skeletonData.findBone(boneName); if (!bone) throw new Error(""IK constraint bone not found: "" + boneName); ikData.bones.push(bone); } ikData.target = skeletonData.findBone(constraintMap[""target""]); if (!ikData.target) throw new Error(""Target bone not found: "" + constraintMap[""target""]); ikData.bendDirection = (!constraintMap.hasOwnProperty(""bendPositive"") || constraintMap[""bendPositive""]) ? 1 : -1; ikData.compress = getValue(constraintMap, ""compress"", false); ikData.stretch = getValue(constraintMap, ""stretch"", false); ikData.uniform = getValue(constraintMap, ""uniform"", false); ikData.softness = getNumber(constraintMap, ""softness"", 0) * scale; ikData.mix = getNumber(constraintMap, ""mix"", 1); skeletonData.ikConstraints.push(ikData); } // Transform constraints. for each (constraintMap in root[""transform""]) { var transformData : TransformConstraintData = new TransformConstraintData(constraintMap[""name""]); transformData.order = constraintMap[""order""] || 0; transformData.skinRequired = getValue(constraintMap, ""skin"", false); for each (boneName in constraintMap[""bones""]) { bone = skeletonData.findBone(boneName); if (!bone) throw new Error(""Transform constraint bone not found: "" + boneName); transformData.bones.push(bone); } transformData.target = skeletonData.findBone(constraintMap[""target""]); if (!transformData.target) throw new Error(""Target bone not found: "" + constraintMap[""target""]); transformData.local = getValue(constraintMap, ""local"", false); transformData.relative = getValue(constraintMap, ""relative"", false); transformData.offsetRotation = Number(constraintMap[""rotation""] || 0); transformData.offsetX = Number(constraintMap[""x""] || 0) * scale; transformData.offsetY = Number(constraintMap[""y""] || 0) * scale; transformData.offsetScaleX = Number(constraintMap[""scaleX""] || 0); transformData.offsetScaleY = Number(constraintMap[""scaleY""] || 0); transformData.offsetShearY = Number(constraintMap[""shearY""] || 0); transformData.mixRotate = getNumber(constraintMap, ""mixRotate"", 1); transformData.mixX = getNumber(constraintMap, ""mixX"", 1); transformData.mixY = getNumber(constraintMap, ""mixY"", transformData.mixX); transformData.mixScaleX = getNumber(constraintMap, ""mixScaleX"", 1); transformData.mixScaleY = getNumber(constraintMap, ""mixScaleY"", transformData.mixScaleX); transformData.mixShearY = getNumber(constraintMap, ""mixShearY"", 1); skeletonData.transformConstraints.push(transformData); } // Path constraints. for each (constraintMap in root[""path""]) { var pathData : PathConstraintData = new PathConstraintData(constraintMap[""name""]); pathData.order = constraintMap[""order""] || 0; pathData.skinRequired = getValue(constraintMap, ""skin"", false); for each (boneName in constraintMap[""bones""]) { bone = skeletonData.findBone(boneName); if (!bone) throw new Error(""Path constraint bone not found: "" + boneName); pathData.bones.push(bone); } pathData.target = skeletonData.findSlot(constraintMap[""target""]); if (!pathData.target) throw new Error(""Path target slot not found: "" + constraintMap[""target""]); pathData.positionMode = PositionMode[constraintMap[""positionMode""] || ""percent""]; pathData.spacingMode = SpacingMode[constraintMap[""spacingMode""] || ""length""]; pathData.rotateMode = RotateMode[constraintMap[""rotateMode""] || ""tangent""]; pathData.offsetRotation = Number(constraintMap[""rotation""] || 0); pathData.position = Number(constraintMap[""position""] || 0); if (pathData.positionMode == PositionMode.fixed) pathData.position *= scale; pathData.spacing = Number(constraintMap[""spacing""] || 0); if (pathData.spacingMode == SpacingMode.length || pathData.spacingMode == SpacingMode.fixed) pathData.spacing *= scale; pathData.mixRotate = getNumber(constraintMap, ""mixRotate"", 1); pathData.mixX = getNumber(constraintMap, ""mixX"", 1); pathData.mixY = getNumber(constraintMap, ""mixY"", pathData.mixX); skeletonData.pathConstraints.push(pathData); } // Skins. var skins : Object = root[""skins""]; for (var i : int = 0; i < skins.length; i++) { var ii : int; var skinMap : Object = skins[i]; var skin : Skin = new Skin(skinMap[""name""]); if (skinMap[""bones""]) { for (ii = 0; ii < skinMap[""bones""].length; ii++) { boneData = skeletonData.findBone(skinMap[""bones""][ii]); if (boneData == null) throw new Error(""Skin bone not found: "" + skinMap[""bones""][ii]); skin.bones.push(boneData); } } var constraint : ConstraintData; if (skinMap[""ik""]) { for (ii = 0; ii < skinMap[""ik""].length; ii++) { constraint = skeletonData.findIkConstraint(skinMap[""ik""][ii]); if (constraint == null) throw new Error(""Skin IK constraint not found: "" + skinMap[""ik""][ii]); skin.constraints.push(constraint); } } if (skinMap[""transform""]) { for (ii = 0; ii < skinMap[""transform""].length; ii++) { constraint = skeletonData.findTransformConstraint(skinMap[""transform""][ii]); if (constraint == null) throw new Error(""Skin transform constraint not found: "" + skinMap[""transform""][ii]); skin.constraints.push(constraint); } } if (skinMap[""path""]) { for (ii = 0; ii < skinMap[""path""].length; ii++) { constraint = skeletonData.findPathConstraint(skinMap[""path""][ii]); if (constraint == null) throw new Error(""Skin path constraint not found: "" + skinMap[""path""][ii]); skin.constraints.push(constraint); } } for (slotName in skinMap.attachments) { var slot : SlotData = skeletonData.findSlot(slotName); var slotEntry : Object = skinMap.attachments[slotName]; for (var attachmentName : String in slotEntry) { var attachment : Attachment = readAttachment(slotEntry[attachmentName], skin, slot.index, attachmentName, skeletonData); if (attachment != null) skin.setAttachment(slot.index, attachmentName, attachment); } } skeletonData.skins.push(skin); if (skin.name == ""default"") skeletonData.defaultSkin = skin; } // Linked meshes. var linkedMeshes : Vector. = this.linkedMeshes; for each (var linkedMesh : LinkedMesh in linkedMeshes) { var parentSkin : Skin = !linkedMesh.skin ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin); if (!parentSkin) throw new Error(""Skin not found: "" + linkedMesh.skin); var parentMesh : Attachment = parentSkin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent); if (!parentMesh) throw new Error(""Parent mesh not found: "" + linkedMesh.parent); linkedMesh.mesh.deformAttachment = linkedMesh.inheritDeform ? VertexAttachment(parentMesh) : linkedMesh.mesh; linkedMesh.mesh.parentMesh = MeshAttachment(parentMesh); linkedMesh.mesh.updateUVs(); } linkedMeshes.length = 0; // Events. var events : Object = root[""events""]; if (events) { for (var eventName : String in events) { var eventMap : Object = events[eventName]; var eventData : EventData = new EventData(eventName); eventData.intValue = eventMap[""int""] || 0; eventData.floatValue = eventMap[""float""] || 0; eventData.stringValue = eventMap[""string""] || """"; eventData.audioPath = eventMap[""audio""] || null; if (eventData.audioPath != null) { eventData.volume = eventMap[""volume""] || 1; eventData.balance = eventMap[""balance""] || 0; } skeletonData.events.push(eventData); } } // Animations. var animations : Object = root[""animations""]; for (var animationName : String in animations) readAnimation(animations[animationName], animationName, skeletonData); return skeletonData; } private function readAttachment(map : Object, skin : Skin, slotIndex : int, name : String, skeletonData: SkeletonData) : Attachment { name = map[""name""] || name; var scale : Number = this.scale; var color : String; switch (AttachmentType[getValue(map, ""type"", ""region"")]) { case AttachmentType.region: var region : RegionAttachment = attachmentLoader.newRegionAttachment(skin, name, map[""path""] || name); if (!region) return null; region.path = map[""path""] || name; region.x = Number(map[""x""] || 0) * scale; region.y = Number(map[""y""] || 0) * scale; region.scaleX = getNumber(map, ""scaleX"", 1); region.scaleY = getNumber(map, ""scaleY"", 1); region.rotation = map[""rotation""] || 0; region.width = Number(map[""width""] || 0) * scale; region.height = Number(map[""height""] || 0) * scale; color = map[""color""]; if (color) region.color.setFromString(color); region.updateOffset(); return region; case AttachmentType.mesh: case AttachmentType.linkedmesh: var mesh : MeshAttachment = attachmentLoader.newMeshAttachment(skin, name, map[""path""] || name); if (!mesh) return null; mesh.path = map[""path""] || name; color = map[""color""]; if (color) mesh.color.setFromString(color); mesh.width = Number(map[""width""] || 0) * scale; mesh.height = Number(map[""height""] || 0) * scale; if (map[""parent""]) { var inheritDeform : Boolean = getValue(map, ""deform"", true); linkedMeshes.push(new LinkedMesh(mesh, map[""skin""], slotIndex, map[""parent""], inheritDeform)); return mesh; } var uvs : Vector. = getFloatArray(map, ""uvs"", 1); readVertices(map, mesh, uvs.length); mesh.triangles = getUintArray(map, ""triangles""); mesh.regionUVs = uvs; mesh.updateUVs(); mesh.hullLength = int(map[""hull""] || 0) * 2; if (map[""edges""]) mesh.edges = getIntArray(map, ""edges""); return mesh; case AttachmentType.boundingbox: var box : BoundingBoxAttachment = attachmentLoader.newBoundingBoxAttachment(skin, name); if (!box) return null; readVertices(map, box, int(map[""vertexCount""]) << 1); return box; case AttachmentType.path: var path : PathAttachment = attachmentLoader.newPathAttachment(skin, name); if (!path) return null; path.closed = getValue(map, ""closed"", false); path.constantSpeed = getValue(map, ""constantSpeed"", true); var vertexCount : int = int(map[""vertexCount""]); readVertices(map, path, vertexCount << 1); var lengths : Vector. = new Vector.(); for each (var curves : Object in map[""lengths""]) { lengths.push(Number(curves) * scale); } path.lengths = lengths; return path; case AttachmentType.point: var point : PointAttachment = attachmentLoader.newPointAttachment(skin, name); if (!point) return null; point.x = getNumber(map, ""x"", 0) * scale; point.y = getNumber(map, ""y"", 0) * scale; point.rotation = getNumber(map, ""rotation"", 0); color = map[""color""]; if (color) point.color.setFromString(color); return point; case AttachmentType.clipping: var clip : ClippingAttachment = attachmentLoader.newClippingAttachment(skin, name); if (!clip) return null; var end : String = map[""end""]; if (end != null) { var slot : SlotData = skeletonData.findSlot(end); if (slot == null) throw new Error(""Clipping end slot not found: "" + end); clip.endSlot = slot; } vertexCount = int(map[""vertexCount""]); readVertices(map, clip, vertexCount << 1); color = map[""color""]; if (color) clip.color.setFromString(color); return clip; } return null; } private function readVertices(map : Object, attachment : VertexAttachment, verticesLength : int) : void { attachment.worldVerticesLength = verticesLength; var vertices : Vector. = getFloatArray(map, ""vertices"", 1); if (verticesLength == vertices.length) { if (scale != 1) { for (var i : int = 0, n : int = vertices.length; i < n; i++) { vertices[i] *= scale; } } attachment.vertices = vertices; return; } var weights : Vector. = new Vector.(verticesLength * 3 * 3); weights.length = 0; var bones : Vector. = new Vector.(verticesLength * 3); bones.length = 0; for (i = 0, n = vertices.length; i < n;) { var boneCount : int = int(vertices[i++]); bones.push(boneCount); for (var nn : int = i + boneCount * 4; i < nn; i += 4) { bones.push(int(vertices[i])); weights.push(vertices[i + 1] * scale); weights.push(vertices[i + 2] * scale); weights.push(vertices[i + 3]); } } attachment.bones = bones; attachment.vertices = weights; } private function readAnimation(map : Object, name : String, skeletonData : SkeletonData) : void { var scale : Number = this.scale; var timelines : Vector. = new Vector.(); var slotMap : Object, slotIndex : int, slotName : String; var timelineMap : Array, keyMap : Object, nextMap : Object; var frame : int, bezier : int; var time : Number, time2 : Number; var curve : Object; var timelineName : String; var i : int, n : int; // Slot timelines. var slots : Object = map[""slots""]; for (slotName in slots) { slotMap = slots[slotName]; slotIndex = skeletonData.findSlotIndex(slotName); for (timelineName in slotMap) { timelineMap = slotMap[timelineName]; if (!timelineMap) continue; if (timelineName == ""attachment"") { var attachmentTimeline : AttachmentTimeline = new AttachmentTimeline(timelineMap.length, slotIndex); for (frame = 0; frame < timelineMap.length; frame++) { keyMap = timelineMap[frame]; attachmentTimeline.setFrame(frame, getNumber(keyMap, ""time"", 0), keyMap.name); } timelines.push(attachmentTimeline); } else if (timelineName == ""rgba"") { var rgbaTimeline : RGBATimeline = new RGBATimeline(timelineMap.length, timelineMap.length << 2, slotIndex); keyMap = timelineMap[0]; time = getNumber(keyMap, ""time"", 0); var rgba : Color = Color.fromString(keyMap.color); for (frame = 0, bezier = 0;; frame++) { rgbaTimeline.setFrame(frame, time, rgba.r, rgba.g, rgba.b, rgba.a); nextMap = timelineMap[frame + 1]; if (!nextMap) { rgbaTimeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); var newRgba : Color = Color.fromString(nextMap.color); curve = keyMap.curve; if (curve) { bezier = readCurve(curve, rgbaTimeline, bezier, frame, 0, time, time2, rgba.r, newRgba.r, 1); bezier = readCurve(curve, rgbaTimeline, bezier, frame, 1, time, time2, rgba.g, newRgba.g, 1); bezier = readCurve(curve, rgbaTimeline, bezier, frame, 2, time, time2, rgba.b, newRgba.b, 1); bezier = readCurve(curve, rgbaTimeline, bezier, frame, 3, time, time2, rgba.a, newRgba.a, 1); } time = time2; rgba = newRgba; keyMap = nextMap; } timelines.push(rgbaTimeline); } else if (timelineName == ""rgb"") { var rgbTimeline : RGBTimeline = new RGBTimeline(timelineMap.length, timelineMap.length * 3, slotIndex); keyMap = timelineMap[0]; time = getNumber(keyMap, ""time"", 0); var rgb : Color = Color.fromString(keyMap.color); for (frame = 0, bezier = 0;; frame++) { rgbTimeline.setFrame(frame, time, rgb.r, rgb.g, rgb.b); nextMap = timelineMap[frame + 1]; if (!nextMap) { rgbTimeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); var newRgb : Color = Color.fromString(nextMap.color); curve = keyMap.curve; if (curve) { bezier = readCurve(curve, rgbTimeline, bezier, frame, 0, time, time2, rgb.r, newRgb.r, 1); bezier = readCurve(curve, rgbTimeline, bezier, frame, 1, time, time2, rgb.g, newRgb.g, 1); bezier = readCurve(curve, rgbTimeline, bezier, frame, 2, time, time2, rgb.b, newRgb.b, 1); } time = time2; rgb = newRgb; keyMap = nextMap; } timelines.push(rgbTimeline); } else if (timelineName == ""alpha"") { timelines.push(readTimeline(timelineMap, new AlphaTimeline(timelineMap.length, timelineMap.length, slotIndex), 0, 1)); } else if (timelineName == ""rgba2"") { var rgba2Timeline : RGBA2Timeline = new RGBA2Timeline(timelineMap.length, timelineMap.length * 7, slotIndex); keyMap = timelineMap[0]; time = getNumber(keyMap, ""time"", 0); var lighta : Color = Color.fromString(keyMap.light); var darka : Color = Color.fromString(keyMap.dark); for (frame = 0, bezier = 0;; frame++) { rgba2Timeline.setFrame(frame, time, lighta.r, lighta.g, lighta.b, lighta.a, darka.r, darka.g, darka.b); nextMap = timelineMap[frame + 1]; if (!nextMap) { rgba2Timeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); var newLighta : Color = Color.fromString(nextMap.light); var newDarka : Color = Color.fromString(nextMap.dark); curve = keyMap.curve; if (curve) { bezier = readCurve(curve, rgba2Timeline, bezier, frame, 0, time, time2, lighta.r, newLighta.r, 1); bezier = readCurve(curve, rgba2Timeline, bezier, frame, 1, time, time2, lighta.g, newLighta.g, 1); bezier = readCurve(curve, rgba2Timeline, bezier, frame, 2, time, time2, lighta.b, newLighta.b, 1); bezier = readCurve(curve, rgba2Timeline, bezier, frame, 3, time, time2, lighta.a, newLighta.a, 1); bezier = readCurve(curve, rgba2Timeline, bezier, frame, 4, time, time2, darka.r, newDarka.r, 1); bezier = readCurve(curve, rgba2Timeline, bezier, frame, 5, time, time2, darka.g, newDarka.g, 1); bezier = readCurve(curve, rgba2Timeline, bezier, frame, 6, time, time2, darka.b, newDarka.b, 1); } time = time2; lighta = newLighta; darka = newDarka; keyMap = nextMap; } timelines.push(rgba2Timeline); } else if (timelineName == ""rgb2"") { var rgb2Timeline : RGB2Timeline = new RGB2Timeline(timelineMap.length, timelineMap.length * 6, slotIndex); keyMap = timelineMap[0]; time = getNumber(keyMap, ""time"", 0); var light : Color = Color.fromString(keyMap.light); var dark : Color = Color.fromString(keyMap.dark); for (frame = 0, bezier = 0;; frame++) { rgb2Timeline.setFrame(frame, time, light.r, light.g, light.b, dark.r, dark.g, dark.b); nextMap = timelineMap[frame + 1]; if (!nextMap) { rgb2Timeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); var newLight : Color = Color.fromString(nextMap.light); var newDark : Color = Color.fromString(nextMap.dark); curve = keyMap.curve; if (curve) { bezier = readCurve(curve, rgb2Timeline, bezier, frame, 0, time, time2, light.r, newLight.r, 1); bezier = readCurve(curve, rgb2Timeline, bezier, frame, 1, time, time2, light.g, newLight.g, 1); bezier = readCurve(curve, rgb2Timeline, bezier, frame, 2, time, time2, light.b, newLight.b, 1); bezier = readCurve(curve, rgb2Timeline, bezier, frame, 3, time, time2, dark.r, newDark.r, 1); bezier = readCurve(curve, rgb2Timeline, bezier, frame, 4, time, time2, dark.g, newDark.g, 1); bezier = readCurve(curve, rgb2Timeline, bezier, frame, 5, time, time2, dark.b, newDark.b, 1); } time = time2; light = newLight; dark = newDark; keyMap = nextMap; } timelines.push(rgb2Timeline); } else throw new Error(""Invalid timeline type for a slot: "" + timelineName + "" ("" + slotName + "")""); } } // Bone timelines. var bones : Object = map[""bones""]; for (var boneName : String in bones) { var boneIndex : int = skeletonData.findBoneIndex(boneName); if (boneIndex == -1) throw new Error(""Bone not found: "" + boneName); var boneMap : Object = bones[boneName]; for (timelineName in boneMap) { timelineMap = boneMap[timelineName]; if (timelineMap.length == 0) continue; if (timelineName === ""rotate"") { timelines.push(readTimeline(timelineMap, new RotateTimeline(timelineMap.length, timelineMap.length, boneIndex), 0, 1)); } else if (timelineName === ""translate"") { var translateTimeline : TranslateTimeline = new TranslateTimeline(timelineMap.length, timelineMap.length << 1, boneIndex); timelines.push(readTimeline2(timelineMap, translateTimeline, ""x"", ""y"", 0, scale)); } else if (timelineName === ""translatex"") { var translateXTimeline : TranslateXTimeline = new TranslateXTimeline(timelineMap.length, timelineMap.length, boneIndex); timelines.push(readTimeline(timelineMap, translateXTimeline, 0, scale)); } else if (timelineName === ""translatey"") { var translateYTimeline : TranslateYTimeline = new TranslateYTimeline(timelineMap.length, timelineMap.length, boneIndex); timelines.push(readTimeline(timelineMap, translateYTimeline, 0, scale)); } else if (timelineName === ""scale"") { var scaleTimeline : ScaleTimeline = new ScaleTimeline(timelineMap.length, timelineMap.length << 1, boneIndex); timelines.push(readTimeline2(timelineMap, scaleTimeline, ""x"", ""y"", 1, 1)); } else if (timelineName === ""scalex"") { var scaleXTimeline : ScaleXTimeline = new ScaleXTimeline(timelineMap.length, timelineMap.length, boneIndex); timelines.push(readTimeline(timelineMap, scaleXTimeline, 1, 1)); } else if (timelineName === ""scaley"") { var scaleYTimeline : ScaleYTimeline = new ScaleYTimeline(timelineMap.length, timelineMap.length, boneIndex); timelines.push(readTimeline(timelineMap, scaleYTimeline, 1, 1)); } else if (timelineName === ""shear"") { var shearTimeline : ShearTimeline = new ShearTimeline(timelineMap.length, timelineMap.length << 1, boneIndex); timelines.push(readTimeline2(timelineMap, shearTimeline, ""x"", ""y"", 0, 1)); } else if (timelineName === ""shearx"") { var shearXTimeline : ShearXTimeline = new ShearXTimeline(timelineMap.length, timelineMap.length, boneIndex); timelines.push(readTimeline(timelineMap, shearXTimeline, 0, 1)); } else if (timelineName === ""sheary"") { var shearYTimeline : ShearYTimeline = new ShearYTimeline(timelineMap.length, timelineMap.length, boneIndex); timelines.push(readTimeline(timelineMap, shearYTimeline, 0, 1)); } else throw new Error(""Invalid timeline type for a bone: "" + timelineName + "" ("" + boneName + "")""); } } // IK constraint timelines. var ikMap : Object = map[""ik""]; for (var ikConstraintName : String in ikMap) { timelineMap = map.ik[ikConstraintName]; keyMap = timelineMap[0]; if (!keyMap) continue; var ikIndex : int = skeletonData.ikConstraints.indexOf(skeletonData.findIkConstraint(ikConstraintName)); var ikTimeline : IkConstraintTimeline = new IkConstraintTimeline(timelineMap.length, timelineMap.length << 1, ikIndex); time = getNumber(keyMap, ""time"", 0); var mix : Number = getNumber(keyMap, ""mix"", 1); var softness : Number = getNumber(keyMap, ""softness"", 0) * scale; for (frame = 0, bezier = 0;; frame++) { ikTimeline.setFrame(frame, time, mix, softness, getValue(keyMap, ""bendPositive"", true) ? 1 : -1, getValue(keyMap, ""compress"", false), getValue(keyMap, ""stretch"", false)); nextMap = timelineMap[frame + 1]; if (!nextMap) { ikTimeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); var mix2 : Number = getNumber(nextMap, ""mix"", 1); var softness2 : Number = getNumber(nextMap, ""softness"", 0) * scale; curve = keyMap.curve; if (curve) { bezier = readCurve(curve, ikTimeline, bezier, frame, 0, time, time2, mix, mix2, 1); bezier = readCurve(curve, ikTimeline, bezier, frame, 1, time, time2, softness, softness2, scale); } time = time2; mix = mix2; softness = softness2; keyMap = nextMap; } timelines.push(ikTimeline); } // Transform constraint timelines. var mixRotate : Number, mixRotate2 : Number; var mixX : Number, mixX2 : Number; var mixY : Number, mixY2 : Number; var transformMap : Object = map[""transform""]; for (var transformName : String in transformMap) { timelineMap = map.transform[transformName]; keyMap = timelineMap[0]; if (!keyMap) continue; var transformIndex : int = skeletonData.transformConstraints.indexOf(skeletonData.findTransformConstraint(transformName)); var transformTimeline : TransformConstraintTimeline = new TransformConstraintTimeline(timelineMap.length, timelineMap.length << 2, transformIndex); time = getNumber(keyMap, ""time"", 0); mixRotate = getNumber(keyMap, ""mixRotate"", 1); var mixShearY : Number = getNumber(keyMap, ""mixShearY"", 1); mixX = getNumber(keyMap, ""mixX"", 1); mixY = getNumber(keyMap, ""mixY"", mixX); var mixScaleX : Number = getNumber(keyMap, ""mixScaleX"", 1); var mixScaleY : Number = getNumber(keyMap, ""mixScaleY"", mixScaleX); for (frame = 0, bezier = 0;; frame++) { transformTimeline.setFrame(frame, time, mixRotate, mixX, mixY, mixScaleX, mixScaleY, mixShearY); nextMap = timelineMap[frame + 1]; if (!nextMap) { transformTimeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); mixRotate2 = getNumber(nextMap, ""mixRotate"", 1); var mixShearY2 : Number = getNumber(nextMap, ""mixShearY"", 1); mixX2 = getNumber(nextMap, ""mixX"", 1); mixY2 = getNumber(nextMap, ""mixY"", mixX2); var mixScaleX2 : Number = getNumber(nextMap, ""mixScaleX"", 1); var mixScaleY2 : Number = getNumber(nextMap, ""mixScaleY"", mixScaleX2); curve = keyMap.curve; if (curve) { bezier = readCurve(curve, transformTimeline, bezier, frame, 0, time, time2, mixRotate, mixRotate2, 1); bezier = readCurve(curve, transformTimeline, bezier, frame, 1, time, time2, mixX, mixX2, 1); bezier = readCurve(curve, transformTimeline, bezier, frame, 2, time, time2, mixY, mixY2, 1); bezier = readCurve(curve, transformTimeline, bezier, frame, 3, time, time2, mixScaleX, mixScaleX2, 1); bezier = readCurve(curve, transformTimeline, bezier, frame, 4, time, time2, mixScaleY, mixScaleY2, 1); bezier = readCurve(curve, transformTimeline, bezier, frame, 5, time, time2, mixShearY, mixShearY2, 1); } time = time2; mixRotate = mixRotate2; mixX = mixX2; mixY = mixY2; mixScaleX = mixScaleX2; mixScaleY = mixScaleY2; mixScaleX = mixScaleX2; keyMap = nextMap; } timelines.push(transformTimeline); } // Path constraint timelines. var paths : Object = map[""path""]; for (var pathName : String in paths) { var index : int = skeletonData.findPathConstraintIndex(pathName); if (index == -1) throw new Error(""Path constraint not found: "" + pathName); var pathData : PathConstraintData = skeletonData.pathConstraints[index]; var pathMap : Object = paths[pathName]; for (timelineName in pathMap) { timelineMap = pathMap[timelineName]; keyMap = timelineMap[0]; if (!keyMap) continue; if (timelineName === ""position"") { var positionTimeline : PathConstraintPositionTimeline = new PathConstraintPositionTimeline(timelineMap.length, timelineMap.length, index); timelines.push(readTimeline(timelineMap, positionTimeline, 0, pathData.positionMode == PositionMode.fixed ? scale : 1)); } else if (timelineName === ""spacing"") { var spacingTimeline : PathConstraintSpacingTimeline = new PathConstraintSpacingTimeline(timelineMap.length, timelineMap.length, index); timelines.push(readTimeline(timelineMap, spacingTimeline, 0, pathData.spacingMode == SpacingMode.length || pathData.spacingMode == SpacingMode.fixed ? scale : 1)); } else if (timelineName === ""mix"") { var mixTimeline : PathConstraintMixTimeline = new PathConstraintMixTimeline(timelineMap.size, timelineMap.size * 3, index); time = getNumber(keyMap, ""time"", 0); mixRotate = getNumber(keyMap, ""mixRotate"", 1); mixX = getNumber(keyMap, ""mixX"", 1); mixY = getNumber(keyMap, ""mixY"", mixX); for (frame = 0, bezier = 0;; frame++) { mixTimeline.setFrame(frame, time, mixRotate, mixX, mixY); nextMap = timelineMap[frame + 1]; if (!nextMap) { mixTimeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); mixRotate2 = getNumber(nextMap, ""mixRotate"", 1); mixX2 = getNumber(nextMap, ""mixX"", 1); mixY2 = getNumber(nextMap, ""mixY"", mixX2); curve = keyMap.curve; if (curve != null) { bezier = readCurve(curve, mixTimeline, bezier, frame, 0, time, time2, mixRotate, mixRotate2, 1); bezier = readCurve(curve, mixTimeline, bezier, frame, 1, time, time2, mixX, mixX2, 1); bezier = readCurve(curve, mixTimeline, bezier, frame, 2, time, time2, mixY, mixY2, 1); } time = time2; mixRotate = mixRotate2; mixX = mixX2; mixY = mixY2; keyMap = nextMap; } timelines.push(mixTimeline); } } } // Deform timelines. var deforms : Object = map[""deform""]; for (var deformName : String in deforms) { var deformMap : Object = deforms[deformName]; var skin : Skin = skeletonData.findSkin(deformName); if (skin == null) throw new Error(""Skin not found: "" + deformName); for (slotName in deformMap) { slotMap = deformMap[slotName]; slotIndex = skeletonData.findSlotIndex(slotName); if (slotIndex == -1) throw new Error(""Slot not found: "" + slotMap.name); for (timelineName in slotMap) { timelineMap = slotMap[timelineName]; keyMap = timelineMap[0]; if (!keyMap) continue; var attachment : VertexAttachment = skin.getAttachment(slotIndex, timelineName) as VertexAttachment; if (attachment == null) throw new Error(""Deform attachment not found: "" + timelineName); var weighted : Boolean = attachment.bones != null; var vertices : Vector. = attachment.vertices; var deformLength : int = weighted ? vertices.length / 3 * 2 : vertices.length; var deformTimeline : DeformTimeline = new DeformTimeline(timelineMap.length, timelineMap.length, slotIndex, attachment); time = getNumber(keyMap, ""time"", 0); for (frame = 0, bezier = 0;; frame++) { var deform : Vector.; var verticesValue : Object = keyMap[""vertices""]; if (verticesValue == null) deform = weighted ? new Vector.(deformLength, true) : vertices; else { deform = new Vector.(deformLength, true); var start : int = Number(keyMap[""offset""] || 0); var temp : Vector. = getFloatArray(keyMap, ""vertices"", 1); for (i = 0; i < temp.length; i++) deform[start + i] = temp[i]; if (scale != 1) { for (i = start, n = i + temp.length; i < n; i++) deform[i] *= scale; } if (!weighted) { for (i = 0; i < deformLength; i++) deform[i] += vertices[i]; } } deformTimeline.setFrame(frame, time, deform); nextMap = timelineMap[frame + 1]; if (!nextMap) { deformTimeline.shrink(bezier); break; } time2 = getNumber(nextMap, ""time"", 0); curve = keyMap.curve; if (curve) bezier = readCurve(curve, deformTimeline, bezier, frame, 0, time, time2, 0, 1, 1); time = time2; keyMap = nextMap; } timelines.push(deformTimeline); } } } // Draw order timelines. var drawOrders : Array = map[""drawOrder""]; if (drawOrders) { var drawOrderTimeline : DrawOrderTimeline = new DrawOrderTimeline(drawOrders.length); var slotCount : int = skeletonData.slots.length; frame = 0; for each (var drawOrderMap : Object in drawOrders) { var drawOrder : Vector. = null; var offsets : Array = drawOrderMap[""offsets""]; if (offsets) { drawOrder = new Vector.(slotCount, true); for (i = slotCount - 1; i >= 0; i--) drawOrder[i] = -1; var unchanged : Vector. = new Vector.(slotCount - offsets.length, true); var originalIndex : int = 0, unchangedIndex : int = 0; for each (var offsetMap : Object in offsets) { slotIndex = skeletonData.findSlotIndex(offsetMap[""slot""]); if (slotIndex == -1) throw new Error(""Slot not found: "" + offsetMap[""slot""]); // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; // Set changed items. drawOrder[originalIndex + offsetMap[""offset""]] = originalIndex++; } // Collect remaining unchanged items. while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++; // Fill in unchanged items. for (i = slotCount - 1; i >= 0; i--) if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex]; } drawOrderTimeline.setFrame(frame++, Number(drawOrderMap[""time""] || 0), drawOrder); } timelines.push(drawOrderTimeline); } // Event timelines. var eventsMap : Array = map[""events""]; if (eventsMap) { var eventTimeline : EventTimeline = new EventTimeline(eventsMap.length); frame = 0; for each (var eventMap : Object in eventsMap) { var eventData : EventData = skeletonData.findEvent(eventMap[""name""]); if (!eventData) throw new Error(""Event not found: "" + eventMap[""name""]); var event : Event = new Event(Number(eventMap[""time""] || 0), eventData); event.intValue = getNumber(eventMap, ""int"", eventData.intValue); event.floatValue = getNumber(eventMap, ""float"", eventData.floatValue); event.stringValue = String(getValue(eventMap, ""string"", eventData.stringValue)); if (eventData.audioPath != null) { event.volume = getNumber(eventMap, ""volume"", 1); event.balance = getNumber(eventMap, ""balance"", 0); } eventTimeline.setFrame(frame++, event); } timelines.push(eventTimeline); } var duration : Number = 0; for (i = 0, n = timelines.length; i < n; i++) duration = Math.max(duration, timelines[i].getDuration()); skeletonData.animations.push(new Animation(name, timelines, duration)); } static private function readTimeline(keys : Array, timeline : CurveTimeline1, defaultValue : Number, scale : Number) : CurveTimeline1 { var keyMap : Object = keys[0]; var time : Number = getNumber(keyMap, ""time"", 0); var value : Number = getNumber(keyMap, ""value"", defaultValue) * scale; for (var frame : int = 0, bezier : int = 0;; frame++) { timeline.setFrame(frame, time, value); var nextMap : Object = keys[frame + 1]; if (!nextMap) { timeline.shrink(bezier); return timeline; } var time2 : Number = getNumber(nextMap, ""time"", 0); var value2 : Number = getNumber(nextMap, ""value"", defaultValue) * scale; if (keyMap.curve) bezier = readCurve(keyMap.curve, timeline, bezier, frame, 0, time, time2, value, value2, scale); time = time2; value = value2; keyMap = nextMap; } } static private function readTimeline2(keys : Array, timeline : CurveTimeline2, name1 : String, name2 : String, defaultValue : Number, scale : Number) : CurveTimeline2 { var keyMap : Object = keys[0]; var time : Number = getNumber(keyMap, ""time"", 0); var value1 : Number = getNumber(keyMap, name1, defaultValue) * scale; var value2 : Number = getNumber(keyMap, name2, defaultValue) * scale; for (var frame : int = 0, bezier : int = 0;; frame++) { timeline.setFrame(frame, time, value1, value2); var nextMap : Object = keys[frame + 1]; if (!nextMap) { timeline.shrink(bezier); return timeline; } var time2 : Number = getNumber(nextMap, ""time"", 0); var nvalue1 : Number = getNumber(nextMap, name1, defaultValue) * scale; var nvalue2 : Number = getNumber(nextMap, name2, defaultValue) * scale; var curve : Object = keyMap.curve; if (curve != null) { bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, value1, nvalue1, scale); bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, value2, nvalue2, scale); } time = time2; value1 = nvalue1; value2 = nvalue2; keyMap = nextMap; } } static private function readCurve(curve : Object, timeline : CurveTimeline, bezier : int, frame : int, value : Number, time1 : Number, time2 : Number, value1 : Number, value2 : Number, scale : Number) : int { if (curve == ""stepped"") { timeline.setStepped(frame); return bezier; } var i : int = value << 2; var cx1 : Number = curve[i]; var cy1 : Number = curve[i + 1] * scale; var cx2 : Number = curve[i + 2]; var cy2 : Number = curve[i + 3] * scale; timeline.setBezier(bezier, frame, value, time1, value1, cx1, cy1, cx2, cy2, time2, value2); return bezier + 1; } static private function getValue(map : Object, property : String, defaultValue : Object) : Object { return map.hasOwnProperty(property) ? map[property] : defaultValue; } static private function getNumber(map : Object, property : String, defaultValue : Number) : Number { return map.hasOwnProperty(property) ? Number(map[property]) : defaultValue; } static private function getFloatArray(map : Object, name : String, scale : Number) : Vector. { var list : Array = map[name]; var values : Vector. = new Vector.(list.length, true); var i : int = 0, n : int = list.length; if (scale == 1) { for (; i < n; i++) values[i] = list[i]; } else { for (; i < n; i++) values[i] = list[i] * scale; } return values; } static private function getIntArray(map : Object, name : String) : Vector. { var list : Array = map[name]; var values : Vector. = new Vector.(list.length, true); for (var i : int = 0, n : int = list.length; i < n; i++) values[i] = int(list[i]); return values; } static private function getUintArray(map : Object, name : String) : Vector. { var list : Array = map[name]; var values : Vector. = new Vector.(list.length, true); for (var i : int = 0, n : int = list.length; i < n; i++) values[i] = int(list[i]); return values; } } } import spine.attachments.MeshAttachment; class LinkedMesh { internal var parent : String, skin : String; internal var slotIndex : int; internal var mesh : MeshAttachment; internal var inheritDeform : Boolean; public function LinkedMesh(mesh : MeshAttachment, skin : String, slotIndex : int, parent : String, inheritDeform : Boolean) { this.mesh = mesh; this.skin = skin; this.slotIndex = slotIndex; this.parent = parent; this.inheritDeform = inheritDeform; } } ",12105,False,2429.50407533384,median "/* HelloWorld.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Demonstrate hardware based inversion of the display. The special command 0x0a7 is used for this. Only some display controller support this command: SSD1306 and compatible controller ST7565 and compatible controller Maybe also others support this command. Consult the datasheet... */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7528_ERC16064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7528_ERC16064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); u8g2.firstPage(); do { u8g2.setFont(u8g2_font_ncenB10_tr); u8g2.drawStr(0,24,""Hello World!""); } while ( u8g2.nextPage() ); } void loop(void) { delay(1000); u8g2.sendF(""c"", 0x0a7); delay(1000); u8g2.sendF(""c"", 0x0a6); } ",16378,True,5176.641084821966,median "/* Serial.ino Read from Serial, output to display. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2018, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list // setup the terminal (U8G2LOG) and connect to u8g2 for automatic refresh of the display // The size (width * height) depends on the selected font and the display #define U8LOG_WIDTH 20 #define U8LOG_HEIGHT 8 uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT]; U8G2LOG u8g2log; void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); Serial.begin(9600); // Start reading from Serial communication interface u8g2.begin(); u8g2.setFont(u8g2_font_5x7_tr); // set the font for the terminal window u8g2log.begin(u8g2, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer); u8g2log.setLineHeightOffset(0); // set extra space between lines in pixel, this can be negative u8g2log.setRedrawMode(1); // 0: Update screen with newline, 1: Update screen for every char } void loop(void) { char c; while (Serial.available() > 0) { c = Serial.read(); // read from Serial Monitor u8g2log.print(c); // print to display Serial.print(c); // and print back to monitor } } ",16240,True,4961.3326946772195,median "/* XORTest.ino Shows solid and transparent font modes with XOR draw. Conclusion: Only use transparent font modes with XOR draw. This example also demonstrates scrolling. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void testXOR(uint8_t x) { u8g2.setFont(u8g2_font_ncenB14_tr); //u8g2.setFont(u8g2_font_courB24_tn); u8g2.firstPage(); do { /* Solid font mode with XOR drawing: Does not make much sense */ u8g2.setFontMode(0); u8g2.setDrawColor(1); u8g2.drawBox(10, 8, 10, 10); u8g2.drawBox(40, 20, 30, 12); u8g2.drawBox(100, 8, 4, 22); u8g2.setDrawColor(2); u8g2.drawStr(x,26, ""XOR Test""); u8g2.drawHLine(0, 29, 128); /* Transparent font mode with XOR drawing: looks good */ u8g2.setFontMode(1); u8g2.setDrawColor(1); u8g2.drawBox(10, 8+32, 10, 10); u8g2.drawBox(40, 20+32, 30, 12); u8g2.drawBox(100, 8+32, 4, 22); u8g2.setDrawColor(2); u8g2.drawStr(x,26+32, ""XOR Test""); u8g2.drawHLine(0, 29+32, 128); } while ( u8g2.nextPage() ); } void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); u8g2.begin(); } void loop(void) { uint8_t i; i = 20; do { testXOR(20-i); delay(15); i--; } while( i != 0 ); i = 20; delay(15); do { testXOR(i); delay(15); i--; } while( i != 0 ); delay(15); } ",16207,True,4944.835000585082,median "// The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_128X32_VISIONOX_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X32_VISIONOX_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_LD7032_60X32_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_ALT_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7528_ERC16064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7528_ERC16064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7571_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7571_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7586S_ERC240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7586S_YMC240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1611_IDS4073_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16Bit Mode //U8G2_UC1611_IDS4073_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16Bit Mode //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display, SPI Mode 2 //U8G2_LS027B7DH01_M0_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display, SPI Mode 0 //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V ",16197,True,4516.023471186442,median "/* HelloWorld.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Demonstrate hardware based inversion of the display. The special command 0x0a7 is used for this. Only some display controller support this command: SSD1306 and compatible controller ST7565 and compatible controller Maybe also others support this command. Consult the datasheet... */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); } // SSD1306 scroll command void loop(void) { u8g2.sendF(""c"", 0x02e); // disable scroll u8g2.firstPage(); do { u8g2.setFont(u8g2_font_ncenB12_tr); u8g2.drawStr(0,15,""U8g2 Demo 1""); u8g2.drawStr(0,50,""HW Scroll""); } while ( u8g2.nextPage() ); // horizontal scroll to the left u8g2.sendF(""caaaaaac"", 0x027, 0, 3, 0, 7, 0, 255, 0x2f); // configure & start scroll delay(8000); u8g2.sendF(""c"", 0x02e); // disable scroll u8g2.firstPage(); do { u8g2.setFont(u8g2_font_ncenB12_tr); u8g2.drawStr(0,15,""U8g2 Demo 2""); u8g2.drawStr(0,50,""HW Scroll""); } while ( u8g2.nextPage() ); // vertical up and horizontal left scroll u8g2.sendF(""caaaaac"", 0x029, 0, 0, 0, 7, 1, 0x2f); // configure & start scroll delay(8000); } ",16222,True,4987.670024615891,median "/** * VERSION: 1.39 * DATE: 2010-09-27 * AS3 (AS2 version is also available) * UPDATES AND DOCUMENTATION AT: http://www.greensock.com/timelinemax/ **/ package com.greensock { import com.greensock.core.*; import com.greensock.events.TweenEvent; import flash.events.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *
    *
  • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
  • * *
  • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
  • * *
  • nest timelines within timelines as deeply as you want.
  • * *
  • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
  • * *
  • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
  • * *
  • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
  • * *
  • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
  • * *
  • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
  • * *
  • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
  • * *
  • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
  • * *
  • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
  • * *
  • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
  • * *
  • get the active tweens in the timeline with getActive().
  • * *
  • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
  • * *
  • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
  • *
* * EXAMPLE:

* * import com.greensock.~~;

* * // create the timeline and add an onComplete call to myFunction when the timeline completes
* var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

* * // add a tween
* myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

* * // add another tween at the end of the timeline (makes sequencing easy)
* myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

* * // repeat the entire timeline twice
* myTimeline.repeat = 2;

* * // delay the repeat by 0.5 seconds each time.
* myTimeline.repeatDelay = 0.5;

* * // pause the timeline (stop() works too)
* myTimeline.pause();

* * // reverse it anytime...
* myTimeline.reverse();

* * // Add a ""spin"" label 3-seconds into the timeline.
* myTimeline.addLabel(""spin"", 3);

* * // insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
* myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

* * // go to the ""spin"" label and play the timeline from there...
* myTimeline.gotoAndPlay(""spin"");

* * // call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * // add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
* myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

* * // nest another TimelineMax inside your timeline...
* var nestedTimeline:TimelineMax = new TimelineMax();
* nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
* myTimeline.append(nestedTimeline);

* * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

* * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

* * You can use the constructor's vars object to do all the setup too, like:

* * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

* * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

* * * NOTES: *
    *
  • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
  • *
  • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
  • *
* * Copyright 2010, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version : Number = 1.39; /** @private **/ protected var _repeat : int; /** @private **/ protected var _repeatDelay : Number; /** @private **/ protected var _cyclesComplete : int; /** @private **/ protected var _dispatcher : EventDispatcher; /** @private **/ protected var _hasUpdateListener : Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo : Boolean; /** * Constructor.

* * SPECIAL PROPERTIES
* The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
    *
  • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
  • * *
  • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
  • * *
  • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
  • * *
  • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
  • * *
  • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
  • * *
  • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
      *
    • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
    • *
    • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
    • *
    • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
    • *
    The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
  • * *
  • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
  • * *
  • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
  • * *
  • onStartParams : Array An Array of parameters to pass the onStart function.
  • * *
  • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
  • * *
  • onUpdateParams : Array An Array of parameters to pass the onUpdate function
  • * *
  • onComplete : Function A function that should be called when the timeline has finished
  • * *
  • onCompleteParams : Array An Array of parameters to pass the onComplete function
  • * *
  • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
  • * *
  • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
  • * *
  • onRepeat : Function A function that should be called every time the timeline repeats
  • * *
  • onRepeatParams : Array An Array of parameters to pass the onRepeat function
  • * *
  • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
  • * *
  • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
  • * *
  • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
  • * *
  • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
  • * *
  • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
  • * *
  • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
  • * *
  • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
  • *
* * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars : Object = null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return TweenLite instance */ public function addCallback(callback : Function, timeOrLabel : *, params : Array = null) : TweenLite { var cb : TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback : Function, timeOrLabel : *=null) : Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a : Array = getTweensOf(callback, false), success : Boolean; var i : int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

* * myTimeline.tweenTo(""myLabel2"");

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

* * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel : *, vars : Object = null) : TweenLite { var varsCopy : Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl : TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

* * var playheadTweens:TimelineMax = new TimelineMax();
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel : *, toTimeOrLabel : *, vars : Object = null) : TweenLite { var tl : TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween : TweenLite, timeline : TimelineMax, fromTime : Number) : void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { // don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t : Number, b : Number, c : Number, d : Number) : Number { return t / d; } /** @private **/ override public function renderTime(time : Number, suppressEvents : Boolean = false, force : Boolean = false) : void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; // so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur : Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime : Number = this.cachedTime, prevStart : Number = this.cachedStartTime, prevTimeScale : Number = this.cachedTimeScale, tween : TweenCore, isComplete : Boolean, rendered : Boolean, repeated : Boolean, next : TweenCore, dur : Number, prevPaused : Boolean = this.cachedPaused; if (time >= totalDur) { if (_rawPrevTime <= totalDur && _rawPrevTime != time) { if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { forceChildrenToBeginning(0, suppressEvents); this.cachedTime = 0; } else { forceChildrenToEnd(this.cachedDuration, suppressEvents); this.cachedTime = this.cachedDuration; } this.cachedTotalTime = totalDur; isComplete = !this.hasPausedChild(); rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { // In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime > 0) { // In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } if (_rawPrevTime >= 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; forceChildrenToBeginning(0, suppressEvents); this.cachedTime = 0; rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration : Number = this.cachedDuration + _repeatDelay; var prevCycles : int = _cyclesComplete; if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { _cyclesComplete = (this.cachedTotalTime / cycleDuration) >> 0; // rounds result, like int() if (_cyclesComplete == this.cachedTotalTime / cycleDuration) { _cyclesComplete--; // otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } if (prevCycles != _cyclesComplete) { repeated = true; } this.cachedTime = ((this.cachedTotalTime / cycleDuration) - _cyclesComplete) * cycleDuration; // originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } if (repeated && !isComplete && (this.cachedTime != prevTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward : Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward : Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap : Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTime == prevTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { // already rendered, so ignore } else if (this.cachedTime - prevTime > 0) { tween = _firstChild; while (tween) { next = tween.nextNode; // record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { // in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; // record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { // in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { // if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } else if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender : Boolean = false, suppressEvents : Boolean = false) : void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested : Boolean = true, tweens : Boolean = true, timelines : Boolean = false) : Array { var a : Array = [], all : Array = getChildren(nested, tweens, timelines), i : int; var l : int = all.length; var cnt : int = 0; for (i = 0; i < l; i += 1) { if (TweenCore(all[i]).active) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate() : void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time : Number = NaN) : String { if (!time && time != 0) { // faster than isNan() time = this.cachedTime; } var labels : Array = getLabelsArray(); var l : int = labels.length; for (var i : int = 0; i < l; i += 1) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time : Number = NaN) : String { if (!time && time != 0) { // faster than isNan() time = this.cachedTime; } var labels : Array = getLabelsArray(); var i : int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray() : Array { var a : Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } // ---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher() : void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = false) : void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type : String, listener : Function, useCapture : Boolean = false) : void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type : String) : Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type : String) : Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e : Event) : Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } // ---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress() : Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n : Number) : void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration() : Number { if (this.cacheIsDirty) { var temp : Number = super.totalDuration; // just forces refresh // Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @private **/ override public function set currentTime(n : Number) : void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat() : int { return _repeat; } public function set repeat(n : int) : void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay() : Number { return _repeatDelay; } public function set repeatDelay(n : Number) : void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel() : String { return getLabelBefore(this.cachedTime + 0.00000001); } } }",12295,False,2063.1612610634725,median "/* SENSOR STATUS DISPLAY https://github.com/Andy4495/ConnectedStatusMonitor Status display for various sensor data readings downloaded from ThingSpeak IoT Platform. Designed specifically for use with TM4C129 Connected LaunchPad and Kentec Touch Display BoosterPack (SPI) Initial web connection code based on ""Web client"" example sketch by David A. Mellis. NTP functions are from the Arduino Time library 07/10/2018 - A.T. - Initial updates 08/17/2018 - A.T. - Functional display code for weather station, workshop and slim temps, and garage door status. 08/19/2018 - A.T. - Add state machine to turn on display depending on state of light sensor on pin A13 08/20/2018 - A.T. - Add NTP time and date to status display 08/22/2018 - A.T. - Add automatic DST support. Other display cleanup. 08/23/2018 - A.T. - Fix DST to switch at 2:00 AM (instead of midnight) 08/24/2018 - A.T. - Minor updates: display time before sensor readings (since it is faster), use #define for DST effective hour, flash LED1 while display backlight off, display welcome message in larger (scaled) font, enable ethernet link and activity LEDs. 08/24/2018 - A.T. - Ethernet LEDs disabled by default, turned on with PUSH1 at reset. Use ""time.nist.gov"" instead of specific IP for time server. 10/02/2018 - A.T. - Replace Workshop display with Pond sensor. Update thresholds for value colors. 10/10/2018 - A.T. - Change pond battery threshold (using 2AAs instead of LiPo). 01/30/2019 - A.T. - Change pond battery threshold (using 3xAAs through a TPS715A33 3.3V regulator). - Fix display of negative temps. - Increased time to wait for ThingSpeak response. 11/04/2019 - A.T. - Add Workshop temp display. - Remove pond battery display (since it is AC powered) - Add battery level warning for Workshop sensor 11/07/2019 - A.T. - Add support for VFD display - Moved light sensor to pin 68/A19 11/11/2019 - A.T. - Update VFD message text. 11/14/2019 - A.T. - Adjust VFD display timing. Change lipo low batt level to 3.8V (lasts about 2.5 days at this point) 11/21/2019 - A.T. - Turn sensor 4 and 5 voltage reading red if less than 2 days remaining. (Sensors 4 and 5 now send charge time remaining instead of millis). 12/01/2019 - A.T. - Add support for displaying Pressure history on SparkFun OLED (parallel mode). -- Query ThingSpeak for pressure data even when display is off - Don't display time if no response/invalid response from time server - Updated low battery thresholds - Remove check for PUSH1 -- ethernet status LEDs always disabled. 01/19/2020 - A.T. - Fix a case where invalid time needs to be cleared from display. 01/21/2020 - A.T. - Change LiPo low battery threshold to 3.75V 02/13/2020 - A.T. - Update to use new Futaba VFD library naming. 04/27/2020 - A.T. - Change lipo time remaining threshold to zero, since the value does not seem to correlate with reality in this application. Tweaked the lipo battery voltage threshold. 09/01/2020 - A.T. - Add support for turtle pond temperature. Rename ""Pond"" to ""Fish"" to distinguish the two sensors. 09/14/2020 - A.T. - Change ""Gargoyle"" to ""Sensor5"" 02/03/2021 - A.T. - Add a check for zero pressure value. *** IMPORTANT *** The Kentec_35_SPI library has an issue where the _getRawTouch() function called in the begin() method can get stuck in an endless loop. Therefore, for proper operation of the display, it is necessary to comment out the call to _getRaw_Touch() in the begin() method in the file Screen_K35_SPI.cpp in the Kentec_35_SPI library. * *************** This sketch uses a modified version of SparkFun's MicroOLED library so that it compiles with Energia and works with MSP and TM4C129 processors: https://github.com/Andy4495/SparkFun_Micro_OLED_Arduino_Library * *************** *** Future improvements: Color a sensor value (or the label) yellow or red if an update has not been received for more than X minutes Add a pixel to y-coordinates to allow for hanging comma space (otherwise comma touches next line) Update lux string to include commas Deal with JSON parse failure -- maybe just display last good value (i.e., no display indication of bad JSON) */ #include // From https://arduinojson.org/ #include #include #include #include // From https://github.com/PaulStoffregen/Time #include ""dst.h"" #include ""Screen_K35_SPI.h"" Screen_K35_SPI myScreen; // ThingSpeakKeys.h is not included in the code distribution, since it contains private key info // This file should #define the following: // #define LAUNCHPAD_MAC {} // Plus #defines for each of your ThingSpeak feed keys and channel IDs #include ""ThingSpeakKeys.h"" #include ""Coordinates.h"" // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield // byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte mac[] = LAUNCHPAD_MAC; // Defined in ThingSpeakKeys.h const char* server = ""api.thingspeak.com""; const char* timeServer = ""time.nist.gov""; // Automatically resolves to nearest active server // IPAddress timeServer(132.163.97.1); // time.nist.gov // Use Standard Time for Time Zone. DST is corrected when printing. // Time zones are #defined in dst.h int timeZone = STANDARD_TZ; // Use standard time, DST correction is done later time_t t; uint16_t timeColor; EthernetUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets char receiveBuffer[1024] = {}; char printBuffer[32] = {}; char prevPrintBuffer[32] = {}; // Based on the Arduinojson.org site, this is the size needed for the buffer for the longest message (weather station) // (Actually, the final term could be ""+ 542"", but I changed it to ""+ 600"" just to be on the safe side. const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(10) + JSON_OBJECT_SIZE(16) + 600; // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; Layout layout; //----- Sensor Reading Global Storage -----// #define TEMPSIZE 6 #define LUXSIZE 9 #define RHSIZE 5 #define PSIZE 6 #define GDSIZE 7 #define BATTSIZE 6 #define TADSIZE 20 #define TIMESIZE 21 char outdoorTemp[TEMPSIZE]; char prevOutdoorTemp[TEMPSIZE]; char outdoorLux[LUXSIZE]; char prevOutdoorLux[LUXSIZE]; char outdoorRH[RHSIZE]; char prevOutdoorRH[RHSIZE]; char outdoorP[PSIZE]; char prevOutdoorP[PSIZE]; char slimTemp[TEMPSIZE]; char prevSlimTemp[TEMPSIZE]; char fishTemp[TEMPSIZE]; char prevFishTemp[TEMPSIZE]; char turtleTemp[TEMPSIZE]; char prevTurtleTemp[TEMPSIZE]; char sensor5Temp[TEMPSIZE]; char prevSensor5Temp[TEMPSIZE]; char workshopTemp[TEMPSIZE]; char prevWorkshopTemp[TEMPSIZE]; char garageDoor[GDSIZE]; char prevGarageDoor[GDSIZE]; char outdoorBatt[BATTSIZE]; char prevOutdoorBatt[BATTSIZE]; char slimBatt[BATTSIZE]; char prevSlimBatt[BATTSIZE]; char sensor5Batt[BATTSIZE]; char prevSensor5Batt[BATTSIZE]; char timeAndDate[TADSIZE]; char prevTimeAndDate[TADSIZE]; char weatherTime[TIMESIZE]; char slimTime[TIMESIZE]; char sensor5Time[TIMESIZE]; char pondTime[TIMESIZE]; char workshopTime[TIMESIZE]; char garageTime[TIMESIZE]; #define LIGHT_SENSOR_PIN 68 #define LIGHT_SENSOR_ADC A19 #define LIGHT_SENSOR_THRESHOLD 2000 // Based on 10K resistor and cheap photoresistor voltage divider and 12-bit ADC (4096 max value) #define LIGHTS_ON_SLEEP_TIME 30000 #define LIGHTS_OFF_SLEEP_TIME 5000 #define BACKLIGHT_PIN 40 #define SLEEPING_STATUS_LED PN_1 // Flash when display backlight is off to show the unit is active #define LIPO_LO_BATT_LEVEL 3780 // There are still a few days left at this level. #define LIPO_LO_TIME_REMAIN 0 // Value reported by Fuel Gauge drops too quickly. Setting to zero effectively disables this check. // VFD support #include #define VFD_CLOCK_PIN 74 #define VFD_DATA_PIN 73 #define VFD_RESET_PIN 72 #define VFD_BUFFER_EN 76 // Controls the EN pins on the CD40109 buffer #define VFD_POWER_CONTROL 77 // HIGH == OFF #define VFD_BRIGHTNESS 128 FutabaVFD162S vfd(VFD_CLOCK_PIN, VFD_DATA_PIN, VFD_RESET_PIN); int vfd_loop_counter = 0; // Used for testing // SparkFun OLED support // This is a modified version of SparkFun's library so that it compiles with Energia and works with MSP and TM4C129 processors #include // https://github.com/Andy4495/SparkFun_Micro_OLED_Arduino_Library // MicroOLED(uint8_t rst, uint8_t dc, uint8_t cs, uint8_t wr, uint8_t rd, // uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, // uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7) MicroOLED oled(35, 50, 79, 48, 58, 12, 29, 49, 85, 86, 59, 51, 30); /* Test data long p_hist[] = { 2902, 2902, 2902, 2902, 2903, 2903, 2903, 2903, 2903, 2903, 2903, 2904, 2904, 2904, 2905, 2905, 2904, 2905, 2905, 2905, 2905, 2905, 2905, 2906, 2906, 2906, 2907, 2907, 2907, 2907, 2909, 2908, 2908, 2908, 2909, 2909, 2909, 2908, 2909, 2909, 2909, 2910, 2910, 2911, 2911, 2911, 2911, 2911, 2911, 2912, 2912, 2912, 2912, 2913, 2913, 2913, 2913, 2914, 2914, 2914, 2914, 2914, 2915, 2915 }; */ // Circular buffer of Pressure readings. // Initial value of 0xFEFE so only show partial display with limited data on startup long p_hist[64]; unsigned int hist_position = 0; // Current position in p_hist circular buffer unsigned int hist_num_entries = 0; // Number of valid entries in the history (used after reset until buffer is filled first time) const unsigned int hist_len = 64; long last_weather_entry_id = 0; // Used to track whether we received new data unsigned long lastPressureQuery = 0; // Track times between readings when displays are off #define PRESSURE_READINGS_TIME 120000UL // Time between readings: 2 minutes (2 min * 60 s/min * 1000 ms/s) int statusLEDstate = 0; enum {LIGHTS_OFF, LIGHTS_TURNED_ON, LIGHTS_ON, LIGHTS_TURNED_OFF}; int lightSensorState = LIGHTS_OFF; void setup() { vfdIOSetup(); pinMode(LIGHT_SENSOR_PIN, INPUT); pinMode(SLEEPING_STATUS_LED, OUTPUT); /// This is just for checking button out of reset /// The rest of the time, this pin (85/PJ0) is used as data pin to OLED. pinMode(PUSH1, INPUT_PULLUP); // start the serial library: Serial.begin(9600); delay(1000); Serial.println(""Starting the Sensor Monitor...""); Serial.println(""Initializing LCD...""); myScreen.begin(); Serial.println(""...LCD Initialized""); myScreen.setPenSolid(true); myScreen.setFontSolid(false); myScreen.setFontSize(2); myScreen.setOrientation(2); displayStartup(); Serial.println(""Initializing Ethernet...""); // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println(""Failed to configure Ethernet using DHCP.""); myScreen.gText(24, 120, ""Failed!"", redColour, blackColour); myScreen.gText(24, 160, ""Program halted."", redColour, blackColour); // no point in carrying on, so do nothing forevermore: for (;;) ; } Serial.println(""Ethernet initialized...""); // give the Ethernet shield a second to initialize: delay(1000); /* Disable this check since the I/O pin used for PUSH1 is used by the OLED // Turn on Ethernet status LEDs if PUSH1 is pressed at reboot // Otherwise, they default to off. if (digitalRead(PUSH1) == LOW) { Ethernet.enableLinkLed(); Ethernet.enableActivityLed(); Serial.println(""Ethernet LINK and ACTIVITY LEDs enabled.""); } else { Serial.println(""Ethernet status LEDs disabled by default.""); // Following code can be used to turn off Ethernet status LEDs (default) // GPIODirModeSet(ACTIVITY_LED_BASE, ACTIVITY_LED_PIN, GPIO_DIR_MODE_IN); // GPIODirModeSet(LINK_LED_BASE, LINK_LED_PIN, GPIO_DIR_MODE_IN); } */ Serial.print(""JsonBuffer size: ""); Serial.println(bufferSize); Serial.println(""Connecting to NTP....""); // DisplayCharacterMap(); // For testing // Initialze the ""previous"" strings to empty prevOutdoorTemp[0] = 0; prevOutdoorLux[0] = 0; prevOutdoorRH[0] = 0; prevOutdoorP[0] = 0; prevSlimTemp[0] = 0; prevWorkshopTemp[0] = 0; prevFishTemp[0] = 0; prevTurtleTemp[0] = 0; prevGarageDoor[0] = 0; prevOutdoorBatt[0] = 0; prevSlimBatt[0] = 0; prevTimeAndDate[0] = 0; Udp.begin(localPort); Serial.println(""Setting up NTP...""); setSyncProvider(getNtpTime); Serial.println(""Setting up OLED.""); oled.begin(); // Initialize the OLED oled.clear(PAGE); // Clear the display's internal memory oled.clear(ALL); // Clear the library's display buffer oled.command(DISPLAYOFF); // Turn off the display until other displays are enabled } void loop() { int lightSensor; lightSensor = analogRead(LIGHT_SENSOR_ADC); Serial.print(""Light Sensor: ""); Serial.println(lightSensor); switch (lightSensorState) { case LIGHTS_OFF: if (lightSensor > LIGHT_SENSOR_THRESHOLD) { lightSensorState = LIGHTS_TURNED_ON; } else { if (millis() - lastPressureQuery > PRESSURE_READINGS_TIME) { lastPressureQuery = millis(); getPressure(); } statusLEDstate = ~statusLEDstate; // Flash the LED digitalWrite(SLEEPING_STATUS_LED, statusLEDstate); digitalWrite(BACKLIGHT_PIN, 0); vfdOff(); oled.clear(PAGE); oled.display(); oled.command(DISPLAYOFF); delay(LIGHTS_OFF_SLEEP_TIME); } break; case LIGHTS_TURNED_ON: statusLEDstate = 0; digitalWrite(SLEEPING_STATUS_LED, statusLEDstate); myScreen.clear(); digitalWrite(BACKLIGHT_PIN, 1); displayWelcome(); displayTitles(); vfdOn(); oled.command(DISPLAYON); lightSensorState = LIGHTS_ON; break; case LIGHTS_ON: if (lightSensor > LIGHT_SENSOR_THRESHOLD) { getAndDisplayTime(); getAndDisplayWeather(); getAndDisplaySlim(); getAndDisplaySensor5(); getAndDisplayPond(); getAndDisplayWorkshop(); getAndDisplayGarage(); Serial.println(""Disconnecting. Waiting 30 seconds before next query. ""); displayOLED(); displayVFD(); // The VFD display messages take 30 seconds, so no need for separate delay. // delay(LIGHTS_ON_SLEEP_TIME); } else { lightSensorState = LIGHTS_OFF; } break; case LIGHTS_TURNED_OFF: // State not needed Serial.println(""Invalid State! Changing state to LIGHTS_OFF.""); lightSensorState = LIGHTS_OFF; break; default: // Should never get here Serial.println(""Reached 'default' case in switch statement! Changing state to LIGHTS_OFF.""); lightSensorState = LIGHTS_OFF; break; } } void GetThingSpeakChannel(EthernetClient* c, const char* chan, const char* key, int results) { const int BUF_SIZE = 256; char buffer[BUF_SIZE]; snprintf(buffer, BUF_SIZE, ""GET /channels/%s/feeds.json?api_key=%s&results=%d"", chan, key, results); /// Serial.println(buffer); c->println(buffer); c->println(); } void GetThingSpeakField(EthernetClient* c, const char* chan, const char* key, const char* field, int results) { const int BUF_SIZE = 256; char buffer[BUF_SIZE]; snprintf(buffer, BUF_SIZE, ""GET /channels/%s/field/%s.json?api_key=%s&results=%d"", chan, field, key, results); /// Serial.println(buffer); c->println(buffer); c->println(); } void getAndDisplayWeather() { DynamicJsonBuffer jsonBuffer(bufferSize); int i = 0; char c; uint16_t battColor; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Weather Station GetThingSpeakChannel(&client, WEATHERSTATION_CHANNEL, WEATHERSTATION_KEY, 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.print(""JSON received size: ""); Serial.println(i); Serial.println(""JSON buffer: ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); /* ""Parsing Program"" code generated from ArduinoJson Assistant at arduinojson.org: JsonObject& channel = root[""channel""]; long channel_id = channel[""id""]; // 379945 const char* channel_name = channel[""name""]; // ""Weather-Station"" const char* channel_description = channel[""description""]; // ""Outdoor weather station using MSP430 LaunchPad and SENSORS BoosterPack. "" const char* channel_latitude = channel[""latitude""]; // ""0.0"" const char* channel_longitude = channel[""longitude""]; // ""0.0"" const char* channel_field1 = channel[""field1""]; // ""Temp-BME280"" const char* channel_field2 = channel[""field2""]; // ""Temp-TMP007-Ext"" const char* channel_field3 = channel[""field3""]; // ""Temp-TMP007-Int"" const char* channel_field4 = channel[""field4""]; // ""Temp-MSP430"" const char* channel_field5 = channel[""field5""]; // ""RH-BME280"" const char* channel_field6 = channel[""field6""]; // ""Pressure-BME280"" const char* channel_field7 = channel[""field7""]; // ""Lux-OPT3001"" const char* channel_field8 = channel[""field8""]; // ""Batt-Vcc"" const char* channel_created_at = channel[""created_at""]; // ""2017-12-07T00:28:34Z"" const char* channel_updated_at = channel[""updated_at""]; // ""2018-06-10T22:26:22Z"" long channel_last_entry_id = channel[""last_entry_id""]; // 90649 */ if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long Tf = strtol(feeds0[""field3""], NULL, 10); long lux = strtol(feeds0[""field7""], NULL, 10); long rh = strtol(feeds0[""field5""], NULL, 10); long p = strtol(feeds0[""field6""], NULL, 10); long wBatt = strtol(feeds0[""field8""], NULL, 10); strncpy(weatherTime, feeds0_created_at, TIMESIZE - 1); weatherTime[TIMESIZE - 1] = '\\0'; // hard-code a null terminator at end of string Serial.println(""Parsed JSON: ""); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); snprintf(outdoorTemp, TEMPSIZE, ""%3i.%i"", Tf / 10, abs(Tf) % 10); snprintf(outdoorLux, LUXSIZE, ""%8i"", lux); snprintf(outdoorRH, RHSIZE, ""%2i.%i"", rh / 10, rh % 10); snprintf(outdoorP, PSIZE, ""%2i.%02i"", p / 100, p % 100); snprintf(outdoorBatt, BATTSIZE, ""%i.%03i"", wBatt / 1000, wBatt % 1000); if (wBatt < 2600) battColor = redColour; else battColor = greenColour; if (feeds0_entry_id != last_weather_entry_id) { last_weather_entry_id = feeds0_entry_id; if (p != 0) { if (hist_num_entries < hist_len) // If we haven't filled the buffer the first time after reset { p_hist[hist_num_entries++] = p; } else // Once buffer has filled, then use a circular buffer and track current postion with wraparound { p_hist[hist_position++] = p; if (hist_position >= hist_len) hist_position = 0; // Wrap around if needed. } } } } else { Serial.println(""JSON parse failed.""); snprintf(outdoorTemp, TEMPSIZE, "" N/A""); snprintf(outdoorLux, LUXSIZE, "" N/A""); snprintf(outdoorRH, RHSIZE, "" N/A""); snprintf(outdoorP, PSIZE, "" N/A""); snprintf(outdoorBatt, BATTSIZE, "" N/A""); strcpy(weatherTime, "" N/A""); battColor = whiteColour; } myScreen.gText(layout.WeatherTempValue.x, layout.WeatherTempValue.y, prevOutdoorTemp, blackColour); myScreen.gText(layout.WeatherTempValue.x, layout.WeatherTempValue.y, outdoorTemp); strncpy(prevOutdoorTemp, outdoorTemp, TEMPSIZE); myScreen.gText(layout.WeatherLuxValue.x, layout.WeatherLuxValue.y, prevOutdoorLux, blackColour); myScreen.gText(layout.WeatherLuxValue.x, layout.WeatherLuxValue.y, outdoorLux); strncpy(prevOutdoorLux, outdoorLux, LUXSIZE); myScreen.gText(layout.WeatherRHValue.x, layout.WeatherRHValue.y, prevOutdoorRH, blackColour); myScreen.gText(layout.WeatherRHValue.x, layout.WeatherRHValue.y, outdoorRH); strncpy(prevOutdoorRH, outdoorRH, RHSIZE); myScreen.gText(layout.WeatherPValue.x, layout.WeatherPValue.y, prevOutdoorP, blackColour); myScreen.gText(layout.WeatherPValue.x, layout.WeatherPValue.y, outdoorP); strncpy(prevOutdoorP, outdoorP, PSIZE); myScreen.gText(layout.BattOutdoorValue.x, layout.BattOutdoorValue.y, prevOutdoorBatt, blackColour); myScreen.gText(layout.BattOutdoorValue.x, layout.BattOutdoorValue.y, outdoorBatt, battColor); strncpy(prevOutdoorBatt, outdoorBatt, BATTSIZE); } // getAndDisplayWeather() void getPressure() { DynamicJsonBuffer jsonBuffer(bufferSize); int i = 0; char c; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Weather Station GetThingSpeakField(&client, WEATHERSTATION_CHANNEL, WEATHERSTATION_KEY, ""field6"", 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.print(""JSON received size: ""); Serial.println(i); Serial.println(""JSON received (field6): ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); /* ""Parsing Program"" code generated from ArduinoJson Assistant at arduinojson.org: JsonObject& channel = root[""channel""]; long channel_id = channel[""id""]; // 379945 const char* channel_name = channel[""name""]; // ""Weather-Station"" const char* channel_description = channel[""description""]; // ""Outdoor weather station using MSP430 LaunchPad and SENSORS BoosterPack. "" const char* channel_latitude = channel[""latitude""]; // ""0.0"" const char* channel_longitude = channel[""longitude""]; // ""0.0"" const char* channel_field6 = channel[""field6""]; // ""Pressure-BME280"" const char* channel_created_at = channel[""created_at""]; // ""2017-12-07T00:28:34Z"" const char* channel_updated_at = channel[""updated_at""]; // ""2018-06-10T22:26:22Z"" long channel_last_entry_id = channel[""last_entry_id""]; // 90649 */ if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long p = strtol(feeds0[""field6""], NULL, 10); Serial.println(""Parsed JSON: ""); Serial.print(""Pressure: ""); Serial.println(p); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); if (feeds0_entry_id != last_weather_entry_id) { last_weather_entry_id = feeds0_entry_id; if (p != 0 ) { if (hist_num_entries < hist_len) // If we haven't filled the buffer the first time after reset { p_hist[hist_num_entries++] = p; } else // Once buffer has filled, then use a circular buffer and track current postion with wraparound { p_hist[hist_position++] = p; if (hist_position >= hist_len) hist_position = 0; // Wrap around if needed. } } } Serial.print(""hist_num_entries: ""); Serial.println(hist_num_entries); Serial.print(""hist_position: ""); Serial.println(hist_position); } else { Serial.println(""JSON parse failed.""); } } // getPressure() void getAndDisplaySlim() { DynamicJsonBuffer jsonBuffer(bufferSize); int i = 0; char c; uint16_t tempColor, battColor; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Slim's sensor GetThingSpeakChannel(&client, SLIMTEMP_CHANNEL, SLIMTEMP_KEY, 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.println(""JSON received: ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); /* ""Parsing Program"" code generated from ArduinoJson Assistant at arduinojson.org: JsonObject& channel = root[""channel""]; long channel_id = channel[""id""]; // 412285 const char* channel_name = channel[""name""]; // ""Slim's Temp"" const char* channel_description = channel[""description""]; // ""Slim's temperature sensor. "" const char* channel_latitude = channel[""latitude""]; // ""0.0"" const char* channel_longitude = channel[""longitude""]; // ""0.0"" const char* channel_field1 = channel[""field1""]; // ""Temp"" const char* channel_field2 = channel[""field2""]; // ""Vcc"" const char* channel_field3 = channel[""field3""]; // ""Loops"" const char* channel_field4 = channel[""field4""]; // ""Millis"" const char* channel_field5 = channel[""field5""]; // ""RSSI"" const char* channel_field6 = channel[""field6""]; // ""LQI"" const char* channel_created_at = channel[""created_at""]; // ""2018-01-26T17:19:35Z"" const char* channel_updated_at = channel[""updated_at""]; // ""2018-08-17T02:18:28Z"" long channel_last_entry_id = channel[""last_entry_id""]; // 165702 */ if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long Tslim = strtol(feeds0[""field1""], NULL, 10); long sBatt = strtol(feeds0[""field2""], NULL, 10); strncpy(slimTime, feeds0_created_at, TIMESIZE - 1); slimTime[TIMESIZE - 1] = '\\0'; // hard-code a null terminator at end of string Serial.println(""Parsed JSON: ""); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); if (Tslim < 800) tempColor = redColour; else tempColor = greenColour; if (sBatt < 2300) battColor = redColour; else battColor = greenColour; snprintf(slimTemp, TEMPSIZE, ""%3i.%i"", Tslim / 10, abs(Tslim) % 10); snprintf(slimBatt, BATTSIZE, ""%i.%03i"", sBatt / 1000, sBatt % 1000); } else { Serial.println(""JSON parse failed.""); snprintf(slimTemp, TEMPSIZE, "" N/A""); snprintf(slimBatt, BATTSIZE, "" N/A""); strcpy(slimTime, "" N/A""); battColor = whiteColour; tempColor = whiteColour; } myScreen.gText(layout.SlimTempValue.x, layout.SlimTempValue.y, prevSlimTemp, blackColour); myScreen.gText(layout.SlimTempValue.x, layout.SlimTempValue.y, slimTemp, tempColor); strncpy(prevSlimTemp, slimTemp, TEMPSIZE); myScreen.gText(layout.BattSlimValue.x, layout.BattSlimValue.y, prevSlimBatt, blackColour); myScreen.gText(layout.BattSlimValue.x, layout.BattSlimValue.y, slimBatt, battColor); strncpy(prevSlimBatt, slimBatt, BATTSIZE); } // getAndDisplaySlim() void getAndDisplaySensor5() { DynamicJsonBuffer jsonBuffer(bufferSize); int i = 0; char c; uint16_t tempColor, battColor; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Slim's sensor GetThingSpeakChannel(&client, TEMP5_CHANNEL, TEMP5_KEY, 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.println(""JSON received: ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); /* ""Parsing Program"" code generated from ArduinoJson Assistant at arduinojson.org: JsonObject& channel = root[""channel""]; long channel_id = channel[""id""]; // 412284 const char* channel_name = channel[""name""]; // ""Indoor Temp 5"" const char* channel_description = channel[""description""]; // ""Indoor Temp Sensor #5"" const char* channel_latitude = channel[""latitude""]; // ""0.0"" const char* channel_longitude = channel[""longitude""]; // ""0.0"" const char* channel_field1 = channel[""field1""]; // ""Temp"" const char* channel_field2 = channel[""field2""]; // ""Vcc"" const char* channel_field3 = channel[""field3""]; // ""Loops"" const char* channel_field4 = channel[""field4""]; // ""Millis"" const char* channel_field5 = channel[""field5""]; // ""RSSI"" const char* channel_field6 = channel[""field6""]; // ""LQI"" const char* channel_created_at = channel[""created_at""]; // ""2018-01-26T17:18:49Z"" const char* channel_updated_at = channel[""updated_at""]; // ""2018-09-18T08:44:13Z"" long channel_last_entry_id = channel[""last_entry_id""]; // 243115 */ if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long T5 = strtol(feeds0[""field1""], NULL, 10); long B5 = strtol(feeds0[""field2""], NULL, 10); unsigned long remain5 = strtoul(feeds0[""field4""], NULL, 10); strncpy(sensor5Time, feeds0_created_at, TIMESIZE - 1); sensor5Time[TIMESIZE - 1] = '\\0'; // hard-code a null terminator at end of string Serial.println(""Parsed JSON: ""); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); if (T5 > 850) tempColor = redColour; else tempColor = greenColour; if ( (B5 < LIPO_LO_BATT_LEVEL) || (remain5 < LIPO_LO_TIME_REMAIN) ) battColor = redColour; else battColor = greenColour; snprintf(sensor5Temp, TEMPSIZE, ""%3i.%i"", T5 / 10, abs(T5) % 10); snprintf(sensor5Batt, BATTSIZE, ""%i.%03i"", B5 / 1000, B5 % 1000); } else { Serial.println(""JSON parse failed.""); snprintf(sensor5Temp, TEMPSIZE, "" N/A""); snprintf(sensor5Batt, BATTSIZE, "" N/A""); strcpy(sensor5Time, "" N/A""); battColor = whiteColour; tempColor = whiteColour; } myScreen.gText(layout.Sensor5TempValue.x, layout.Sensor5TempValue.y, prevSensor5Temp, blackColour); myScreen.gText(layout.Sensor5TempValue.x, layout.Sensor5TempValue.y, sensor5Temp, tempColor); strncpy(prevSensor5Temp, sensor5Temp, TEMPSIZE); myScreen.gText(layout.BattSensor5Value.x, layout.BattSensor5Value.y, prevSensor5Batt, blackColour); myScreen.gText(layout.BattSensor5Value.x, layout.BattSensor5Value.y, sensor5Batt, battColor); strncpy(prevSensor5Batt, sensor5Batt, BATTSIZE); } // getAndDisplaySensor5() void getAndDisplayWorkshop() { DynamicJsonBuffer jsonBuffer(bufferSize); int i = 0; char c; uint16_t battColor; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Slim's sensor GetThingSpeakChannel(&client, TEMP4_CHANNEL, TEMP4_KEY, 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.println(""JSON received: ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long T4 = strtol(feeds0[""field1""], NULL, 10); long B4 = strtol(feeds0[""field2""], NULL, 10); long remain4 = strtol(feeds0[""field4""], NULL, 10); strncpy(workshopTime, feeds0_created_at, TIMESIZE - 1); workshopTime[TIMESIZE - 1] = '\\0'; // hard-code a null terminator at end of string Serial.println(""Parsed JSON: ""); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); if ( (B4 < LIPO_LO_BATT_LEVEL) || (remain4 < LIPO_LO_TIME_REMAIN)) battColor = redColour; else battColor = blackColour; snprintf(workshopTemp, TEMPSIZE, ""%3i.%i"", T4 / 10, abs(T4) % 10); } else { Serial.println(""JSON parse failed.""); snprintf(workshopTemp, TEMPSIZE, "" N/A""); strcpy(workshopTime, "" N/A""); } myScreen.gText(layout.WorkshopTempValue.x, layout.WorkshopTempValue.y, prevWorkshopTemp, blackColour); myScreen.gText(layout.WorkshopTempValue.x, layout.WorkshopTempValue.y, workshopTemp, whiteColour); myScreen.gText(layout.WorkshopLoBat.x, layout.WorkshopLoBat.y, WorkshopLoBat, battColor); strncpy(prevWorkshopTemp, workshopTemp, TEMPSIZE); } // getAndDisplayWorkshop() void getAndDisplayPond() { DynamicJsonBuffer jsonBuffer(bufferSize); int i = 0; char c; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Pond sensor GetThingSpeakChannel(&client, POND_CHANNEL, POND_KEY, 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.println(""JSON received: ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); /* ""Parsing Program"" code generated from ArduinoJson Assistant at arduinojson.org: JsonObject& channel = root[""channel""]; long channel_id = channel[""id""]; // 572681 const char* channel_name = channel[""name""]; // ""Pond Sensor"" const char* channel_description = channel[""description""]; // ""Various sensor readings at the pond. "" const char* channel_latitude = channel[""latitude""]; // ""0.0"" const char* channel_longitude = channel[""longitude""]; // ""0.0"" const char* channel_field1 = channel[""field1""]; // ""Air Temp"" const char* channel_field2 = channel[""field2""]; // ""Submerged Temp"" const char* channel_field3 = channel[""field3""]; // ""Battery mV"" const char* channel_field4 = channel[""field4""]; // ""Millis"" const char* channel_field5 = channel[""field5""]; // ""Pump Status"" const char* channel_field6 = channel[""field6""]; // ""Aerator Status"" const char* channel_created_at = channel[""created_at""]; // ""2018-09-09T19:02:08Z"" const char* channel_updated_at = channel[""updated_at""]; // ""2018-09-09T23:27:23Z"" int channel_last_entry_id = channel[""last_entry_id""]; // 77 */ if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long fishWaterT = strtol(feeds0[""field2""], NULL, 10); // The Turtle Pond temp sensor is stored in ""field1"" which was originally designed as the ""Air Temp"" value long turtleWaterT = strtol(feeds0[""field1""], NULL, 10); long pondmV = strtol(feeds0[""field3""], NULL, 10); strncpy(pondTime, feeds0_created_at, TIMESIZE - 1); pondTime[TIMESIZE - 1] = '\\0'; // hard-code a null terminator at end of string Serial.println(""Parsed JSON: ""); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); snprintf(fishTemp, TEMPSIZE, ""%3i.%i"", fishWaterT / 10, abs(fishWaterT) % 10); snprintf(turtleTemp, TEMPSIZE, ""%3i.%i"", turtleWaterT / 10, abs(turtleWaterT) % 10); } else { Serial.println(""JSON parse failed.""); snprintf(fishTemp, TEMPSIZE, "" N/A""); snprintf(turtleTemp, TEMPSIZE, "" N/A""); strcpy(pondTime, "" N/A""); } myScreen.gText(layout.FishTempValue.x, layout.FishTempValue.y, prevFishTemp, blackColour); myScreen.gText(layout.FishTempValue.x, layout.FishTempValue.y, fishTemp); strncpy(prevFishTemp, fishTemp, TEMPSIZE); myScreen.gText(layout.TurtleTempValue.x, layout.TurtleTempValue.y, prevTurtleTemp, blackColour); myScreen.gText(layout.TurtleTempValue.x, layout.TurtleTempValue.y, turtleTemp); strncpy(prevTurtleTemp, turtleTemp, TEMPSIZE); } // getAndDisplayPond() void getAndDisplayGarage() { DynamicJsonBuffer jsonBuffer(bufferSize); uint16_t doorColor; int i = 0; char c; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println(""connected""); } else { // if you didn't get a connection to the server: Serial.println(""connection failed""); } // Make a HTTP request for Garage sensor GetThingSpeakChannel(&client, REPEATER_CHANNEL, REPEATER_KEY, 1); // Need to check for connection and wait for characters // Need to timeout after some time, but not too soon before receiving response // Initially just use delay(), but replace with improved code using millis() delay(750); while (client.connected()) { /// Add a timeout with millis() c = client.read(); if (c != -1) receiveBuffer[i++] = c; if (i > sizeof(receiveBuffer) - 2) break; // Leave a byte for the null terminator } receiveBuffer[i] = '\\0'; Serial.println(""JSON received: ""); Serial.println(receiveBuffer); Serial.println(""""); client.stop(); JsonObject& root = jsonBuffer.parseObject(receiveBuffer); /* ""Parsing Program"" code generated from ArduinoJson Assistant at arduinojson.org: JsonObject& channel = root[""channel""]; long channel_id = channel[""id""]; // 452942 const char* channel_name = channel[""name""]; // ""Garage Repeater"" const char* channel_description = channel[""description""]; // ""Repeater hub to improve weather station reception"" const char* channel_latitude = channel[""latitude""]; // ""0.0"" const char* channel_longitude = channel[""longitude""]; // ""0.0"" const char* channel_field1 = channel[""field1""]; // ""Temp"" const char* channel_field2 = channel[""field2""]; // ""Vcc"" const char* channel_field3 = channel[""field3""]; // ""RxHubEthUptime"" const char* channel_field4 = channel[""field4""]; // ""Millis"" const char* channel_field5 = channel[""field5""]; // ""RSSI"" const char* channel_field6 = channel[""field6""]; // ""LQI"" const char* channel_field7 = channel[""field7""]; // ""RxHubMinutes"" const char* channel_field8 = channel[""field8""]; // ""Door"" const char* channel_created_at = channel[""created_at""]; // ""2018-03-18T16:17:02Z"" const char* channel_updated_at = channel[""updated_at""]; // ""2018-08-17T16:41:12Z"" long channel_last_entry_id = channel[""last_entry_id""]; // 51130 */ if (root.success()) { JsonObject& feeds0 = root[""feeds""][0]; const char* feeds0_created_at = feeds0[""created_at""]; // ""2018-06-10T22:26:23Z"" long feeds0_entry_id = feeds0[""entry_id""]; // 90649 long door = strtol(feeds0[""field8""], NULL, 10); strncpy(garageTime, feeds0_created_at, TIMESIZE - 1); garageTime[TIMESIZE - 1] = '\\0'; // hard-code a null terminator at end of string Serial.println(""Parsed JSON: ""); Serial.print(""Created at: ""); Serial.println(feeds0_created_at); Serial.print(""Entry ID: ""); Serial.println(feeds0_entry_id); if (door > 45) { snprintf(garageDoor, GDSIZE, "" OPEN""); doorColor = redColour; } else { snprintf(garageDoor, GDSIZE, ""Closed""); doorColor = greenColour; } } else { Serial.println(""JSON parse failed.""); snprintf(garageDoor, GDSIZE, "" N/A""); strcpy(garageTime, "" N/A""); doorColor = whiteColour; } myScreen.gText(layout.GDValue.x, layout.GDValue.y, prevGarageDoor, blackColour); myScreen.gText(layout.GDValue.x, layout.GDValue.y, garageDoor, doorColor); strncpy(prevGarageDoor, garageDoor, TEMPSIZE); } // getAndDisplayGarage() void getAndDisplayTime() { int i, yr, mo, da, dst_status; int theHour; t = now(); // Get the current time Serial.print(""timeNotSet = ""); Serial.print(timeNotSet); Serial.print("", timeNeedsSync = ""); Serial.print(timeNeedsSync); Serial.print("", timeSet = ""); Serial.print(timeSet); Serial.print("". timeStatus() = ""); Serial.println(timeStatus()); if (timeStatus() == timeSet) { yr = year(t); mo = month(t); da = day(t); theHour = hour(t); i = (yr - DST_FIRST_YEAR) * 4; dst_status = 0; // Assume standard time unless changed below if (yr <= MAX_DST_YEAR) { if ( (mo == dst_info[i + 0] && da == dst_info[i + 1] && theHour >= DST_EFFECTIVE_HOUR) || // DST changeover time (mo == dst_info[i + 0] && da > dst_info[i + 1]) || (mo > dst_info[i + 0]) ) // Past start of DST, now check if DST has ended if ( (mo == dst_info[i + 2] && da == dst_info[i + 3] && theHour < DST_EFFECTIVE_HOUR) || // ST changover time (mo == dst_info[i + 2] && da < dst_info[i + 3]) || (mo < dst_info[i + 2]) ) { dst_status = 1; t = t + 3600; // Add an hour } } /* /// Test Code int k, l; // i = (2029 - DST_FIRST_YEAR) * 4; i = 0; theHour = 1; for (k = 1; k < 13; k++) // Cycle through months for (l = 1; l < 32; l++) // Cycle through days { dst_status = 0; if ( (k == dst_info[i + 0] && l == dst_info[i + 1] && theHour >= DST_EFFECTIVE_HOUR) || // DST changeover at 2:00 AM (k == dst_info[i + 0] && l > dst_info[i + 1]) || (k > dst_info[i + 0]) ) // Past start of DST, now check if DST has ended if ( (k == dst_info[i + 2] && l == dst_info[i + 3] && theHour < DST_EFFECTIVE_HOUR) || // ST changover at 2:00 AM (k == dst_info[i + 2] && l < dst_info[i + 3]) || (k < dst_info[i + 2]) ) { dst_status = 1; } snprintf(timeAndDate, TADSIZE, ""%02d %s %02d:%02d %s"", l, monthShortStr(k), theHour, minute(t), (dst_status) ? DAYLIGHT_TZ_STRING : STANDARD_TZ_STRING); Serial.print(""Time and Date String: ""); Serial.println(timeAndDate); } /// */ snprintf(timeAndDate, TADSIZE, ""%02d %s %2d:%02d %s %s"", day(t), monthShortStr(month(t)), hourFormat12(t), minute(t), (isAM(t)) ? ""AM"" : ""PM"", (dst_status) ? DAYLIGHT_TZ_STRING : STANDARD_TZ_STRING); myScreen.gText(layout.TimeAndDateValue.x, layout.TimeAndDateValue.y, prevTimeAndDate, blackColour); myScreen.gText(layout.TimeAndDateValue.x, layout.TimeAndDateValue.y, timeAndDate, timeColor); strncpy(prevTimeAndDate, timeAndDate, TADSIZE); } // if (timeStatus() == timeSet) else { // timeStatus is not valid, so clear the time display myScreen.gText(layout.TimeAndDateValue.x, layout.TimeAndDateValue.y, prevTimeAndDate, blackColour); } } // getAndDisplayTime() void displayStartup() { myScreen.gText(0, 0, ""Weather Station"", yellowColour, blackColour, 1, 1); myScreen.gText(24, 60, ""Initializing"", redColour, blackColour); myScreen.gText(48, 80, ""Ethernet. . ."", redColour, blackColour); } void displayWelcome() { // myScreen.gText(0, 0, ""Weather Station"", blueColour, blackColour, 1, 1); myScreen.setFontSize(0); // gText font size multiplier only works with font size 0 myScreen.gText(24, 60, ""Welcome,"", redColour, blackColour, 4, 4); // For font size 2: x = 240/2 - 12*8/2 = 72 myScreen.gText(60, 120, ""Andy!"", redColour, blackColour, 4, 4); // For font size 2: x = 240/2 - 12*5/2 = 90 myScreen.setFontSize(2); delay(2000); } void displayTitles() { myScreen.setOrientation(2); myScreen.clear(); myScreen.gText(layout.WeatherTitle.x, layout.WeatherTitle.y, WeatherTitle); myScreen.gText(layout.WeatherTempUnits.x, layout.WeatherTempUnits.y, DegreesF); myScreen.gText(layout.WeatherLuxUnits.x, layout.WeatherLuxUnits.y, Lux); myScreen.gText(layout.WeatherRHUnits.x, layout.WeatherRHUnits.y, RH); myScreen.gText(layout.WeatherPUnits.x, layout.WeatherPUnits.y, inHG); myScreen.gText(layout.SlimTitle.x, layout.SlimTitle.y, SlimTitle); myScreen.gText(layout.SlimTempUnits.x, layout.SlimTempUnits.y, DegreesF); myScreen.gText(layout.Sensor5Title.x, layout.Sensor5Title.y, Sensor5Title); myScreen.gText(layout.Sensor5TempUnits.x, layout.Sensor5TempUnits.y, DegreesF); myScreen.gText(layout.WorkshopTitle.x, layout.WorkshopTitle.y, WorkshopTitle); myScreen.gText(layout.WorkshopTempUnits.x, layout.WorkshopTempUnits.y, DegreesF); myScreen.gText(layout.FishTitle.x, layout.FishTitle.y, FishTitle); myScreen.gText(layout.FishTempUnits.x, layout.FishTempUnits.y, DegreesF); myScreen.gText(layout.TurtleTitle.x, layout.TurtleTitle.y, TurtleTitle); myScreen.gText(layout.TurtleTempUnits.x, layout.TurtleTempUnits.y, DegreesF); myScreen.gText(layout.GDTitle.x, layout.GDTitle.y, GDTitle); myScreen.gText(layout.BattTitle.x, layout.BattTitle.y, BatteriesTitle); myScreen.gText(layout.BattOutdoorSubtitle.x, layout.BattOutdoorSubtitle.y, OutdoorSubtitle); myScreen.gText(layout.BattOutdoorUnits.x, layout.BattOutdoorValue.y, V); myScreen.gText(layout.BattSlimSubtitle.x, layout.BattSlimSubtitle.y, SlimSubtitle); myScreen.gText(layout.BattSlimUnits.x, layout.BattSlimUnits.y, V); myScreen.gText(layout.BattSensor5Subtitle.x, layout.BattSensor5Subtitle.y, Sensor5Subtitle); myScreen.gText(layout.BattSensor5Units.x, layout.BattSensor5Units.y, V); // Don't really need to display ""Time and Date"" title -- it's pretty obvious // myScreen.gText(layout.TimeAndDateTitle.x, layout.TimeAndDateTitle.y, TimeAndDateTitle); } void vfdIOSetup() { pinMode(VFD_BUFFER_EN, OUTPUT); digitalWrite(VFD_BUFFER_EN, LOW); // Disable CD40109 buffer pinMode(VFD_POWER_CONTROL, OUTPUT); digitalWrite(VFD_POWER_CONTROL, HIGH); // Turn off VFD power pinMode(VFD_CLOCK_PIN, OUTPUT); digitalWrite(VFD_CLOCK_PIN, HIGH); // Set IO pins to initial states pinMode(VFD_DATA_PIN, OUTPUT); digitalWrite(VFD_DATA_PIN, LOW); pinMode(VFD_RESET_PIN, OUTPUT); digitalWrite(VFD_RESET_PIN, LOW); // Call vfd.begin to set up internal variables. Note that the // VFD is powered down at this point, so the reset and device // configuration that is done in begin() aren't actually getting // received by VFD. vfd.begin(16, 2); } void vfdOff() { Serial.println(""VFD powered down.""); digitalWrite(VFD_BUFFER_EN, LOW); // Disable CD40109 buffer before turning off power digitalWrite(VFD_POWER_CONTROL, HIGH); } void vfdOn() { Serial.println(""VFD turned on.""); digitalWrite(VFD_POWER_CONTROL, LOW); // Turn on VFD power before enabling IO pins digitalWrite(VFD_CLOCK_PIN, HIGH); digitalWrite(VFD_DATA_PIN, LOW); digitalWrite(VFD_RESET_PIN, LOW); digitalWrite(VFD_BUFFER_EN, HIGH); // Enable IO pins digitalWrite(VFD_RESET_PIN, HIGH); // VFD reset sequence delay(5); digitalWrite(VFD_RESET_PIN, LOW); delay(5); // Configure VFD after coming out of reset vfd.writeCharacterDirect(FutabaVFD162S::SET_INPUT_OUTPUT_MODE_CHARACTER); vfd.writeCharacterDirect(0x01); // I/O Mode 1: Unidirectional (no handshake) vfd.clear(); vfd.setBrightness(VFD_BRIGHTNESS); } void displayVFD() { #define DISPLAY_DELAY 7000 // Printing time text ""+5"" to skip over ""YYYY-"" in time string vfd.clear(); vfd.print(""Weather: ""); vfd.setCursor(0, 1); // Line 2 vfd.print(weatherTime + 5); delay(DISPLAY_DELAY); vfd.clear(); vfd.print(""Slim: ""); vfd.setCursor(0, 1); // Line 2 vfd.print(slimTime + 5); delay(DISPLAY_DELAY); vfd.clear(); vfd.print(""Sensor 5: ""); vfd.setCursor(0, 1); // Line 2 vfd.print(sensor5Time + 5); delay(DISPLAY_DELAY); vfd.clear(); vfd.print(""Pond: ""); vfd.setCursor(0, 1); // Line 2 vfd.print(pondTime + 5); delay(DISPLAY_DELAY); vfd.clear(); vfd.print(""Workshop: ""); vfd.setCursor(0, 1); // Line 2 vfd.print(workshopTime + 5); delay(DISPLAY_DELAY); vfd.clear(); vfd.print(""Repeater: ""); vfd.setCursor(0, 1); // Line 2 vfd.print(garageTime + 5); // delay(DISPLAY_DELAY); // No delay after last status, since pulling update from ThingSpeak takes several seconds } // displayVFD() void displayOLED() { int hist_max = 0; int hist_min = 32767; int hist_mid; int hist_delta; char p_decimal[3]; for (int i = 0; i < hist_num_entries; i++) { if ( p_hist[i] > hist_max) hist_max = p_hist[i]; if ( p_hist[i] < hist_min) hist_min = p_hist[i]; } hist_mid = (hist_max + hist_min) / 2; hist_delta = hist_max - hist_min; Serial.print(""Min: ""); Serial.println(hist_min); Serial.print(""Max: ""); Serial.println(hist_max); Serial.print(""Hist size: ""); Serial.println(hist_num_entries); Serial.print(""Hist position: ""); Serial.println(hist_position); oled.clear(PAGE); // Clear the buffer // If range is values is < 30 (lines available in display area), then plot the points relative to row 15 // If values is >= 30, then use map function to fit the values in display area for (int i = 0; i < hist_num_entries; i++) { if (hist_delta < 30) oled.pixel(i, 15 - (p_hist[(i + hist_position ) % hist_len] - hist_mid)); else oled.pixel(i, map(p_hist[(i + hist_position ) % hist_len], hist_min, hist_max, 34, 0)); } if (hist_num_entries > 0) { oled.setFontType(1); // 8x16 characters oled.setCursor(0, 37); // Bottom row, no blank pixel under letters oled.print(""P:""); if (hist_num_entries < hist_len) oled.print(p_hist[hist_num_entries - 1] / 100); else oled.print(p_hist[(hist_position - 1) % hist_len] / 100); oled.print("".""); if (hist_num_entries < hist_len) { snprintf(p_decimal, 3, ""%.2d"", p_hist[hist_num_entries - 1] % 100); } else { snprintf(p_decimal, 3, ""%.2d"", p_hist[(hist_position - 1) % hist_len] % 100); } oled.print(p_decimal); oled.display(); } } // displayOLED() time_t getNtpTime() { while (Udp.parsePacket() > 0) ; // discard any previously received packets Serial.println(""Transmit NTP Request""); sendNTPpacket(timeServer); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { Serial.println(""Receive NTP Response""); timeColor = whiteColour; Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; } } Serial.println(""No NTP Response :-(""); timeColor = blackColour; return 0; // return 0 if unable to get the time } // send an NTP request to the time server at the given address void sendNTPpacket(const char* address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } void DisplayCharacterMap() { unsigned char tempChar[2]; tempChar[1] = '\\0'; tempChar[0] = 128; int i, j; delay(2000); myScreen.clear(); for (j = 0; j < 8; j++) { for (i = 0; i < 16; i++) { myScreen.gText(i * 12, j * 16, (const char*) tempChar); tempChar[0]++; } } // delay(60000); } ",16345,True,3093.7537728970196,median "/* Feathers Copyright 2012-2014 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { import feathers.core.IFeathersControl; import feathers.core.IValidating; import flash.errors.IllegalOperationError; import flash.geom.Point; import starling.display.DisplayObject; import starling.events.Event; import starling.events.EventDispatcher; /** * Dispatched when a property of the layout changes, indicating that a * redraw is probably needed. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Positions items from top to bottom in a single column. * * @see http://wiki.starling-framework.org/feathers/vertical-layout */ public class VerticalLayout extends EventDispatcher implements IVariableVirtualLayout, ITrimmedVirtualLayout { /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the top. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_TOP:String = ""top""; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the middle. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_MIDDLE:String = ""middle""; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the bottom. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_BOTTOM:String = ""bottom""; /** * The items will be aligned to the left of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_LEFT:String = ""left""; /** * The items will be aligned to the center of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_CENTER:String = ""center""; /** * The items will be aligned to the right of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_RIGHT:String = ""right""; /** * The items will fill the width of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_JUSTIFY:String = ""justify""; /** * Constructor. */ public function VerticalLayout() { } /** * @private */ protected var _heightCache:Array = []; /** * @private */ protected var _discoveredItemsCache:Vector. = new []; /** * @private */ protected var _gap:Number = 0; /** * The space, in pixels, between items. * * @default 0 */ public function get gap():Number { return this._gap; } /** * @private */ public function set gap(value:Number):void { if(this._gap == value) { return; } this._gap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _firstGap:Number = NaN; /** * The space, in pixels, between the first and second items. If the * value of firstGap is NaN, the value of the * gap property will be used instead. * * @default NaN */ public function get firstGap():Number { return this._firstGap; } /** * @private */ public function set firstGap(value:Number):void { if(this._firstGap == value) { return; } this._firstGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _lastGap:Number = NaN; /** * The space, in pixels, between the last and second to last items. If * the value of lastGap is NaN, the value of * the gap property will be used instead. * * @default NaN */ public function get lastGap():Number { return this._lastGap; } /** * @private */ public function set lastGap(value:Number):void { if(this._lastGap == value) { return; } this._lastGap = value; this.dispatchEventWith(Event.CHANGE); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The space, in pixels, that appears on top, before the first item. * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingRight:Number = 0; /** * The minimum space, in pixels, to the right of the items. * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The space, in pixels, that appears on the bottom, after the last * item. * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The minimum space, in pixels, to the left of the items. * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalAlign:String = VERTICAL_ALIGN_TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the total item height is less than the bounds, the positions of * the items can be aligned vertically. * * @default VerticalLayout.VERTICAL_ALIGN_TOP * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _horizontalAlign:String = HORIZONTAL_ALIGN_LEFT; [Inspectable(type=""String"",enumeration=""left,center,right,justify"")] /** * The alignment of the items horizontally, on the x-axis. * * @default VerticalLayout.HORIZONTAL_ALIGN_LEFT * * @see #HORIZONTAL_ALIGN_LEFT * @see #HORIZONTAL_ALIGN_CENTER * @see #HORIZONTAL_ALIGN_RIGHT * @see #HORIZONTAL_ALIGN_JUSTIFY */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this._horizontalAlign == value) { return; } this._horizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _useVirtualLayout:Boolean = true; /** * @inheritDoc * * @default true */ public function get useVirtualLayout():Boolean { return this._useVirtualLayout; } /** * @private */ public function set useVirtualLayout(value:Boolean):void { if(this._useVirtualLayout == value) { return; } this._useVirtualLayout = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _hasVariableItemDimensions:Boolean = false; /** * When the layout is virtualized, and this value is true, the items may * have variable width values. If false, the items will all share the * same width value with the typical item. * * @default false */ public function get hasVariableItemDimensions():Boolean { return this._hasVariableItemDimensions; } /** * @private */ public function set hasVariableItemDimensions(value:Boolean):void { if(this._hasVariableItemDimensions == value) { return; } this._hasVariableItemDimensions = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _distributeHeights:Boolean = false; /** * Distributes the height of the view port equally to each item. If the * view port height needs to be measured, the largest item's height will * be used for all items, subject to any specified minimum and maximum * height values. * * @default false */ public function get distributeHeights():Boolean { return this._distributeHeights; } /** * @private */ public function set distributeHeights(value:Boolean):void { if(this._distributeHeights == value) { return; } this._distributeHeights = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _manageVisibility:Boolean = false; /** * Determines if items will be set invisible if they are outside the * view port. Can improve performance, especially for non-virtual * layouts. If true, you will not be able to manually * change the visible property of any items in the layout. * * @default false */ public function get manageVisibility():Boolean { return this._manageVisibility; } /** * @private */ public function set manageVisibility(value:Boolean):void { if(this._manageVisibility == value) { return; } this._manageVisibility = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _beforeVirtualizedItemCount:int = 0; /** * @inheritDoc */ public function get beforeVirtualizedItemCount():int { return this._beforeVirtualizedItemCount; } /** * @private */ public function set beforeVirtualizedItemCount(value:int):void { if(this._beforeVirtualizedItemCount == value) { return; } this._beforeVirtualizedItemCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _afterVirtualizedItemCount:int = 0; /** * @inheritDoc */ public function get afterVirtualizedItemCount():int { return this._afterVirtualizedItemCount; } /** * @private */ public function set afterVirtualizedItemCount(value:int):void { if(this._afterVirtualizedItemCount == value) { return; } this._afterVirtualizedItemCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItem:DisplayObject; /** * @inheritDoc * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemWidth * @see #typicalItemHeight */ public function get typicalItem():DisplayObject { return this._typicalItem; } /** * @private */ public function set typicalItem(value:DisplayObject):void { if(this._typicalItem == value) { return; } this._typicalItem = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _resetTypicalItemDimensionsOnMeasure:Boolean = false; /** * If set to true, the width and height of the * typicalItem will be reset to typicalItemWidth * and typicalItemHeight, respectively, whenever the * typical item needs to be measured. The measured dimensions of the * typical item are used to fill in the blanks of a virtualized layout * for virtual items that don't have their own display objects to * measure yet. * * @default false * * @see #typicalItemWidth * @see #typicalItemHeight * @see #typicalItem */ public function get resetTypicalItemDimensionsOnMeasure():Boolean { return this._resetTypicalItemDimensionsOnMeasure; } /** * @private */ public function set resetTypicalItemDimensionsOnMeasure(value:Boolean):void { if(this._resetTypicalItemDimensionsOnMeasure == value) { return; } this._resetTypicalItemDimensionsOnMeasure = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemWidth:Number = NaN; /** * Used to reset the width, in pixels, of the typicalItem * for measurement. The measured dimensions of the typical item are used * to fill in the blanks of a virtualized layout for virtual items that * don't have their own display objects to measure yet. * *

This value is only used when resetTypicalItemDimensionsOnMeasure * is set to true. If resetTypicalItemDimensionsOnMeasure * is set to false, this value will be ignored and the * typicalItem dimensions will not be reset before * measurement.

* *

If typicalItemWidth is set to NaN, the * typical item will auto-size itself to its preferred width. If you * pass a valid Number value, the typical item's width will * be set to a fixed size. May be used in combination with * typicalItemHeight.

* * @default NaN * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemHeight * @see #typicalItem */ public function get typicalItemWidth():Number { return this._typicalItemWidth; } /** * @private */ public function set typicalItemWidth(value:Number):void { if(this._typicalItemWidth == value) { return; } this._typicalItemWidth = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemHeight:Number = NaN; /** * Used to reset the height, in pixels, of the typicalItem * for measurement. The measured dimensions of the typical item are used * to fill in the blanks of a virtualized layout for virtual items that * don't have their own display objects to measure yet. * *

This value is only used when resetTypicalItemDimensionsOnMeasure * is set to true. If resetTypicalItemDimensionsOnMeasure * is set to false, this value will be ignored and the * typicalItem dimensions will not be reset before * measurement.

* *

If typicalItemHeight is set to NaN, the * typical item will auto-size itself to its preferred height. If you * pass a valid Number value, the typical item's height will * be set to a fixed size. May be used in combination with * typicalItemWidth.

* * @default NaN * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemWidth * @see #typicalItem */ public function get typicalItemHeight():Number { return this._typicalItemHeight; } /** * @private */ public function set typicalItemHeight(value:Number):void { if(this._typicalItemHeight == value) { return; } this._typicalItemHeight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _scrollPositionVerticalAlign:String = VERTICAL_ALIGN_MIDDLE; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * When the scroll position is calculated for an item, an attempt will * be made to align the item to this position. * * @default VerticalLayout.VERTICAL_ALIGN_MIDDLE * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get scrollPositionVerticalAlign():String { return this._scrollPositionVerticalAlign; } /** * @private */ public function set scrollPositionVerticalAlign(value:String):void { this._scrollPositionVerticalAlign = value; } /** * @inheritDoc */ public function get requiresLayoutOnScroll():Boolean { return this._manageVisibility || this._useVirtualLayout; } /** * @inheritDoc */ public function layout(items:Vector., viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult { var scrollX:Number = viewPortBounds ? viewPortBounds.scrollX : 0; var scrollY:Number = viewPortBounds ? viewPortBounds.scrollY : 0; var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; if(this._useVirtualLayout) { this.prepareTypicalItem(explicitWidth - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } if(!this._useVirtualLayout || this._hasVariableItemDimensions || this._distributeHeights || this._horizontalAlign != HORIZONTAL_ALIGN_JUSTIFY || explicitWidth != explicitWidth) //isNaN { this.validateItems(items, explicitWidth - this._paddingLeft - this._paddingRight, explicitHeight); } if(!this._useVirtualLayout) { this.applyPercentHeights(items, explicitHeight, minHeight, maxHeight); } var distributedHeight:Number; if(this._distributeHeights) { distributedHeight = this.calculateDistributedHeight(items, explicitHeight, minHeight, maxHeight); } var hasDistributedHeight:Boolean = distributedHeight == distributedHeight; //!isNaN this._discoveredItemsCache.length = 0; var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var maxItemWidth:Number = this._useVirtualLayout ? calculatedTypicalItemWidth : 0; var positionY:Number = boundsY + this._paddingTop; var indexOffset:int = 0; var itemCount:int = items.length; var totalItemCount:int = itemCount; if(this._useVirtualLayout && !this._hasVariableItemDimensions) { totalItemCount += this._beforeVirtualizedItemCount + this._afterVirtualizedItemCount; indexOffset = this._beforeVirtualizedItemCount; positionY += (this._beforeVirtualizedItemCount * (calculatedTypicalItemHeight + this._gap)); if(hasFirstGap && this._beforeVirtualizedItemCount > 0) { positionY = positionY - this._gap + this._firstGap; } } var secondToLastIndex:int = totalItemCount - 2; var discoveredItemsCacheLastIndex:int = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; var iNormalized:int = i + indexOffset; var gap:Number = this._gap; if(hasFirstGap && iNormalized == 0) { gap = this._firstGap; } else if(hasLastGap && iNormalized > 0 && iNormalized == secondToLastIndex) { gap = this._lastGap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedHeight:Number = this._heightCache[iNormalized]; } if(this._useVirtualLayout && !item) { if(!this._hasVariableItemDimensions || cachedHeight != cachedHeight) //isNaN { positionY += calculatedTypicalItemHeight + gap; } else { positionY += cachedHeight + gap; } } else { if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y = item.pivotY + positionY; var itemWidth:Number = item.width; var itemHeight:Number; if(hasDistributedHeight) { item.height = itemHeight = distributedHeight; } else { itemHeight = item.height; } if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(cachedHeight != itemHeight) { this._heightCache[iNormalized] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } positionY += itemHeight + gap; if(itemWidth > maxItemWidth) { maxItemWidth = itemWidth; } if(this._useVirtualLayout) { this._discoveredItemsCache[discoveredItemsCacheLastIndex] = item; discoveredItemsCacheLastIndex++; } } } if(this._useVirtualLayout && !this._hasVariableItemDimensions) { positionY += (this._afterVirtualizedItemCount * (calculatedTypicalItemHeight + this._gap)); if(hasLastGap && this._afterVirtualizedItemCount > 0) { positionY = positionY - this._gap + this._lastGap; } } var discoveredItems:Vector. = this._useVirtualLayout ? this._discoveredItemsCache : items; var totalWidth:Number = maxItemWidth + this._paddingLeft + this._paddingRight; var availableWidth:Number = explicitWidth; if(availableWidth != availableWidth) //isNaN { availableWidth = totalWidth; if(availableWidth < minWidth) { availableWidth = minWidth; } else if(availableWidth > maxWidth) { availableWidth = maxWidth; } } var discoveredItemCount:int = discoveredItems.length; var totalHeight:Number = positionY - this._gap + this._paddingBottom - boundsY; var availableHeight:Number = explicitHeight; if(availableHeight != availableHeight) //isNaN { availableHeight = totalHeight; if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } if(totalHeight < availableHeight) { var verticalAlignOffsetY:Number = 0; if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { verticalAlignOffsetY = availableHeight - totalHeight; } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { verticalAlignOffsetY = (availableHeight - totalHeight) / 2; } if(verticalAlignOffsetY != 0) { for(i = 0; i < discoveredItemCount; i++) { item = discoveredItems[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y += verticalAlignOffsetY; } } } for(i = 0; i < discoveredItemCount; i++) { item = discoveredItems[i]; var layoutItem:ILayoutDisplayObject = item as ILayoutDisplayObject; if(layoutItem && !layoutItem.includeInLayout) { continue; } if(this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY) { item.x = item.pivotX + boundsX + this._paddingLeft; item.width = availableWidth - this._paddingLeft - this._paddingRight; } else { if(layoutItem) { var layoutData:VerticalLayoutData = layoutItem.layoutData as VerticalLayoutData; if(layoutData) { var percentWidth:Number = layoutData.percentWidth; if(percentWidth == percentWidth) //!isNaN { if(percentWidth < 0) { percentWidth = 0; } if(percentWidth > 100) { percentWidth = 100; } itemWidth = percentWidth * (availableWidth - this._paddingLeft - this._paddingRight) / 100; if(item is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(item); var itemMinWidth:Number = feathersItem.minWidth; if(itemWidth < itemMinWidth) { itemWidth = itemMinWidth; } else { var itemMaxWidth:Number = feathersItem.maxWidth; if(itemWidth > itemMaxWidth) { itemWidth = itemMaxWidth; } } } item.width = itemWidth; } } } switch(this._horizontalAlign) { case HORIZONTAL_ALIGN_RIGHT: { item.x = item.pivotX + boundsX + availableWidth - this._paddingRight - item.width; break; } case HORIZONTAL_ALIGN_CENTER: { item.x = item.pivotX + boundsX + this._paddingLeft + (availableWidth - this._paddingLeft - this._paddingRight - item.width) / 2; break; } default: //left { item.x = item.pivotX + boundsX + this._paddingLeft; } } } if(this.manageVisibility) { item.visible = ((item.y - item.pivotY + item.height) >= (boundsY + scrollY)) && ((item.y - item.pivotY) < (scrollY + availableHeight)); } } this._discoveredItemsCache.length = 0; if(!result) { result = new LayoutBoundsResult(); } result.contentWidth = this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY ? availableWidth : totalWidth; result.contentHeight = totalHeight; result.viewPortWidth = availableWidth; result.viewPortHeight = availableHeight; return result; } /** * @inheritDoc */ public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point { if(!result) { result = new Point(); } if(!this._useVirtualLayout) { throw new IllegalOperationError(""measureViewPort() may be called only if useVirtualLayout is true."") } var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; var needsWidth:Boolean = explicitWidth != explicitWidth; //isNaN var needsHeight:Boolean = explicitHeight != explicitHeight; //isNaN if(!needsWidth && !needsHeight) { result.x = explicitWidth; result.y = explicitHeight; return result; } var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; this.prepareTypicalItem(explicitWidth - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var positionY:Number; if(this._distributeHeights) { positionY = (calculatedTypicalItemHeight + this._gap) * itemCount; } else { positionY = 0; var maxItemWidth:Number = calculatedTypicalItemWidth; if(!this._hasVariableItemDimensions) { positionY += ((calculatedTypicalItemHeight + this._gap) * itemCount); } else { for(var i:int = 0; i < itemCount; i++) { var cachedHeight:Number = this._heightCache[i]; if(cachedHeight != cachedHeight) //isNaN { positionY += calculatedTypicalItemHeight + this._gap; } else { positionY += cachedHeight + this._gap; } } } } positionY -= this._gap; if(hasFirstGap && itemCount > 1) { positionY = positionY - this._gap + this._firstGap; } if(hasLastGap && itemCount > 2) { positionY = positionY - this._gap + this._lastGap; } if(needsWidth) { var resultWidth:Number = maxItemWidth + this._paddingLeft + this._paddingRight; if(resultWidth < minWidth) { resultWidth = minWidth; } else if(resultWidth > maxWidth) { resultWidth = maxWidth; } result.x = resultWidth; } else { result.x = explicitWidth; } if(needsHeight) { var resultHeight:Number = positionY + this._paddingTop + this._paddingBottom; if(resultHeight < minHeight) { resultHeight = minHeight; } else if(resultHeight > maxHeight) { resultHeight = maxHeight; } result.y = resultHeight; } else { result.y = explicitHeight; } return result; } /** * @inheritDoc */ public function resetVariableVirtualCache():void { this._heightCache.length = 0; } /** * @inheritDoc */ public function resetVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { delete this._heightCache[index]; if(item) { this._heightCache[index] = item.height; this.dispatchEventWith(Event.CHANGE); } } /** * @inheritDoc */ public function addToVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { var heightValue:* = item ? item.height : undefined; this._heightCache.splice(index, 0, heightValue); } /** * @inheritDoc */ public function removeFromVariableVirtualCacheAtIndex(index:int):void { this._heightCache.splice(index, 1); } /** * @inheritDoc */ public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector. = null):Vector. { if(result) { result.length = 0; } else { result = new []; } if(!this._useVirtualLayout) { throw new IllegalOperationError(""getVisibleIndicesAtScrollPosition() may be called only if useVirtualLayout is true."") } this.prepareTypicalItem(width - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var resultLastIndex:int = 0; var visibleTypicalItemCount:int = Math.ceil(height / (calculatedTypicalItemHeight + this._gap)); if(!this._hasVariableItemDimensions) { //this case can be optimized because we know that every item has //the same height var indexOffset:int = 0; var totalItemHeight:Number = itemCount * (calculatedTypicalItemHeight + this._gap) - this._gap; if(hasFirstGap && itemCount > 1) { totalItemHeight = totalItemHeight - this._gap + this._firstGap; } if(hasLastGap && itemCount > 2) { totalItemHeight = totalItemHeight - this._gap + this._lastGap; } if(totalItemHeight < height) { if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { indexOffset = Math.ceil((height - totalItemHeight) / (calculatedTypicalItemHeight + this._gap)); } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { indexOffset = Math.ceil(((height - totalItemHeight) / (calculatedTypicalItemHeight + this._gap)) / 2); } } var minimum:int = (scrollY - this._paddingTop) / (calculatedTypicalItemHeight + this._gap); if(minimum < 0) { minimum = 0; } minimum -= indexOffset; //if we're scrolling beyond the final item, we should keep the //indices consistent so that items aren't destroyed and //recreated unnecessarily var maximum:int = minimum + visibleTypicalItemCount; if(maximum >= itemCount) { maximum = itemCount - 1; } minimum = maximum - visibleTypicalItemCount; if(minimum < 0) { minimum = 0; } for(var i:int = minimum; i <= maximum; i++) { result[resultLastIndex] = i; resultLastIndex++; } return result; } var secondToLastIndex:int = itemCount - 2; var maxPositionY:Number = scrollY + height; var positionY:Number = this._paddingTop; for(i = 0; i < itemCount; i++) { var gap:Number = this._gap; if(hasFirstGap && i == 0) { gap = this._firstGap; } else if(hasLastGap && i > 0 && i == secondToLastIndex) { gap = this._lastGap; } var cachedHeight:Number = this._heightCache[i]; if(cachedHeight != cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } var oldPositionY:Number = positionY; positionY += itemHeight + gap; if(positionY > scrollY && oldPositionY < maxPositionY) { result[resultLastIndex] = i; resultLastIndex++; } if(positionY >= maxPositionY) { break; } } //similar to above, in order to avoid costly destruction and //creation of item renderers, we're going to fill in some extra //indices var resultLength:int = result.length; var visibleItemCountDifference:int = visibleTypicalItemCount - resultLength; if(visibleItemCountDifference > 0 && resultLength > 0) { //add extra items before the first index var firstExistingIndex:int = result[0]; var lastIndexToAdd:int = firstExistingIndex - visibleItemCountDifference; if(lastIndexToAdd < 0) { lastIndexToAdd = 0; } for(i = firstExistingIndex - 1; i >= lastIndexToAdd; i--) { result.unshift(i); } } resultLength = result.length; visibleItemCountDifference = visibleTypicalItemCount - resultLength; resultLastIndex = resultLength; if(visibleItemCountDifference > 0) { //add extra items after the last index var startIndex:int = (resultLength > 0) ? (result[resultLength - 1] + 1) : 0; var endIndex:int = startIndex + visibleItemCountDifference; if(endIndex > itemCount) { endIndex = itemCount; } for(i = startIndex; i < endIndex; i++) { result[resultLastIndex] = i; resultLastIndex++; } } return result; } /** * @inheritDoc */ public function getScrollPositionForIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { if(!result) { result = new Point(); } if(this._useVirtualLayout) { this.prepareTypicalItem(width - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var positionY:Number = y + this._paddingTop; var lastHeight:Number = 0; var gap:Number = this._gap; var startIndexOffset:int = 0; var endIndexOffset:Number = 0; var itemCount:int = items.length; var totalItemCount:int = itemCount; if(this._useVirtualLayout && !this._hasVariableItemDimensions) { totalItemCount += this._beforeVirtualizedItemCount + this._afterVirtualizedItemCount; if(index < this._beforeVirtualizedItemCount) { //this makes it skip the loop below startIndexOffset = index + 1; lastHeight = calculatedTypicalItemHeight; gap = this._gap; } else { startIndexOffset = this._beforeVirtualizedItemCount; endIndexOffset = index - items.length - this._beforeVirtualizedItemCount + 1; if(endIndexOffset < 0) { endIndexOffset = 0; } positionY += (endIndexOffset * (calculatedTypicalItemHeight + this._gap)); } positionY += (startIndexOffset * (calculatedTypicalItemHeight + this._gap)); } index -= (startIndexOffset + endIndexOffset); var secondToLastIndex:int = totalItemCount - 2; for(var i:int = 0; i <= index; i++) { var item:DisplayObject = items[i]; var iNormalized:int = i + startIndexOffset; if(hasFirstGap && iNormalized == 0) { gap = this._firstGap; } else if(hasLastGap && iNormalized > 0 && iNormalized == secondToLastIndex) { gap = this._lastGap; } else { gap = this._gap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedHeight:Number = this._heightCache[iNormalized]; } if(this._useVirtualLayout && !item) { if(!this._hasVariableItemDimensions || cachedHeight != cachedHeight) //isNaN { lastHeight = calculatedTypicalItemHeight; } else { lastHeight = cachedHeight; } } else { var itemHeight:Number = item.height; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(itemHeight != cachedHeight) { this._heightCache[iNormalized] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } lastHeight = itemHeight; } positionY += lastHeight + gap; } positionY -= (lastHeight + gap); if(this._scrollPositionVerticalAlign == VERTICAL_ALIGN_MIDDLE) { positionY -= (height - lastHeight) / 2; } else if(this._scrollPositionVerticalAlign == VERTICAL_ALIGN_BOTTOM) { positionY -= (height - lastHeight); } result.x = 0; result.y = positionY; return result; } /** * @private */ protected function validateItems(items:Vector., justifyWidth:Number, distributedHeight:Number):void { //if the alignment is justified, then we want to set the width of //each item before validating because setting one dimension may //cause the other dimension to change, and that will invalidate the //layout if it happens after validation, causing more invalidation var mustSetJustifyWidth:Boolean = this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY && justifyWidth == justifyWidth; //!isNaN var itemCount:int = items.length; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } if(mustSetJustifyWidth) { item.width = justifyWidth; } if(this._distributeHeights) { item.height = distributedHeight; } if(item is IValidating) { IValidating(item).validate() } } } /** * @private */ protected function prepareTypicalItem(justifyWidth:Number):void { if(!this._typicalItem) { return; } if(this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY && justifyWidth == justifyWidth) //!isNaN { this._typicalItem.width = justifyWidth; } else if(this._resetTypicalItemDimensionsOnMeasure) { this._typicalItem.width = this._typicalItemWidth; } if(this._resetTypicalItemDimensionsOnMeasure) { this._typicalItem.height = this._typicalItemHeight; } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } } /** * @private */ protected function calculateDistributedHeight(items:Vector., explicitHeight:Number, minHeight:Number, maxHeight:Number):Number { var itemCount:int = items.length; if(explicitHeight != explicitHeight) //isNaN { var maxItemHeight:Number = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; var itemHeight:Number = item.height; if(itemHeight > maxItemHeight) { maxItemHeight = itemHeight; } } explicitHeight = maxItemHeight * itemCount + this._paddingTop + this._paddingBottom + this._gap * (itemCount - 1); var needsRecalculation:Boolean = false; if(explicitHeight > maxHeight) { explicitHeight = maxHeight; needsRecalculation = true; } else if(explicitHeight < minHeight) { explicitHeight = minHeight; needsRecalculation = true; } if(!needsRecalculation) { return maxItemHeight; } } var availableSpace:Number = explicitHeight - this._paddingTop - this._paddingBottom - this._gap * (itemCount - 1); if(itemCount > 1 && this._firstGap == this._firstGap) //!isNaN { availableSpace += this._gap - this._firstGap; } if(itemCount > 2 && this._lastGap == this._lastGap) //!isNaN { availableSpace += this._gap - this._lastGap; } return availableSpace / itemCount; } /** * @private */ protected function applyPercentHeights(items:Vector., explicitHeight:Number, minHeight:Number, maxHeight:Number):void { var remainingHeight:Number = explicitHeight; this._discoveredItemsCache.length = 0; var totalExplicitHeight:Number = 0; var totalMinHeight:Number = 0; var totalPercentHeight:Number = 0; var itemCount:int = items.length; var pushIndex:int = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject) { var layoutItem:ILayoutDisplayObject = ILayoutDisplayObject(item); if(!layoutItem.includeInLayout) { continue; } var layoutData:VerticalLayoutData = layoutItem.layoutData as VerticalLayoutData; if(layoutData) { var percentHeight:Number = layoutData.percentHeight; if(percentHeight === percentHeight) //!isNaN { if(layoutItem is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(layoutItem); totalMinHeight += feathersItem.minHeight; } totalPercentHeight += percentHeight; this._discoveredItemsCache[pushIndex] = item; pushIndex++; continue; } } } totalExplicitHeight += item.height; } totalExplicitHeight += this._gap * (itemCount - 1); if(this._firstGap === this._firstGap && itemCount > 1) { totalExplicitHeight += (this._firstGap - this._gap); } else if(this._lastGap === this._lastGap && itemCount > 2) { totalExplicitHeight += (this._lastGap - this._gap); } totalExplicitHeight += this._paddingTop + this._paddingBottom; if(totalPercentHeight < 100) { totalPercentHeight = 100; } if(remainingHeight != remainingHeight) //isNaN { remainingHeight = totalExplicitHeight + totalMinHeight; if(remainingHeight < minHeight) { remainingHeight = minHeight; } else if(remainingHeight > maxHeight) { remainingHeight = maxHeight; } } remainingHeight -= totalExplicitHeight; if(remainingHeight < 0) { remainingHeight = 0; } do { var needsAnotherPass:Boolean = false; var percentToPixels:Number = remainingHeight / totalPercentHeight; for(i = 0; i < pushIndex; i++) { layoutItem = ILayoutDisplayObject(this._discoveredItemsCache[i]); if(!layoutItem) { continue; } layoutData = VerticalLayoutData(layoutItem.layoutData); percentHeight = layoutData.percentHeight; var itemHeight:Number = percentToPixels * percentHeight; if(layoutItem is IFeathersControl) { feathersItem = IFeathersControl(layoutItem); var itemMinHeight:Number = feathersItem.minHeight; if(itemHeight < itemMinHeight) { itemHeight = itemMinHeight; remainingHeight -= itemHeight; totalPercentHeight -= percentHeight; this._discoveredItemsCache[i] = null; needsAnotherPass = true; } else { var itemMaxHeight:Number = feathersItem.maxHeight; if(itemHeight > itemMaxHeight) { itemHeight = itemMaxHeight; remainingHeight -= itemHeight; totalPercentHeight -= percentHeight; this._discoveredItemsCache[i] = null; needsAnotherPass = true; } } } layoutItem.height = itemHeight; } } while(needsAnotherPass) this._discoveredItemsCache.length = 0; } } } ",12263,False,2329.380298910878,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls.scrollClasses { import flash.display.DisplayObject; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Point; import flash.ui.Keyboard; import flash.utils.Timer; import mx.controls.Button; import mx.core.UIComponent; import mx.core.mx_internal; import mx.events.FlexEvent; import mx.events.SandboxMouseEvent; import mx.events.ScrollEvent; import mx.events.ScrollEventDetail; import mx.managers.ISystemManager; import mx.styles.ISimpleStyleClient; import mx.styles.StyleProxy; use namespace mx_internal; //-------------------------------------- // Styles //-------------------------------------- include ""../../styles/metadata/SkinStyles.as"" /** * Name of the class to use as the default skin for the down arrow button of * the scroll bar. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarDownButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""downArrowSkin"", type=""Class"", inherit=""no"", states=""up, over, down, disabled"")] /** * Name of the class to use as the skin for the down arrow button of the * scroll bar when it is disabled. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarDownButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""downArrowDisabledSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the down arrow button of the * scroll bar when you click the arrow button * . *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarDownButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""downArrowDownSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the down arrow button of the * scroll bar when the mouse pointer is over the arrow button. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarDownButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""downArrowOverSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the down arrow button of * the scroll bar. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarDownButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""downArrowUpSkin"", type=""Class"", inherit=""no"")] /** * Color of any symbol of a component. Examples include the check mark of a CheckBox or * the arrow of a ScrollBar button. * * @default 0x000000 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [Style(name=""symbolColor"", type=""uint"", format=""Color"", inherit=""yes"", theme=""spark"")] /** * Name of the class to use as the default skin for the down arrow button of * the scroll bar. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollThumbSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarThumbSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""thumbSkin"", type=""Class"", inherit=""no"", states=""up, over, down"")] /** * Name of the class to use as the skin for the thumb of the scroll bar * when you click the thumb. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollThumbSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarThumbSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""thumbDownSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the icon for the thumb of the scroll bar. * * @default ""undefined"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""thumbIcon"", type=""Class"", inherit=""no"")] /** * The number of pixels to offset the scroll thumb from the center of the scroll bar. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""thumbOffset"", type=""Number"", inherit=""no"")] /** * Name of the class to use as the skin for the thumb of the scroll bar * when the mouse pointer is over the thumb. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollThumbSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarThumbSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""thumbOverSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the thumb of the scroll bar. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollThumbSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarThumbSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""thumbUpSkin"", type=""Class"", inherit=""no"")] /** * The colors of the track, as an array of two colors. * You can use the same color twice for a solid track color. * * @default [0x94999b, 0xe7e7e7] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""trackColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""no"", theme=""halo"")] /** * Name of the class to use as the default skin for the track of the scroll bar. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollTrackSkin. For the Spark theme, the default skin * class is mx.skins.spark.ScrollBarTrackSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""trackSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the track of the scroll bar * when the scroll bar is disabled. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""trackDisabledSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the track of the scroll bar * when you click on the track. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""trackDownSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the track of the scroll bar * when the mouse pointer is over the scroll bar. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""trackOverSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the track of the scroll bar. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""trackUpSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the default skin for the up arrow button of the scroll bar. * *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.mx.skins.spark.ScrollBarUpButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""upArrowSkin"", type=""Class"", inherit=""no"", states=""up, over, down, disabled"")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar * when it is disabled. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.mx.skins.spark.ScrollBarUpButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""upArrowDisabledSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar * when you click the arrow button. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.mx.skins.spark.ScrollBarUpButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""upArrowDownSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar * when the mouse pointer is over the arrow button. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.mx.skins.spark.ScrollBarUpButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""upArrowOverSkin"", type=""Class"", inherit=""no"")] /** * Name of the class to use as the skin for the up arrow button of the * scroll bar. * *

If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height * (for horizontal ScrollBars) or width (for vertical ScrollBars) as the track.

* *

The default skin class is based on the theme. For example, with the Halo theme, * the default skin class is mx.skins.halo.ScrollArrowSkin. For the Spark theme, the default skin * class is mx.skins.spark.mx.skins.spark.ScrollBarUpButtonSkin.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""upArrowUpSkin"", type=""Class"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""doubleClickEnabled"", kind=""property"")] [Exclude(name=""errorColor"", kind=""style"")] [Exclude(name=""focusBlendMode"", kind=""style"")] [Exclude(name=""focusSkin"", kind=""style"")] [Exclude(name=""focusThickness"", kind=""style"")] /** * The ScrollBar class is the base class for the HScrollBar and VScrollBar * controls. * A ScrollBar consists of two arrow buttons, a track between them, * and a variable-size scroll thumb. The scroll thumb can move by * clicking on either of the two arrow buttons, dragging the scroll thumb * along the track, or clicking on the track. * *

The width of a scroll bar is equal to the largest width of its subcomponents * (up arrow, down arrow, thumb, and track). * Every subcomponent is centered in the scroll bar.

* * @mxml * *

The <mx:ScrollBar> tag inherits all of the tag attributes * of its superclass, and adds the following tag attributes:

* *
 *  <mx:ScrollBar
 *    Properties
 *    direction=""vertical|horizontal""
 *    lineScrollSize=""1""
 *    maxScrollPosition=""0""
 *    minScrollPosition=""0""
 *    pageScrollSize=""Reset to the pageSize parameter of setScrollProperties""
 *    pageSize=""0""
 *    scrollPosition=""0""
 * 
 *    Styles
 *    borderColor=""0xB7BABC"" 
 *    cornerRadius=""0"" 
 *    disabledIconColor=""0x999999""
 *    downArrowDisabledSkin=""mx.skins.halo.ScrollArrowSkin""
 *    downArrowDownSkin=""mx.skins.halo.ScrollArrowSkin""
 *    downArrowOverSkin=""mx.skins.halo.ScrollArrowSkin""
 *    downArrowUpSkin=""mx.skins.halo.ScrollArrowSkin""
 *    fillAlphas=""[0.6, 0.4]"" 
 *    fillColors=""[0xFFFFFF, 0xCCCCCC]"" 
 *    highlightAlphas=""[0.3, 0.0]"" 
 *    iconColor=""0x111111""
 *    thumbDownSkin=""mx.skins.halo.ScrollThumbSkin""
 *    thumbIcon=""undefined""
 *    thumbOffset=""0""
 *    thumbOverSkin=""mx.skins.halo.ScrollThumbSkin""
 *    thumbUpSkin=""mx.skins.halo.ScrollThumbSkin""
 *    trackColors=""[0x94999b, 0xe7e7e7]""
 *    trackSkin=""mx.skins.halo.ScrollTrackSkin""
 *    upArrowDisabledSkin=""mx.skins.halo.ScrollArrowSkin""
 *    upArrowDownSkin=""mx.skins.halo.ScrollArrowSkin""
 *    upArrowOverSkin=""mx.skins.halo.ScrollArrowSkin""
 *    upArrowUpSkin=""mx.skins.halo.ScrollArrowSkin""
 *  />
 *  
* * @see mx.controls.HScrollBar * @see mx.controls.VScrollBar * @see mx.controls.Button * @see mx.controls.scrollClasses.ScrollThumb * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class ScrollBar extends UIComponent { include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The width of a vertical scrollbar, or the height of a horizontal * scrollbar, in pixels. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const THICKNESS:Number = 16; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function ScrollBar() { super(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * The up arrow button. */ mx_internal var upArrow:Button; /** * @private * The down arrow button. */ mx_internal var downArrow:Button; /** * @private * The scroll track */ mx_internal var scrollTrack:Button; /** * @private * The scroll thumb */ mx_internal var scrollThumb:ScrollThumb; /** * @private * Used to keep track of minimums because of the orientation change. */ mx_internal var _minWidth:Number = 16; /** * @private */ mx_internal var _minHeight:Number = 32; /** * @private * true if servicing a scroll event. */ mx_internal var isScrolling:Boolean; /** * @private * Timer used to autoscroll when holding the mouse down on the track. */ private var trackScrollTimer:Timer; /** * @private * The direction we're going when in track scroll repeat. */ private var trackScrollRepeatDirection:int; /** * @private * The direction we're going when in track scroll repeat. */ private var trackScrolling:Boolean = false; /** * @private * Where the mouse is on the track. */ private var trackPosition:Number; /** * @private * Old position, used to compute deltas when button presses are auto * repeated */ mx_internal var oldPosition:Number; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // doubleClickEnabled //---------------------------------- /** * @private * Scrollbars cannot be doubleClickEnabled. * It messes up fast clicking on its buttons. */ override public function set doubleClickEnabled(value:Boolean):void { } //---------------------------------- // enabled //---------------------------------- /** * @private * Turn off buttons, or turn on buttons and resync thumb. */ override public function set enabled(value:Boolean):void { super.enabled = value; invalidateDisplayList(); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private * Storage for the direction property. */ private var _direction:String = ScrollBarDirection.VERTICAL; [Bindable(""directionChanged"")] [Inspectable(category=""General"", enumeration=""vertical,horizontal"", defaultValue=""vertical"")] /** * Specifies whether the ScrollBar is for horizontal or vertical scrolling. * Valid values in MXML are ""vertical"" and ""horizontal"". * *

In ActionScript, you use the following constants * to set this property: * ScrollBarDirection.VERTICAL and * ScrollBarDirection.HORIZONTAL.

* * @default ScrollBarDirection.VERTICAL * * @see mx.controls.scrollClasses.ScrollBarDirection * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get direction():String { return _direction; } /** * @private */ public function set direction(value:String):void { _direction = value; invalidateSize(); invalidateDisplayList(); dispatchEvent(new Event(""directionChanged"")); } //---------------------------------- // downArrowStyleFilters //---------------------------------- /** * Set of styles to pass from the ScrollBar to the down arrow. * @see mx.styles.StyleProxy * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get downArrowStyleFilters():Object { return null; } //---------------------------------- // lineMinusDetail //---------------------------------- /** * @private * String used to set the detail property of a ScrollEvent. */ mx_internal function get lineMinusDetail():String { return direction == ScrollBarDirection.VERTICAL ? ScrollEventDetail.LINE_UP : ScrollEventDetail.LINE_LEFT; } //---------------------------------- // linePlusDetail //---------------------------------- /** * @private * String used to set the detail property of a ScrollEvent. */ mx_internal function get linePlusDetail():String { return direction == ScrollBarDirection.VERTICAL ? ScrollEventDetail.LINE_DOWN : ScrollEventDetail.LINE_RIGHT; } //---------------------------------- // lineScrollSize //---------------------------------- /** * @private * Storage for the lineScrollSize property. */ private var _lineScrollSize:Number = 1; [Inspectable(category=""Other"", defaultValue=""1"")] /** * Amount to scroll when an arrow button is pressed, in pixels. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get lineScrollSize():Number { return _lineScrollSize; } /** * @private */ public function set lineScrollSize(value:Number):void { _lineScrollSize = value; } //---------------------------------- // maxDetail //---------------------------------- /** * @private * String used to set the detail property of a ScrollEvent. */ private function get maxDetail():String { return direction == ScrollBarDirection.VERTICAL ? ScrollEventDetail.AT_BOTTOM : ScrollEventDetail.AT_RIGHT; } //---------------------------------- // maxScrollPosition //---------------------------------- /** * @private * Storage for the maxScrollPosition property. */ private var _maxScrollPosition:Number = 0; [Inspectable(category=""Other"", defaultValue=""0"")] /** * Number which represents the maximum scroll position. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get maxScrollPosition():Number { return _maxScrollPosition; } /** * @private */ public function set maxScrollPosition(value:Number):void { _maxScrollPosition = value; invalidateDisplayList(); } //---------------------------------- // minDetail //---------------------------------- /** * @private * String used to set the detail property of a ScrollEvent. */ private function get minDetail():String { return direction == ScrollBarDirection.VERTICAL ? ScrollEventDetail.AT_TOP : ScrollEventDetail.AT_LEFT; } //---------------------------------- // minScrollPosition //---------------------------------- /** * @private * Storage for the minScrollPosition property. */ private var _minScrollPosition:Number = 0; [Inspectable(category=""Other"", defaultValue=""0"")] /** * Number that represents the minimum scroll position. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get minScrollPosition():Number { return _minScrollPosition; } /** * @private */ public function set minScrollPosition(value:Number):void { _minScrollPosition = value; invalidateDisplayList(); } //---------------------------------- // pageMinusDetail //---------------------------------- /** * @private * String used to set the detail property of a ScrollEvent. */ mx_internal function get pageMinusDetail():String { return direction == ScrollBarDirection.VERTICAL ? ScrollEventDetail.PAGE_UP : ScrollEventDetail.PAGE_LEFT; } //---------------------------------- // pagePlusDetail //---------------------------------- /** * @private * String used to set the detail property of a ScrollEvent. * Can be ScrollEventDetail.PAGE_RIGHT or * ScrollEventDetail.PAGE_DOWN. */ mx_internal function get pagePlusDetail():String { return direction == ScrollBarDirection.VERTICAL ? ScrollEventDetail.PAGE_DOWN : ScrollEventDetail.PAGE_RIGHT; } //---------------------------------- // pageSize //---------------------------------- /** * @private * Storage for the pageSize property. */ private var _pageSize:Number = 0; [Inspectable(category=""Other"", defaultValue=""0"")] /** * The number of lines equivalent to one page. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get pageSize():Number { return _pageSize; } /** * @private */ public function set pageSize(value:Number):void { _pageSize = value; } //---------------------------------- // pageScrollSize //---------------------------------- /** * @private * Storage for the pageScrollSize property.l */ private var _pageScrollSize:Number = 0; [Inspectable(category=""Other"", defaultValue=""0"")] /** * Amount to move the scroll thumb when the scroll bar * track is pressed, in pixels. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get pageScrollSize():Number { return _pageScrollSize; } /** * @private */ public function set pageScrollSize(value:Number):void { _pageScrollSize = value; } //---------------------------------- // scrollPosition //---------------------------------- /** * @private * Storage for the scrollPosition property. */ private var _scrollPosition:Number = 0; [Inspectable(category=""Other"", defaultValue=""0"")] /** * Number that represents the current scroll position. * * The value is between minScrollPosition and * maxScrollPosition inclusively. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get scrollPosition():Number { return _scrollPosition; } /** * @private */ public function set scrollPosition(value:Number):void { _scrollPosition = value; if (scrollThumb) { // Turn on bitmap caching whenever we start scrolling. Turn it // off whenever we resize the scrollbar (because caching hurts // performance during a resize animation) if (!cacheAsBitmap) cacheHeuristic = scrollThumb.cacheHeuristic = true; if (!isScrolling) { // Update thumb. value = Math.min(value, maxScrollPosition); value = Math.max(value, minScrollPosition); var denom:Number = maxScrollPosition - minScrollPosition; var y:Number = (denom == 0 || isNaN(denom)) ? 0 : ((value - minScrollPosition) * (trackHeight - scrollThumb.height) / (denom)) + trackY; var x:Number = (virtualWidth - scrollThumb.width) / 2 + getStyle(""thumbOffset""); scrollThumb.move(Math.round(x), Math.round(y)); } } } //---------------------------------- // thumbStyleFilters //---------------------------------- /** * Set of styles to pass from the ScrollBar to the thumb. * @see mx.styles.StyleProxy * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get thumbStyleFilters():Object { return null; } //---------------------------------- // trackHeight //---------------------------------- /** * @private */ private function get trackHeight():Number { return virtualHeight - (upArrow.getExplicitOrMeasuredHeight() + downArrow.getExplicitOrMeasuredHeight()); } //---------------------------------- // trackY //---------------------------------- /** * @private */ private function get trackY():Number { return upArrow.getExplicitOrMeasuredHeight(); } //---------------------------------- // upArrowStyleFilters //---------------------------------- /** * Set of styles to pass from the ScrollBar to the up arrow. * @see mx.styles.StyleProxy * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get upArrowStyleFilters():Object { return null; } //---------------------------------- // virtualHeight //---------------------------------- /** * @private * For internal use only. * Used by horizontal bar to deal with rotation. */ mx_internal function get virtualHeight():Number { return unscaledHeight; } //---------------------------------- // virtualWidth //---------------------------------- /** * @private * For internal use only. * Used by horizontal bar to deal with rotation. */ mx_internal function get virtualWidth():Number { return unscaledWidth; } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private * Create child objects. */ override protected function createChildren():void { super.createChildren(); // Create the scroll track. if (!scrollTrack) { scrollTrack = new Button(); scrollTrack.focusEnabled = false; scrollTrack.tabEnabled = false; scrollTrack.skinName = ""trackSkin""; scrollTrack.upSkinName = ""trackUpSkin""; scrollTrack.overSkinName = ""trackOverSkin""; scrollTrack.downSkinName = ""trackDownSkin""; scrollTrack.disabledSkinName = ""trackDisabledSkin""; if (scrollTrack is ISimpleStyleClient) ISimpleStyleClient(scrollTrack).styleName = this; addChild(scrollTrack); scrollTrack.validateProperties(); } // Create the up-arrow button, layered above the track. if (!upArrow) { upArrow = new Button(); // It will get enabled later in setScrollProperties(). upArrow.enabled = false; // Holding it down will cause continuous scrolling. upArrow.autoRepeat = true; upArrow.focusEnabled = false; upArrow.tabEnabled = false; // This button is a 4-state Button // that by default uses the ScrollArrowSkin. upArrow.upSkinName = ""upArrowUpSkin""; upArrow.overSkinName = ""upArrowOverSkin""; upArrow.downSkinName = ""upArrowDownSkin""; upArrow.disabledSkinName = ""upArrowDisabledSkin""; upArrow.skinName = ""upArrowSkin""; upArrow.upIconName = """"; upArrow.overIconName = """"; upArrow.downIconName = """"; upArrow.disabledIconName = """"; addChild(upArrow); upArrow.styleName = new StyleProxy(this, upArrowStyleFilters); upArrow.validateProperties(); upArrow.addEventListener(FlexEvent.BUTTON_DOWN, upArrow_buttonDownHandler); } // Create the down-arrow button, layered above the track. if (!downArrow) { downArrow = new Button(); // It will get enabled later in setScrollProperties(). downArrow.enabled = false; // Holding it down will cause continuous scrolling. downArrow.autoRepeat = true; downArrow.focusEnabled = false; downArrow.tabEnabled = false; // This button is a 4-state Button // that by default uses the ScrollArrowSkin. downArrow.upSkinName = ""downArrowUpSkin""; downArrow.overSkinName = ""downArrowOverSkin""; downArrow.downSkinName = ""downArrowDownSkin""; downArrow.disabledSkinName = ""downArrowDisabledSkin""; downArrow.skinName = ""downArrowSkin""; downArrow.upIconName = """"; downArrow.overIconName = """"; downArrow.downIconName = """"; downArrow.disabledIconName = """"; addChild(downArrow); downArrow.styleName = new StyleProxy(this, downArrowStyleFilters); downArrow.validateProperties(); downArrow.addEventListener(FlexEvent.BUTTON_DOWN, downArrow_buttonDownHandler); } } /** * @private * Determine our min width/height based on the up and down * arrow sizes. */ override protected function measure():void { super.measure(); //make sure arrows have required values upArrow.validateSize(); downArrow.validateSize(); scrollTrack.validateSize(); _minWidth = scrollThumb ? scrollThumb.getExplicitOrMeasuredWidth() : 0; _minWidth = Math.max(scrollTrack.getExplicitOrMeasuredWidth(), upArrow.getExplicitOrMeasuredWidth(), downArrow.getExplicitOrMeasuredWidth(), _minWidth); _minHeight = upArrow.getExplicitOrMeasuredHeight() + downArrow.getExplicitOrMeasuredHeight(); } /** * @private * Size changed so re-position everything. */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { if ($height == 1) return; if (!upArrow) return; super.updateDisplayList(unscaledWidth, unscaledHeight); // Turn on bitmap caching whenever we start scrolling. Turn it // off whenever we resize the scrollbar (because caching hurts // performance during a resize animation) if (cacheAsBitmap) { cacheHeuristic = false; if (scrollThumb) scrollThumb.cacheHeuristic = false; } upArrow.setActualSize(upArrow.getExplicitOrMeasuredWidth(), upArrow.getExplicitOrMeasuredHeight()); upArrow.move((virtualWidth - upArrow.width) / 2, 0); scrollTrack.setActualSize(scrollTrack.getExplicitOrMeasuredWidth(), virtualHeight); scrollTrack.x = (virtualWidth - scrollTrack.width) / 2; scrollTrack.y = 0; downArrow.setActualSize(downArrow.getExplicitOrMeasuredWidth(), downArrow.getExplicitOrMeasuredHeight()); downArrow.move((virtualWidth - downArrow.width) / 2, virtualHeight - downArrow.getExplicitOrMeasuredHeight()); setScrollProperties(pageSize, minScrollPosition, maxScrollPosition, _pageScrollSize); // Reset thumb position. scrollPosition = _scrollPosition; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Sets the range and viewport size of the ScrollBar control. * * The ScrollBar control updates the state of the arrow buttons and * size of the scroll thumb accordingly. * * @param pageSize Number which represents the size of one page. * * @param minScrollPosition Number which represents the bottom of the * scrolling range. * * @param maxScrollPosition Number which represents the top of the * scrolling range. * * @param pageScrollSize Number which represents the increment to move when * the scroll track is pressed. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function setScrollProperties(pageSize:Number, minScrollPosition:Number, maxScrollPosition:Number, pageScrollSize:Number = 0):void { var thumbHeight:Number; this.pageSize = pageSize; _pageScrollSize = (pageScrollSize > 0) ? pageScrollSize : pageSize; this.minScrollPosition = Math.max(minScrollPosition, 0); this.maxScrollPosition = Math.max(maxScrollPosition, 0); _scrollPosition = Math.max(this.minScrollPosition, _scrollPosition); _scrollPosition = Math.min(this.maxScrollPosition, _scrollPosition); // If the ScrollBar is enabled and has a nonzero range ... if (this.maxScrollPosition - this.minScrollPosition > 0 && enabled) { upArrow.enabled = true; downArrow.enabled = true; scrollTrack.enabled = true; addEventListener(MouseEvent.MOUSE_DOWN, scrollTrack_mouseDownHandler); addEventListener(MouseEvent.MOUSE_OVER, scrollTrack_mouseOverHandler); addEventListener(MouseEvent.MOUSE_OUT, scrollTrack_mouseOutHandler); if (!scrollThumb) { scrollThumb = new ScrollThumb(); scrollThumb.focusEnabled = false; scrollThumb.tabEnabled = false; // Add the thumb above the up arrow but below the down arrow addChildAt(scrollThumb, getChildIndex(downArrow)); scrollThumb.styleName = new StyleProxy(this, thumbStyleFilters); // This button is a 4-state Button // that by default uses the ScrollThumbSkin. scrollThumb.upSkinName = ""thumbUpSkin""; scrollThumb.overSkinName = ""thumbOverSkin""; scrollThumb.downSkinName = ""thumbDownSkin""; scrollThumb.iconName = ""thumbIcon""; scrollThumb.skinName = ""thumbSkin""; } thumbHeight = trackHeight < 0 ? 0 : Math.round( pageSize / (this.maxScrollPosition - this.minScrollPosition + pageSize) * trackHeight); if (thumbHeight < scrollThumb.minHeight) { if (trackHeight < scrollThumb.minHeight) { scrollThumb.visible = false; } else { thumbHeight = scrollThumb.minHeight; scrollThumb.visible = true; scrollThumb.setActualSize(scrollThumb.measuredWidth, scrollThumb.minHeight); } } else { scrollThumb.visible = true; scrollThumb.setActualSize(scrollThumb.measuredWidth, thumbHeight); } scrollThumb.setRange(upArrow.getExplicitOrMeasuredHeight() + 0, virtualHeight - downArrow.getExplicitOrMeasuredHeight() - scrollThumb.height, this.minScrollPosition, this.maxScrollPosition); scrollPosition = Math.max(Math.min(scrollPosition, this.maxScrollPosition), this.minScrollPosition); } else { upArrow.enabled = false; downArrow.enabled = false; scrollTrack.enabled = false; if (scrollThumb) scrollThumb.visible = false; } } /** * @private */ mx_internal function lineScroll(direction:int):void { var delta:Number = _lineScrollSize; var newPos:Number = _scrollPosition + direction * delta; if (newPos > maxScrollPosition) newPos = maxScrollPosition; else if (newPos < minScrollPosition) newPos = minScrollPosition; if (newPos != scrollPosition) { var oldPosition:Number = scrollPosition; scrollPosition = newPos; var detail:String = direction < 0 ? lineMinusDetail : linePlusDetail; dispatchScrollEvent(oldPosition, detail); } } /** * @private */ mx_internal function pageScroll(direction:int):void { var delta:Number = _pageScrollSize != 0 ? _pageScrollSize : pageSize; var newPos:Number = _scrollPosition + direction * delta; if (newPos > maxScrollPosition) newPos = maxScrollPosition; else if (newPos < minScrollPosition) newPos = minScrollPosition; if (newPos != scrollPosition) { var oldPosition:Number = scrollPosition; scrollPosition = newPos; var detail:String = direction < 0 ? pageMinusDetail : pagePlusDetail; dispatchScrollEvent(oldPosition, detail); } } /** * @private * Dispatch a scroll event. */ mx_internal function dispatchScrollEvent(oldPosition:Number, detail:String):void { var event:ScrollEvent = new ScrollEvent(ScrollEvent.SCROLL); event.detail = detail; event.position = scrollPosition; event.delta = scrollPosition - oldPosition; event.direction = direction; dispatchEvent(event); } /** * @private * Returns true if it is a scrollbar key. * It will execute the equivalent code for that key as well. */ mx_internal function isScrollBarKey(key:uint):Boolean { var oldPosition:Number; if (key == Keyboard.HOME) { if (scrollPosition != 0) { oldPosition = scrollPosition; scrollPosition = 0; dispatchScrollEvent(oldPosition, minDetail); } return true; } else if (key == Keyboard.END) { if (scrollPosition < maxScrollPosition) { oldPosition = scrollPosition; scrollPosition = maxScrollPosition; dispatchScrollEvent(oldPosition, maxDetail); } return true; } return false; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * Callback when the up-arrow button is pressed or autorepeated. */ private function upArrow_buttonDownHandler(event:FlexEvent):void { if (isNaN(oldPosition)) oldPosition = scrollPosition; lineScroll(-1); } /** * @private * Callback when the down-arrow button is pressed or autorepeated. */ private function downArrow_buttonDownHandler(event:FlexEvent):void { if (isNaN(oldPosition)) oldPosition = scrollPosition; lineScroll(1); } /** * @private * Show the over skin of the scrollTrack if there is one. */ private function scrollTrack_mouseOverHandler(event:MouseEvent):void { if (!(event.target == this || event.target == scrollTrack) || !enabled) return; if (trackScrolling) trackScrollTimer.start(); } /** * @private * Hide the over skin of the scrollTrack. */ private function scrollTrack_mouseOutHandler(event:MouseEvent):void { if (trackScrolling && enabled) trackScrollTimer.stop(); } /** * @private * Set up the repeating events when pressing on the track. */ private function scrollTrack_mouseDownHandler(event:MouseEvent):void { if (!(event.target == this || event.target == scrollTrack) || !enabled) return; trackScrolling = true; var sbRoot:DisplayObject = systemManager.getSandboxRoot(); sbRoot.addEventListener( MouseEvent.MOUSE_UP, scrollTrack_mouseUpHandler, true); sbRoot.addEventListener( MouseEvent.MOUSE_MOVE, scrollTrack_mouseMoveHandler, true); // in case we go offscreen sbRoot.addEventListener( SandboxMouseEvent.MOUSE_UP_SOMEWHERE, scrollTrack_mouseLeaveHandler); systemManager.deployMouseShields(true); var pt:Point = new Point(event.localX, event.localY); pt = event.target.localToGlobal(pt); pt = globalToLocal(pt); trackPosition = pt.y; if (isNaN(oldPosition)) oldPosition = scrollPosition; trackScrollRepeatDirection = scrollThumb.y + scrollThumb.height < pt.y ? 1 : scrollThumb.y > pt.y ? -1 : 0; pageScroll(trackScrollRepeatDirection); if (!trackScrollTimer) { trackScrollTimer = new Timer(getStyle(""repeatDelay""), 1); trackScrollTimer.addEventListener(TimerEvent.TIMER, trackScrollTimerHandler); } else { trackScrollTimer.delay = getStyle(""repeatDelay""); trackScrollTimer.repeatCount = 1; } trackScrollTimer.start(); } /** * @private * This gets called at certain intervals * to repeat the scroll event when pressing the track. */ private function trackScrollTimerHandler(event:Event):void { if (trackScrollRepeatDirection == 1) if (scrollThumb.y + scrollThumb.height > trackPosition) return; if (trackScrollRepeatDirection == -1) if (scrollThumb.y < trackPosition) return; pageScroll(trackScrollRepeatDirection); if (trackScrollTimer && trackScrollTimer.repeatCount == 1) { trackScrollTimer.delay = getStyle(""repeatInterval""); trackScrollTimer.repeatCount = 0; } } /** * @private * Stop repeating events because the track is no longer pressed * special case to restore focus when we've released the mouse */ private function scrollTrack_mouseUpHandler(event:MouseEvent):void { scrollTrack_mouseLeaveHandler(event); } private function scrollTrack_mouseLeaveHandler(event:Event):void { trackScrolling = false; var sbRoot:DisplayObject = systemManager.getSandboxRoot(); sbRoot.removeEventListener( MouseEvent.MOUSE_UP, scrollTrack_mouseUpHandler, true); sbRoot.removeEventListener( MouseEvent.MOUSE_MOVE, scrollTrack_mouseMoveHandler, true); // in case we go offscreen sbRoot.removeEventListener( SandboxMouseEvent.MOUSE_UP_SOMEWHERE, scrollTrack_mouseLeaveHandler); systemManager.deployMouseShields(false); if (trackScrollTimer) trackScrollTimer.reset(); if (event.target != scrollTrack) return; var detail:String = oldPosition > scrollPosition ? pageMinusDetail : pagePlusDetail; dispatchScrollEvent(oldPosition, detail); oldPosition = NaN; } /** * @private * Stop repeating events because the track is no longer pressed * special case to restore focus when we've released the mouse */ private function scrollTrack_mouseMoveHandler(event:MouseEvent):void { if (trackScrolling) { var pt:Point = new Point(event.stageX, event.stageY); pt = globalToLocal(pt); trackPosition = pt.y; } } } } ",12051,False,1980.2006356416223,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ package com.hurlant.math { import com.hurlant.crypto.prng.Random; import com.hurlant.util.Hex; import com.hurlant.util.Memory; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1<0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-->0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } clamp(); value.position = Math.min(p+length,value.length); } /** * clamp off excess high words */ bi_internal function clamp():void { var c:int = s&DM; while (t>0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { return parseInt(str.charAt(index), 36); } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-->0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12125,True,2650.04861961807,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.validators.supportClasses { import flash.globalization.NationalDigitsType; import flash.globalization.NumberFormatter; import mx.core.mx_internal; import mx.validators.NumberValidatorDomainType; import mx.validators.ValidationResult; import spark.formatters.CurrencyFormatter; import spark.formatters.NumberFormatter; import spark.globalization.LastOperationStatus; import spark.globalization.supportClasses.GlobalizationBase; import spark.validators.supportClasses.GlobalizationUtils; import spark.validators.supportClasses.GlobalizationValidatorBase; use namespace mx_internal; /** * The NumberValidatorBase class contains all the common functionality that is * required by the NumberValidator and * CurrencyValidator classes. * * @mxml * *

The <s:NumberValidator> tag * inherits all of the tag attributes of its superclass, * and adds the following tag attributes:

* *
 *  <s:NumberValidatorBase
 *    Properties
 *    allowNegative=""true""
 *    decimalPointCountError=""The decimal separator can only occur once.""
 *    decimalSeparator=""locale specified string or customized by user.""
 *    digitsType=""locale specified string or customized by user.""
 *    domain=""real""
 *    fractionalDigits=""locale specified string or customized by user.""
 *    fractionalDigitsError=""The amount entered has too many digits beyond the decimal point.""
 *    greaterThanMaxError=""The number entered is too large.""
 *    groupingSeparator=""locale specified string or customized by user.""
 *    invalidCharError=""The input contains invalid characters.""
 *    invalidFormatCharsError=""One of the formatting parameters is invalid.""
 *    lessThanMinError=""The amount entered is too small.""
 *    localeUndefinedError=""Locale is undefined.""
 *    maxValue=""NaN""
 *    minValue=""NaN""
 *    negativeError=""The amount may not be negative.""
 *    negativeSymbolError=""The negative symbol is repeated or not in right place.""
 *    notAnIntegerError=""The number must be an integer.""
 *    parseError=""The input string could not be parsed.""
 *  />
 *  
* * @see spark.formatters.supportClasses.NumberFormatterBase * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class NumberValidatorBase extends GlobalizationValidatorBase { include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class Constants // //-------------------------------------------------------------------------- private static const ALLOW_NEGATIVE:String = ""allowNegative""; private static const DECIMAL_SEPARATOR:String = ""decimalSeparator""; private static const DIGITS_TYPE:String = ""digitsType""; private static const FRACTIONAL_DIGITS:String = ""fractionalDigits""; private static const GROUPING_SEPARATOR:String = ""groupingSeparator""; private static const NEGATIVE_SYMBOL:String = ""negativeSymbol""; // Used by inheritors. mx_internal static const NUMBER_VALIDATOR_TYPE:int = 1; mx_internal static const CURRENCY_VALIDATOR_TYPE:int = 2; private static const NEGATIVE_SYMBOLS:String = ""-"" + String.fromCharCode(0x2212, 0xFE63, 0xFF0D); mx_internal static const VALID_CHARS:String = DECIMAL_DIGITS + ""("" + "")"" + NEGATIVE_SYMBOLS; // Follows flash.globalization limit. private static const PATTERN_LENGTH_LIMIT:int = 10; private static const DECIMAL_SEP_STD:String = "".""; /** * @private * A String containing the decimal digits 0 through 9. * */ mx_internal static const DECIMAL_DIGITS:String = ""0123456789""; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function NumberValidatorBase() { super(); // Previously allowNegative was an object. If it was null, the default // value was loaded from resource manager in the setter. But now it // is a boolean. Hence load it explicitly. _allowNegative = allowNegativeOverride = resourceManager.getBoolean( ""validators"", ""allowNegative""); _domain = NumberValidatorDomainType.REAL; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Underlying working instance of flash.globalizaiton.NumberFormatter or * CurrencyFormatter class. * * Because it can be either type and they don't have common base except * Object, it is defined as Object. */ private var _g11nWorkingInstance:Object = null; /** * @private * If the g11nWorkingInstance has not been defined. Call * ensureStyleSource to ensure that there is a styleParent. If there is * not a style parent, then this instance will be added as a style client * to the topLevelApplication. As a side effect of this, the styleChanged * method will be called and if there is a locale style defined for the * topLevelApplication, the createWorkingInstance method will be * executed creating a g11nWorkingInstance. */ mx_internal function get g11nWorkingInstance ():Object { if (!_g11nWorkingInstance) ensureStyleSource(); return _g11nWorkingInstance; } mx_internal function set g11nWorkingInstance (sparkFormatter:Object): void { _g11nWorkingInstance = sparkFormatter; } //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- //---------------------------------- // lastOperationStatus //---------------------------------- [Bindable(""change"")] /** * @inheritDoc * * @see spark.Globalization.LastOperationStatus * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override public function get lastOperationStatus():String { return g11nWorkingInstance ? g11nWorkingInstance.lastOperationStatus : fallbackLastOperationStatus; } //---------------------------------- // useFallback //---------------------------------- [Bindable(""change"")] /** * @private */ override mx_internal function get useFallback():Boolean { return g11nWorkingInstance.useFallback; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // allowNegative //---------------------------------- /** * @private * Storage for the allowNegative property. */ private var _allowNegative:Boolean; /** * @private */ protected var allowNegativeOverride:Boolean; [Inspectable(category=""General"", defaultValue=""true"")] [Bindable(""change"")] /** * Specifies whether negative numbers are permitted. * Valid values are true or false. * * @default true * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get allowNegative():Boolean { return _allowNegative; } public function set allowNegative(value:Boolean):void { allowNegativeOverride = value; _allowNegative = value; update(); } //---------------------------------- // decimalSeparator //---------------------------------- [Bindable(""change"")] /** * The decimal separator character used for validating numbers that have * a decimal part. * *

This property is initially set based on the locale style of the * validator object.

* *

The default value is dependent on the locale and operating * system.

* * @throws TypeError if this property is assigned a null value. * * @see #validate() * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get decimalSeparator():String { return getBasicProperty(properties, DECIMAL_SEPARATOR); } public function set decimalSeparator(value:String):void { setBasicProperty(properties, DECIMAL_SEPARATOR, value); } //---------------------------------- // digitsType //---------------------------------- [Bindable(""change"")] /** * Defines the set of digit characters to be used when * validating numbers. * *

Different languages and regions use different sets of * characters to represent the * digits 0 through 9. This property defines the set of digits * to be used.

* *

The value of this property represents the Unicode value for * the zero digit of a decimal digit set. * The valid values for this property are defined in the * NationalDigitsType class.

* *

The default value is dependent on the locale and operating * system.

* * @see flash.globalization.NationalDigitsType * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get digitsType():uint { return getBasicProperty(properties, DIGITS_TYPE); } public function set digitsType(value:uint):void { setBasicProperty(properties, DIGITS_TYPE, value); } //---------------------------------- // domain //---------------------------------- /** * @private * Storage for the domain property. */ private var _domain:String; /** * @private */ protected var domainOverride:String = ""real""; [Inspectable(category=""General"", enumeration=""int,real"", defaultValue=""real"")] [Bindable(""change"")] /** * Type of number to be validated. * Permitted values are ""real"" and ""int"". * *

In ActionScript, you can use the following constants to set this * property: * NumberValidatorDomainType.REAL or * NumberValidatorDomainType.INT.

* * @default ""real"" * * @see #NumberValidatorDomainType * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get domain():String { return _domain; } /** * @private */ public function set domain(value:String):void { domainOverride = value; if (!value) { _domain = resourceManager.getString( ""validators"", ""numberValidatorDomain""); } else if ((value != NumberValidatorDomainType.INT) && (value != NumberValidatorDomainType.REAL)) { throw new ArgumentError(); } else { _domain = value; } update(); } //---------------------------------- // fractionalDigits //---------------------------------- [Bindable(""change"")] [Inspectable(category=""General"", minValue=""0"")] /** * The maximum number of digits that can appear after the decimal * separator. * *

The default value is dependent on the locale and operating * system.

* * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get fractionalDigits():int { return getBasicProperty(properties, FRACTIONAL_DIGITS); } public function set fractionalDigits(value:int):void { setBasicProperty(properties, FRACTIONAL_DIGITS, value); } //---------------------------------- // groupingSeparator //---------------------------------- [Bindable(""change"")] /** * The character or string used for the grouping separator. * *

The value of this property is used as the grouping * separator when validating numbers. This * property is initially set based on the locale that is selected * when the validator object is constructed.

* * @throws TypeError if this property is assigned a null value. * *

The default value is dependent on the locale and operating * system.

* * @see #validate() * @see #groupingPattern * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get groupingSeparator():String { return getBasicProperty(properties, GROUPING_SEPARATOR); } public function set groupingSeparator(value:String):void { setBasicProperty(properties, GROUPING_SEPARATOR, value); } //---------------------------------- // maxValue //---------------------------------- /** * @private * Storage for the maxValue property. */ private var _maxValue:Number; /** * @private */ protected var maxValueOverride:Number; [Inspectable(category=""General"", defaultValue=""null"")] [Bindable(""change"")] /** * Maximum value for a valid number. A value of NaN means there is no * maximum. * * @default NaN * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get maxValue():Number { return _maxValue; } /** * @private */ public function set maxValue(value:Number):void { maxValueOverride = value; _maxValue = value; update(); } //---------------------------------- // minValue //---------------------------------- /** * @private * Storage for the minValue property. */ private var _minValue:Number; /** * @private */ protected var minValueOverride:Number; [Inspectable(category=""General"", defaultValue=""null"")] [Bindable(""change"")] /** * Minimum value for a valid number. A value of NaN means there is no * minimum. * * @default NaN * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get minValue():Number { return _minValue; } public function set minValue(value:Number):void { minValueOverride = value; _minValue = value; update(); } //---------------------------------- // negativeSymbol //---------------------------------- [Bindable(""change"")] /** * The negative symbol to be used when validating negative values. * *

This symbol is used when validating a negative number. * This is read-only property as not all operating systems allow * customizing of this property.

* *

This property is set to a default value specified by the locale.

* * @see #negativeNumberFormat * @see #validate() * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get negativeSymbol():String { return getBasicProperty(properties, NEGATIVE_SYMBOL); } //-------------------------------------------------------------------------- // // Properties: Errors // //-------------------------------------------------------------------------- //---------------------------------- // decimalPointCountError //---------------------------------- /** * @private * Storage for the decimalPointCountError property. */ private var _decimalPointCountError:String; /** * @private */ protected var decimalPointCountErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the decimal separator character occurs more than * once. * * @default ""The decimal separator can occur only once."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get decimalPointCountError():String { return _decimalPointCountError; } public function set decimalPointCountError(value:String):void { if (decimalPointCountErrorOverride && (decimalPointCountErrorOverride == value)) return; decimalPointCountErrorOverride = value; _decimalPointCountError = value ? value : resourceManager.getString(""validators"", ""decimalPointCountError""); update(); } //---------------------------------- // fractionalDigitsError //---------------------------------- /** * @private * Storage for the fractionalDigitsError property. */ private var _fractionalDigitsError:String; /** * @private */ protected var fractionalDigitsErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when fraction digits exceeds the value specified * by the fractionalDigits property. * * @default ""The amount entered has too many digits beyond the decimal * point."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get fractionalDigitsError():String { return _fractionalDigitsError; } public function set fractionalDigitsError(value:String):void { if (fractionalDigitsErrorOverride && (fractionalDigitsErrorOverride == value)) return; fractionalDigitsErrorOverride = value; _fractionalDigitsError = value ? value : resourceManager.getString(""validators"", ""fractionalDigitsError""); update(); } //---------------------------------- // greaterThanMaxError //---------------------------------- /** * @private * Storage for the exceedsMaxError property. */ private var _greaterThanMaxError:String; /** * @private */ protected var greaterThanMaxErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value exceeds the maxValue property. * * @default ""The number entered is too large."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get greaterThanMaxError():String { return _greaterThanMaxError; } /** * @private */ public function set greaterThanMaxError(value:String):void { if (greaterThanMaxErrorOverride && (greaterThanMaxErrorOverride == value)) return; greaterThanMaxErrorOverride = value; _greaterThanMaxError = value ? value : resourceManager.getString(""validators"", ""exceedsMaxErrorNV""); update(); } //---------------------------------- // invalidCharError //---------------------------------- /** * @private * Storage for the invalidCharError property. */ private var _invalidCharError:String; /** * @private */ protected var invalidCharErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value contains invalid characters. * * @default ""The input contains invalid characters."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get invalidCharError():String { return _invalidCharError; } /** * @private */ public function set invalidCharError(value:String):void { if (invalidCharErrorOverride && (invalidCharErrorOverride == value)) return; invalidCharErrorOverride = value; _invalidCharError = value ? value : resourceManager.getString(""validators"", ""invalidCharError""); update(); } //---------------------------------- // invalidFormatCharsError //---------------------------------- /** * @private * Storage for the invalidFormatCharsError property. */ private var _invalidFormatCharsError:String; /** * @private */ protected var invalidFormatCharsErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value contains invalid format characters, which * means that it contains a digit or minus sign (-) as a separator * character, or it contains two or more consecutive separator characters. * * @default ""One of the formatting parameters is invalid."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get invalidFormatCharsError():String { return _invalidFormatCharsError; } public function set invalidFormatCharsError(value:String):void { if (invalidFormatCharsErrorOverride && (invalidFormatCharsErrorOverride == value)) return; invalidFormatCharsErrorOverride = value; _invalidFormatCharsError = value ? value : resourceManager.getString(""validators"", ""invalidFormatCharsError""); update(); } //---------------------------------- // lessThanMinError //---------------------------------- /** * @private * Storage for the lowerThanMinError property. */ private var _lessThanMinError:String; /** * @private */ protected var lessThanMinErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value is less than the minValue. * * @default ""The amount entered is too small."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get lessThanMinError():String { return _lessThanMinError; } public function set lessThanMinError(value:String):void { if (lessThanMinErrorOverride && (lessThanMinErrorOverride == value)) return; lessThanMinErrorOverride = value; _lessThanMinError = value ? value : resourceManager.getString(""validators"", ""lowerThanMinError""); update(); } //---------------------------------- // localeUndefinedError //---------------------------------- private var _localeUndefinedError:String; /** * @private */ protected var localeUndefinedErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the locale is undefined or is not available. * * @default ""Locale is undefined."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get localeUndefinedError():String { return _localeUndefinedError; } public function set localeUndefinedError(value:String):void { if (localeUndefinedErrorOverride && (localeUndefinedErrorOverride == value)) return; localeUndefinedErrorOverride = value; _localeUndefinedError = value ? value : resourceManager.getString(""validators"", ""localeUndefinedError""); update(); } //---------------------------------- // negativeError //---------------------------------- /** * @private * Storage for the negativeError property. */ private var _negativeError:String; /** * @private */ protected var negativeErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value is negative and the * allowNegative property is false. * * @default ""The amount may not be negative."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get negativeError():String { return _negativeError; } public function set negativeError(value:String):void { if (negativeErrorOverride && (negativeErrorOverride == value)) return; negativeErrorOverride = value; _negativeError = value ? value : resourceManager.getString(""validators"", ""negativeError""); update(); } //---------------------------------- // negativeSymbolError //---------------------------------- /** * @private * Storage for the negativeSymbolError property. */ private var _negativeSymbolError:String; /** * @private */ protected var negativeSymbolErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the negative symbol is repeated or is in wrong place. * * @default ""The negative symbol is repeated or not in right place."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get negativeSymbolError():String { return _negativeSymbolError; } public function set negativeSymbolError(value:String):void { if (negativeSymbolErrorOverride && (negativeSymbolErrorOverride == value)) return; negativeSymbolErrorOverride = value; _negativeSymbolError = value ? value : resourceManager.getString(""validators"", ""negativeSymbolError""); update(); } //---------------------------------- // notAnIntegerError //---------------------------------- /** * @private * Storage for the integerError property. */ private var _notAnIntegerError:String; /** * @private */ protected var notAnIntegerErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the number must be an integer, as defined * by the domain property. * * @default ""The number must be an integer."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get notAnIntegerError():String { return _notAnIntegerError; } public function set notAnIntegerError(value:String):void { if (notAnIntegerErrorOverride && (notAnIntegerErrorOverride == value)) return; notAnIntegerErrorOverride = value; _notAnIntegerError = value ? value : resourceManager.getString(""validators"", ""integerError""); update(); } //---------------------------------- // parseError //---------------------------------- private var _parseError:String; /** * @private */ protected var parseErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when number could not be parsed. * * @default ""The input string could not be parsed."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get parseError():String { return _parseError; } /** * @private */ public function set parseError(value:String):void { if (parseErrorOverride && (parseErrorOverride == value)) return; parseErrorOverride = value; _parseError = value ? value : resourceManager.getString(""validators"", ""parseError""); update(); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Create underlying formatter object for currency or number validator. * This method has the common code that is needed by both currency and * number validator object's createWorkingInstance(). * *

Create locale specific formatter object using localeStyle property. * If localeStyle is null, this method sets fallbackLastOperationStatus to * LOCALE_UNDEFINED_ERROR and returns. * If localeStyle is specified and fallback is enforced, then fallback * formatter object is created using ""en-US"" locale. Otherwise creates * the flash.globalization formatter. The formatter properties are updated * with the user overriden values.

* * @param validatorType An integer specifying currency or number validator. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 * */ mx_internal function createWorkingInstanceCore(validatorType:int):void { if (validatorType == NUMBER_VALIDATOR_TYPE) g11nWorkingInstance = new spark.formatters.NumberFormatter(); else if (validatorType == CURRENCY_VALIDATOR_TYPE) g11nWorkingInstance = new spark.formatters.CurrencyFormatter(); if (!g11nWorkingInstance) { throw new Error(""Internal failure: "" + ""spark formatter creation failure.""); } g11nWorkingInstance.enforceFallback = enforceFallback; g11nWorkingInstance.setStyle(""locale"", localeStyle); if (g11nWorkingInstance.lastOperationStatus != LastOperationStatus.UNSUPPORTED_ERROR) { properties = g11nWorkingInstance propagateBasicProperties(g11nWorkingInstance); return; } } /** * @private * Return the actual locale id name. * *

This method gets the actual locale id name from the internal * formatter object. If the formatter object is not available, returns * ""en-US"" as the ultimate fallback locale id name.

* * @param validatorType int having the validator type: currency or number * @returns String Actual locale id name * */ mx_internal function getActualLocaleIDName(validatorType:int):String { if (g11nWorkingInstance) { return (validatorType == NUMBER_VALIDATOR_TYPE) ? (g11nWorkingInstance as spark.formatters.NumberFormatter).actualLocaleIDName : (g11nWorkingInstance as spark.formatters.CurrencyFormatter).actualLocaleIDName; } // Flex binding allows a situation of getting actual locale id name // even before createWorkingInstance() is called. else { fallbackLastOperationStatus = LastOperationStatus.LOCALE_UNDEFINED_ERROR; return undefined; } } /** * @private * get the index of first digit. */ mx_internal function indexOfFirstDigit(input:String, len:int, start:int=0):int { if (!input || !len) return -1; for (var i:int = start; i < len; i++) { var c0:int = input.charCodeAt(i); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) return -1; if (isDigit(c32)) return i; if (c0 != c32) i++; // surrogate found. index increment for lower surrogate. } return -1; } /** * @private * get the index of last digit. */ mx_internal function indexOfLastDigit(input:String, len:int, end:int):int { if (!input || !len) return -1; for (var i:int = end; i >= 0; i--) { var c0:int = input.charCodeAt(i); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) return -1; if (c0 != c32) i--; // surrogate found. index decrement for lower surrogate. if (isDigit(c32)) return i; } return -1; } /** * @private */ mx_internal function inputHasMultipleNegativeSymbols(input:String):Boolean { if (!input) return false; var nflag:Boolean = false; var gflag:Boolean = false; var i:int = 0; var c:String; if (negativeSymbol == decimalSeparator) { nflag = true; } else { for (i = 0; i < NEGATIVE_SYMBOLS.length; i++) { c = NEGATIVE_SYMBOLS.charAt(i); if (decimalSeparator == c) { nflag = true; break; } } } if (negativeSymbol == groupingSeparator) { gflag = true } else { for (i = 0; i < NEGATIVE_SYMBOLS.length; i++) { c = NEGATIVE_SYMBOLS.charAt(i); if (groupingSeparator == c) { gflag = true; break; } } } if (!nflag && !gflag && (input.indexOf(negativeSymbol) != input.lastIndexOf(negativeSymbol))) { return true; } var nsymbols:String = NEGATIVE_SYMBOLS + negativeSymbol; var ncount:int = 0; for (i = 0; i < input.length; i++) { c = input.charAt(i); if (nsymbols.indexOf(c) != -1) ncount++; } if (!gflag) { if (!nflag) { if (ncount > 1) return true; } else { if (ncount > 2) return true; } } return false; } /** * @private */ mx_internal function inputHasNegativeSymbol(input:String):Boolean { if (!input) return false; if (input.indexOf(negativeSymbol) != -1) return true; for (var i:int = 0; i < input.length; i++) { var c:String = input.charAt(i); if (NEGATIVE_SYMBOLS.indexOf(c) != -1) return true; } return false; } /** * @private * Check if it is a digit.. */ private function isDigit(codepoint:int):Boolean { if (GlobalizationUtils.isDigit(codepoint)) return true; // Adding 9 may not be right always. But there is no way for user to // communicate the highest digit. if ((codepoint >= digitsType) && (codepoint <= digitsType + 9 )) return true; return false; } /** * @private */ mx_internal function isNegativeSymbol(input:String):Boolean { if (!input) return false; if (input == negativeSymbol) return true; for (var i:int = 0; i < NEGATIVE_SYMBOLS.length; i++) { var c:String = NEGATIVE_SYMBOLS.charAt(i); if (input == c) return true; } return false; } /** * @private * Load the error strings overrides. */ mx_internal function loadChangedResources():void { decimalPointCountError = decimalPointCountErrorOverride; greaterThanMaxError = greaterThanMaxErrorOverride; notAnIntegerError = notAnIntegerErrorOverride; invalidCharError = invalidCharErrorOverride; invalidFormatCharsError = invalidFormatCharsErrorOverride; lessThanMinError = lessThanMinErrorOverride; negativeError = negativeErrorOverride; negativeSymbolError = negativeSymbolErrorOverride; fractionalDigitsError = fractionalDigitsErrorOverride; parseError = parseErrorOverride; localeUndefinedError = localeUndefinedError; } private function inputHasNoDigits(input:String):Boolean { if (!input) return false; for (var i:int; i < input.length; i++) { var c0:int = input.charCodeAt(i); var c1:int = processSurrogates(input, c0, i, input.length); if (c1 == -1) continue; if (c0 != c1) i++; if (isDigit(c1)) return false; } return true; } /** * @private */ mx_internal function processSurrogates(input:String, c0:int, index:int, len:int):int { var j:int = 0; var c1:int; if (GlobalizationUtils.isLeadingSurrogate(c0)) { j = index + 1; if (j < len) { c1 = input.charCodeAt(j); if (GlobalizationUtils.isTrailingSurrogate(c1)) c0 = GlobalizationUtils.surrogateToUTF32(c0, c1); else return -1; } else return -1; } else if (GlobalizationUtils.isTrailingSurrogate(c0)) { j = index - 1; if (j >= 0) { c1 = input.charCodeAt(j); if (GlobalizationUtils.isLeadingSurrogate(c1)) c0 = GlobalizationUtils.surrogateToUTF32(c1, c0); else return -1; } else return -1; } return c0; } /** * @private * Validate the number string portion after the decimal point. * *

Checks that there are no errors in the number string after the * decimal. Example errors could be having a grouping separator or using an * invalid character like non-numeral after the decimal. If * there are any such errors, this method reports ""invalidCharError"" and * returns false. Otherwise, returns true.

* * @param input Input string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateDecimalString(input:String, baseField:String, results:Array, negPosLeft:Boolean):Boolean { if (!input) return true; var dindex:int; if (negPosLeft) dindex = input.lastIndexOf(decimalSeparator); else dindex = input.indexOf(decimalSeparator); var c:String; var i:int; var c0:int; var c1:int; if (dindex == -1) return true; for (i = input.length; i > dindex; i--) { c0 = input.charCodeAt(i); c1 = processSurrogates(input, c0, i, eindex); if (c1 == -1) return false; //illegal surrogate if (isDigit(c1)) break; if (c0 != c1) i--; // digit was surrogate. increment string index. } var eindex:int = i; i = dindex + decimalSeparator.length; for (; i < eindex; i++) { c0 = input.charCodeAt(i); c1 = processSurrogates(input, c0, i, eindex); if ((c1 != -1) && isDigit(c1)) { if (c0 != c1) i++; // digit was surrogate. increment string index. continue; } else { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } } return true; } /** * @private * Check if a number has correct number of fraction digits. * *

This method validates if a decimal number has correct number of * fraction digits as specified by the fractionalDigits * property. It also checks if a number is supposed to be integer, based * on the domain property. For fraction digits error, it * reports the ""fractionalDigitsError"" message as specified in the * validator resources bundle. For integer error it reports the * ""integerError"" message. If there is an error, * this method returns false. Otherwise returns * true.

* * @param input Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateFractionPart(input:String, decimalSeparatorIndex:int, baseField:String, results:Array):Boolean { if (!input) return true; // Make sure that there aren't too many digits after the decimal point: // if domain is int there should be none, // otherwise there should be no more than specified by fractionalDigits. // The input string ALWAYS contains . as decimalseparator as, the caller // converts number obtained from NumberFormatter.parseNumber() to string // and then sends. const len:int = input.length; if (decimalSeparatorIndex != -1) { var numDigitsAfterDecimal:Number = 0; // we only have a '.' if (input == decimalSeparator) { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } var i:int = decimalSeparatorIndex + decimalSeparator.length; // There may not be any digits after the decimal // if domain is int. var c0:int = input.charCodeAt(i); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } if ((i < len) && isDigit(c32)) { if (domain == NumberValidatorDomainType.INT) { results.push(new ValidationResult( true, baseField,""integer"", notAnIntegerError)); return false; } } for (;i < len; i++) { c0 = input.charCodeAt(i); c32 = processSurrogates(input, c0, i, len); if (c32 == -1) { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } if (c0 != c32) i++; // surrogate found. increment index of lower surrogate. ++numDigitsAfterDecimal; // break at ) or - or currency string when validatng fractions. if (!isDigit(c32)) break; // Make sure fractionalDigits is not exceeded. if (fractionalDigits != -1 && numDigitsAfterDecimal > fractionalDigits) { results.push(new ValidationResult( true, baseField, ""fractionalDigits"", fractionalDigitsError)); return false; } } } return true; } /** * @private * Check if a number string contains invalid characters. * *

This method validates if a number string has any characters other * than the caller specified valid characters. Valid characters for numbers * and currency comprise of digits, decimal separator, grouping separator, * negative format characters, currency ISO code, currency symbol and white * space. If any other character is found, then this method returns * false. Otherwise returns true.

* * @param input String representation of number to be validated. * @param len int specifying the length of input * @param validChars String containing all valid characters. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ // detect if invalid characters are present in input. Caller supplies the // valid characters. // TODO: The code to check for valid surrogates is repeated in many methods. // See if this can be optimized. mx_internal function validateInputCharacters(input:String, len:int, validChars:String):Boolean { if (!input) return true; for (var i:int = 0; i < len; i++) { const c:String = input.charAt(i); if (validChars.indexOf(c) == -1) { var c0:int = c.charCodeAt(0); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) return true; else if (c0 != c32) // surrogate. increment string index. i++; if (isDigit(c0)) continue; if (GlobalizationUtils.isWhiteSpace(c0)) continue; return true; } } return false; } /** * @private * Check if input number string has any format or negative symbol errors. * *

This method validates if an input number string has right format * and does not have multiple negative symbols. * If there is an error, this method returns false. Otherwise * returns true.

* * @param input Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ // check some common errors. mx_internal function validateNumberFormat(input:String, results:Array, baseField:String):Boolean { if (!input) return true; const len:int = input.length; var c:String; if (input.charAt(0) == ""("") { // Make sure the last character is a closed parenthesis. if (input.charAt(len - 1) != "")"") { results.push(new ValidationResult( true, baseField, ""invalidFormatChars"", invalidFormatCharsError)); return false; } } else if (input.charAt(len - 1) == "")"") { // Make sure the last character is a closed parenthesis. if (input.charAt(0) != ""("") { results.push(new ValidationResult( true, baseField, ""invalidFormatCharsError"", invalidFormatCharsError)); return false; } } if (decimalSeparator == groupingSeparator) { results.push(new ValidationResult( true, baseField, ""invalidFormatChars"", invalidFormatCharsError)); return false; } else if (inputHasNoDigits(input)) { results.push(new ValidationResult( true, baseField, ""parseError"", parseError)); return false; } else if (inputHasMultipleNegativeSymbols(input)) { results.push(new ValidationResult( true, baseField, ""negativeSymbol"", negativeSymbolError)); return false; } return true; } /** * @private * Check if input number can be negative depending on allowNegative * property. * *

Checks if input number can be negative based on the * allowNegative property. If allowNegative is * false and number is negative, this method reports ""negativeError"" and * returns false. Otherwise, returns true.

* * @param inputNum Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateNumberNegativity(inputNum:Number, baseField:String, results:Array):Boolean { if (inputNum < 0) { // Check if negative input is allowed. if (!allowNegative) { results.push(new ValidationResult( true, baseField, ""negative"", negativeError)); return false; } } return true; } /** * @private * Check if a number is in a range specified by the user. * *

This method validates if a number is in the range specified by the * user. The minValue and maxValue properties define the range. If the * number is not in the range, then this method reports either * ""lowerThanMinError"" or ""exceedsMaxError"". If there is a range error, * this returns false. Otherwise returns * true.

* * @param num Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateNumberRange(num:Number, baseField:String, results:Array):Boolean { const maxValue:Number = Number(maxValue); const minValue:Number = Number(minValue); if (!isNaN(minValue) || !isNaN(maxValue)) { if (!isNaN(minValue) && (num < minValue)) { results.push(new ValidationResult( true, baseField, ""lowerThanMin"", lessThanMinError)); return false; } if (!isNaN(maxValue) && (num > maxValue)) { results.push(new ValidationResult( true, baseField, ""exceedsMax"", greaterThanMaxError)); return false; } } return true; } } } ",12312,True,2603.800746592771,median "/* StateBufferLoop.ino This example implements the for/next picture drawing loop as a state machine. Pro: Display refresh is distributed over several steps (only one page is drawn at a time, which consumes lesser time than refreshing the complete screen) Contra: (A) Artefacts may be visible. (B) It is more difficult to switch between different screens. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); } uint16_t seconds = 0; // this task should be called as often as possible void high_speed_task(void) { // place your commands here, they will be executed very often // as an example, calculated the seconds since startup... seconds = millis() / 1000; } // this procedure contains the u8g2 draw commands to draw someting on the screen void draw() { u8g2.setFont(u8g2_font_logisoso58_tn); u8g2.setCursor(0,60); u8g2.print(seconds); } // this is the state machine, which will replace the do - while loop void draw_page(void) { static uint8_t is_next_page = 0; // call to first page, if required if ( is_next_page == 0 ) { u8g2.firstPage(); is_next_page = 1; } // draw our screen draw(); // call to next page if ( u8g2.nextPage() == 0 ) { is_next_page = 0; // ensure, that first page is called } } // arduno main loop void loop(void) { high_speed_task(); draw_page(); } ",16304,True,4946.399114098567,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.managers { import flash.display.DisplayObject; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Timer; import mx.controls.ToolTip; import mx.core.FlexGlobals; import mx.core.FlexVersion; import mx.core.IFlexModule; import mx.core.IInvalidating; import mx.core.ILayoutDirectionElement; import mx.core.IToolTip; import mx.core.IUIComponent; import mx.core.LayoutDirection; import mx.core.mx_internal; import mx.effects.EffectManager; import mx.effects.IAbstractEffect; import mx.events.DynamicEvent; import mx.events.EffectEvent; import mx.events.ToolTipEvent; import mx.managers.IToolTipManagerClient; import mx.styles.IStyleClient; import mx.validators.IValidatorListener; use namespace mx_internal; [ExcludeClass] /** * @private * The ToolTipManager lets you set basic ToolTip and error tip functionality, * such as display delay and the disabling of ToolTips. * * @see mx.controls.ToolTip * @see mx.validators.Validator */ public class ToolTipManagerImpl extends EventDispatcher implements IToolTipManager2 { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var instance:IToolTipManager2; /** * @private * * Place to hook in additional classes */ public static var mixins:Array; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ public static function getInstance():IToolTipManager2 { if (!instance) instance = new ToolTipManagerImpl(); return instance; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private */ public function ToolTipManagerImpl() { super(); if (instance) throw new Error(""Instance already exists.""); if (mixins) { var n:int = mixins.length; for (var i:int = 0; i < n; i++) { new mixins[i](this); } } if (hasEventListener(""initialize"")) dispatchEvent(new Event(""initialize"")); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * A flag that keeps track of whether this class's initialize() * method has been executed. */ mx_internal var initialized:Boolean = false; /** * @private * This timer is used to delay the appearance of a normal ToolTip * after the mouse moves over a target; an error tip has no such delay. * *

This timer, which is lazily created, is started when the mouse * moves over an object with a ToolTip, with a duration specified * by showDelay. * If the mouse moves out of this object before the timer fires, * the ToolTip is never created. * If the mouse stays over the object until the timer fires, * the ToolTip is created and its showEffect is started. */ mx_internal var showTimer:Timer; /** * @private * This timer is used to make the tooltip ""time out"" and hide itself * if the mouse stays over a target. * *

This timer, which is lazily created, is started * when the showEffect ends. * When it fires, the hideEffect is started.

*/ mx_internal var hideTimer:Timer; /** * @private * This timer is used to implement mousing quickly over multiple targets * with ToolTip... * *

This timer, which is lazily created, is started * when ...

*/ mx_internal var scrubTimer:Timer; /** * @private */ mx_internal var currentText:String; /** * @private */ mx_internal var isError:Boolean; /** * The UIComponent with the ToolTip assigned to it * that was most recently under the mouse. * During much of the tool tip life cycle this property * has the same value as the currentTarget property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var previousTarget:DisplayObject; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // currentTarget //---------------------------------- /** * @private */ private var _currentTarget:DisplayObject; /** * The UIComponent that is currently displaying a ToolTip, * or null if none is. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get currentTarget():DisplayObject { return _currentTarget; } /** * @private */ public function set currentTarget(value:DisplayObject):void { _currentTarget = value; } //---------------------------------- // currentToolTip //---------------------------------- /** * @private */ mx_internal var _currentToolTip:DisplayObject; /** * The ToolTip object that is currently visible, * or null if none is shown. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get currentToolTip():IToolTip { return _currentToolTip as IToolTip; } /** * @private */ public function set currentToolTip(value:IToolTip):void { _currentToolTip = value as DisplayObject; if (hasEventListener(""currentToolTip"")) dispatchEvent(new Event(""currentToolTip"")); } //---------------------------------- // enabled //---------------------------------- /** * @private */ private var _enabled:Boolean = true; /** * If true, the ToolTipManager will automatically show * ToolTips when the user moves the mouse pointer over components. * If false, no ToolTips will be shown. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get enabled():Boolean { return _enabled; } /** * @private */ public function set enabled(value:Boolean):void { _enabled = value; } //---------------------------------- // hideDelay //---------------------------------- /** * @private */ private var _hideDelay:Number = 10000; // milliseconds /** * The amount of time, in milliseconds, that Flex waits * to hide the ToolTip after it appears. * Once Flex hides a ToolTip, the user must move the mouse * off the component and then back onto it to see the ToolTip again. * If you set hideDelay to Infinity, * Flex does not hide the ToolTip until the user triggers an event, * such as moving the mouse off of the component. * * @default 10000 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hideDelay():Number { return _hideDelay; } /** * @private */ public function set hideDelay(value:Number):void { _hideDelay = value; } //---------------------------------- // hideEffect //---------------------------------- /** * @private */ private var _hideEffect:IAbstractEffect; /** * The effect that plays when a ToolTip is hidden, * or null if the ToolTip should disappear with no effect. * *

Effects are not marshaled across applicationDomains in a sandbox * as they may not be supportable in different versions

* * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hideEffect():IAbstractEffect { return _hideEffect; } /** * @private */ public function set hideEffect(value:IAbstractEffect):void { _hideEffect = value as IAbstractEffect; } //---------------------------------- // scrubDelay //---------------------------------- /** * @private */ private var _scrubDelay:Number = 100; // milliseconds /** * The amount of time, in milliseconds, that a user can take * when moving the mouse between controls before Flex again waits * for the duration of showDelay to display a ToolTip. * *

This setting is useful if the user moves quickly from one control * to another; after displaying the first ToolTip, Flex will display * the others immediately rather than waiting. * The shorter the setting for scrubDelay, the more * likely that the user must wait for an amount of time specified * by showDelay in order to see the next ToolTip. * A good use of this property is if you have several buttons on a * toolbar, and the user will quickly scan across them to see brief * descriptions of their functionality.

* * @default 100 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get scrubDelay():Number { return _scrubDelay; } /** * @private */ public function set scrubDelay(value:Number):void { _scrubDelay = value; } //---------------------------------- // showDelay //---------------------------------- /** * @private */ private var _showDelay:Number = 500; // milliseconds /** * The amount of time, in milliseconds, that Flex waits * before displaying the ToolTip box once a user * moves the mouse over a component that has a ToolTip. * To make the ToolTip appear instantly, set showDelay to 0. * * @default 500 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showDelay():Number { return _showDelay; } /** * @private */ public function set showDelay(value:Number):void { _showDelay = value; } //---------------------------------- // showEffect //---------------------------------- /** * @private */ private var _showEffect:IAbstractEffect; /** * The effect that plays when a ToolTip is shown, * or null if the ToolTip should appear with no effect. * *

Effects are not marshaled across applicationDomains in a sandbox * as they may not be supportable in different versions

* * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showEffect():IAbstractEffect { return _showEffect; } /** * @private */ public function set showEffect(value:IAbstractEffect):void { _showEffect = value as IAbstractEffect; } //---------------------------------- // toolTipClass //---------------------------------- /** * @private */ private var _toolTipClass:Class = ToolTip; /** * The class to use for creating ToolTips. * *

The ToolTipClass is not marshaled across applicationDomains in a sandbox * as they may not be supportable in different versions. Child * applications should only be interested in setting the tooltip * for objects within themselves

* * @default mx.controls.ToolTip * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get toolTipClass():Class { return _toolTipClass; } /** * @private */ public function set toolTipClass(value:Class):void { _toolTipClass = value; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Initializes the class. * *

This method sets up three Timer objects that ToolTipManager * starts and stops while tracking the mouse. * The repeatCount is set to 1 so that they fire only once. * Their duration is set later, just before they are started. * The timers are never destroyed once they are created here.

* *

This method is called by targetChanged(); Flex waits to initialize * the class until mouse-tracking happens in order to optimize * startup time.

*/ mx_internal function initialize():void { if (!showTimer) { showTimer = new Timer(0, 1); showTimer.addEventListener(TimerEvent.TIMER, showTimer_timerHandler); } if (!hideTimer) { hideTimer = new Timer(0, 1); hideTimer.addEventListener(TimerEvent.TIMER, hideTimer_timerHandler); } if (!scrubTimer) scrubTimer = new Timer(0, 1); initialized = true; } /** * Registers a target UIComponent or UITextField, and the text * for its ToolTip, with the ToolTipManager. * This causes the ToolTipManager to display a ToolTip * when the mouse hovers over the target. * *

This method is called by the setter * for the toolTip property in UIComponent and UITextField.

* * @param target The UIComponent or UITextField that owns the ToolTip. * * @param oldToolTip The old text that was displayed * in the ToolTip. * * @param newToolTip The new text to display in the ToolTip. * If null, no ToolTip will be displayed when the mouse hovers * over the target. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function registerToolTip(target:DisplayObject, oldToolTip:String, newToolTip:String):void { if (!oldToolTip && newToolTip) { target.addEventListener(MouseEvent.MOUSE_OVER, toolTipMouseOverHandler); target.addEventListener(MouseEvent.MOUSE_OUT, toolTipMouseOutHandler); // If the mouse is already over the object // that's getting a toolTip, show the tip. if (mouseIsOver(target)) showImmediately(target); } else if (oldToolTip && !newToolTip) { target.removeEventListener(MouseEvent.MOUSE_OVER, toolTipMouseOverHandler); target.removeEventListener(MouseEvent.MOUSE_OUT, toolTipMouseOutHandler); // If the mouse is over the object whose toolTip // is being removed, hide the tip. if (mouseIsOver(target)) hideImmediately(target); } } /** * Registers a target UIComponent, and the text * for its error tip, with the ToolTipManager. * This causes the ToolTipManager to display an error tip * when the mouse hovers over the target. * *

This method is called by the setter * for the errorString property in UIComponent.

* * @param target The UIComponent or UITextField that owns the ToolTip. * * @param oldErrorString The old text that was displayed * in the error tip. * * @param newErrorString The new text to display in the error tip. * If null, no error tip will be displayed when the mouse hovers * over the target. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function registerErrorString(target:DisplayObject, oldErrorString:String, newErrorString:String):void { if (!oldErrorString && newErrorString) { target.addEventListener(MouseEvent.MOUSE_OVER, errorTipMouseOverHandler); target.addEventListener(MouseEvent.MOUSE_OUT, errorTipMouseOutHandler); // If the mouse is already over the object // that's getting an errorTip, show the tip. if (mouseIsOver(target)) showImmediately(target); } else if (oldErrorString && !newErrorString) { target.removeEventListener(MouseEvent.MOUSE_OVER, errorTipMouseOverHandler); target.removeEventListener(MouseEvent.MOUSE_OUT, errorTipMouseOutHandler); // If the mouse is over the object whose toolTip // is being removed, hide the tip. if (mouseIsOver(target)) hideImmediately(target); } } /** * @private * Returns true if the mouse is over the specified target. */ private function mouseIsOver(target:DisplayObject):Boolean { if (!target || !target.stage) return false; //SDK:13465 - If we pass through the above if block, then //we have a target component and its been added to the //display list. If the mouse coordinates are (0,0), there //is a chance the component has not been positioned yet //and we'll end up mistakenly showing tooltips since the //target hitTest will return true. if ((target.stage.mouseX == 0) && (target.stage.mouseY == 0)) return false; if (target is ILayoutManagerClient && !ILayoutManagerClient(target).initialized) return false; return target.hitTestPoint(target.stage.mouseX, target.stage.mouseY, true); } /** * @private * Shows the tip immediately when the toolTip or errorTip property * becomes non-null and the mouse is over the target. */ private function showImmediately(target:DisplayObject):void { var oldShowDelay:Number = ToolTipManager.showDelay; ToolTipManager.showDelay = 0; checkIfTargetChanged(target); ToolTipManager.showDelay = oldShowDelay; } /** * @private * Hides the tip immediately when the toolTip or errorTip property * becomes null and the mouse is over the target. */ private function hideImmediately(target:DisplayObject):void { checkIfTargetChanged(null); } /** * Replaces the ToolTip, if necessary. * *

Determines whether the UIComponent or UITextField object * with the ToolTip assigned to it that is currently under the mouse * pointer is the most recent such object. * If not, it removes the old ToolTip and displays the new one.

* * @param displayObject The UIComponent or UITextField that is currently under the mouse. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function checkIfTargetChanged(displayObject:DisplayObject):void { if (!enabled) return; findTarget(displayObject); if (currentTarget != previousTarget) { targetChanged(); previousTarget = currentTarget; } } /** * Searches from the displayObject object up the chain * of parent objects until it finds a UIComponent or UITextField object * with a toolTip or errorString property. * Treats an empty string as a valid toolTip property. * Sets the currentTarget property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function findTarget(displayObject:DisplayObject):void { // Walk up the DisplayObject parent chain looking for a UIComponent // with a toolTip or errorString property. Note that we stop // even if we find a tooltip which is an empty string. Although // we don't display empty tooltips, we have to track when we // are over a movieclip with an empty tooltip so that we can // hide any previous tooltip. This allows a child to set // toolTip="""" to ""cancel"" its parent's toolTip. while (displayObject) { if (displayObject is IValidatorListener) { currentText = IValidatorListener(displayObject).errorString; var showErrorTip:Boolean; if (displayObject is IStyleClient) showErrorTip = FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0 || IStyleClient(displayObject).getStyle(""showErrorTip""); ; if (currentText != null && currentText != """" && showErrorTip) { currentTarget = displayObject; isError = true; return; } } if (displayObject is IToolTipManagerClient) { currentText = IToolTipManagerClient(displayObject).toolTip; if (currentText != null) { currentTarget = displayObject; isError = false; return; } } displayObject = displayObject.parent; } currentText = null; currentTarget = null; } /** * Removes any ToolTip that is currently displayed and displays * the ToolTip for the UIComponent that is currently under the mouse * pointer, as determined by the currentTarget property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function targetChanged():void { // Do lazy creation of the Timer objects this class uses. if (!initialized) initialize() var event:ToolTipEvent; if (previousTarget && currentToolTip) { if (currentToolTip is IToolTip) { event = new ToolTipEvent(ToolTipEvent.TOOL_TIP_HIDE); event.toolTip = currentToolTip; previousTarget.dispatchEvent(event); } else { if (hasEventListener(ToolTipEvent.TOOL_TIP_HIDE)) dispatchEvent(new Event(ToolTipEvent.TOOL_TIP_HIDE)); } } reset(); if (currentTarget) { // Don't display empty tooltips. if (currentText == """") return; // Dispatch a ""startToolTip"" event // from the object displaying the tooltip. event = new ToolTipEvent(ToolTipEvent.TOOL_TIP_START); currentTarget.dispatchEvent(event); if (showDelay == 0 || scrubTimer.running) { // Create the tooltip and start its showEffect. createTip(); initializeTip(); positionTip(); showTip(); } else { showTimer.delay = showDelay; showTimer.start(); // After the delay, showTimer_timerHandler() // will create the tooltip and start its showEffect. } } } /** * Creates an invisible new ToolTip. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set, * The ToolTipManager makes subsequent calls to * initializeTip(), positionTip(), * and showTip() to complete the display * of the ToolTip.

* *

The type of ToolTip that is created is determined by the * toolTipClass property. * By default, this is the ToolTip class. * This class can be styled to appear as either a normal ToolTip * (which has a yellow background by default) or as an error tip * for validation errors (which is red by default).

* *

After creating the ToolTip with the new * operator, this method stores a reference to it in the * currentToolTip property. * It then uses addChild() to add this ToolTip to the * SystemManager's toolTips layer.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function createTip():void { // Dispatch a ""createToolTip"" event // from the object displaying the tooltip. var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_CREATE); currentTarget.dispatchEvent(event); if (event.toolTip) currentToolTip = event.toolTip; else currentToolTip = new toolTipClass(); currentToolTip.visible = false; // Set the tooltip to be in the same module factory as the target to the // correct style manager is used. Don't overwrite an existing module factory. if (currentToolTip is IFlexModule && IFlexModule(currentToolTip).moduleFactory == null && currentTarget is IFlexModule) IFlexModule(currentToolTip).moduleFactory = IFlexModule(currentTarget).moduleFactory; if (hasEventListener(""createTip"")) if (!dispatchEvent(new Event(""createTip"", false, true))) return; var sm:ISystemManager = getSystemManager(currentTarget) as ISystemManager; sm.topLevelSystemManager.toolTipChildren.addChild(currentToolTip as DisplayObject); } /** * Initializes a newly created ToolTip with the appropriate text, * based on the object under the mouse. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set. * The ToolTipManager calls createTip() before * this method, and positionTip() and * showTip() after.

* *

If a normal ToolTip is being displayed, this method * sets its text as specified by the toolTip * property of the object under the mouse. * If an error tip is being displayed, the text is as * specified by the errorString property * of the object under the mouse.

* *

This method also makes the ToolTip the appropriate * size for the text that it needs to display.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function initializeTip():void { // Set the text of the tooltip. if (currentToolTip is IToolTip) IToolTip(currentToolTip).text = currentText; if (isError && currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""styleName"", ""errorTip""); sizeTip(currentToolTip); if (currentToolTip is IStyleClient) { // Set up its ""show"" and ""hide"" effects. if (showEffect) IStyleClient(currentToolTip).setStyle(""showEffect"", showEffect); if (hideEffect) IStyleClient(currentToolTip).setStyle(""hideEffect"", hideEffect); } if (showEffect || hideEffect) { currentToolTip.addEventListener(EffectEvent.EFFECT_END, effectEndHandler); } } /** * @private * Objects added to the SystemManager's ToolTip layer don't get * automatically measured or sized, so ToolTipManager has to * measure it and set its size. */ public function sizeTip(toolTip:IToolTip):void { // Force measure() to be called on the tooltip. // Otherwise, its measured size will be 0. if (toolTip is IInvalidating) IInvalidating(toolTip).validateNow(); toolTip.setActualSize( toolTip.getExplicitOrMeasuredWidth(), toolTip.getExplicitOrMeasuredHeight()); } /** * Positions a newly created and initialized ToolTip on the stage. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set. * The ToolTipManager calls createTip() and * initializeTip() before this method, * and showTip() after.

* *

If a normal ToolTip is being displayed, this method positions * its upper-left (upper-right) corner near the lower-right (lower-left) * of the arrow cursor. This method ensures that the ToolTip is * completely in view. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function positionTip():void { // Determine layoutDirection of the target component. var layoutDirection:String; if (currentTarget is ILayoutDirectionElement) layoutDirection = ILayoutDirectionElement(currentTarget).layoutDirection; else layoutDirection = LayoutDirection.LTR; const mirror:Boolean = (layoutDirection == LayoutDirection.RTL); var x:Number; var y:Number; var screenWidth:Number = currentToolTip.screen.width; var screenHeight:Number = currentToolTip.screen.height; if (isError) { // Tooltips are laid out in the same direction as the target // component. var tipElt:ILayoutDirectionElement = currentToolTip as ILayoutDirectionElement; if (tipElt && tipElt.layoutDirection != layoutDirection) { tipElt.layoutDirection = layoutDirection; // sizeTip below will call validateNow() tipElt.invalidateLayoutDirection(); } var targetGlobalBounds:Rectangle = getGlobalBounds(currentTarget, currentToolTip.root, mirror); x = mirror ? targetGlobalBounds.left - 4 : targetGlobalBounds.right + 4; y = targetGlobalBounds.top - 1; // If there's no room to the right (left) of the control, put it // above or below, with the left (right) edge of the error tip // aligned with the left (right) edge of the target. var noRoom:Boolean = mirror ? x < currentToolTip.width : x + currentToolTip.width > screenWidth; if (noRoom) { var newWidth:Number = NaN; var oldWidth:Number = NaN; x = mirror ? targetGlobalBounds.right + 2 - currentToolTip.width : targetGlobalBounds.left - 2; // If the error tip would be too wide for the stage, // reduce the maximum width to fit onstage. Note that // we have to reassign the text in order to get the tip // to relayout after changing the border style and maxWidth. if (mirror) { if (x < currentToolTip.width + 4) { // -4 on the left, +2 on the right = -2 x = 4; newWidth = targetGlobalBounds.right - 2; } } else { if (x + currentToolTip.width + 4 > screenWidth) newWidth = screenWidth - x - 4; } if (!isNaN(newWidth)) { oldWidth = Object(toolTipClass).maxWidth; Object(toolTipClass).maxWidth = newWidth; if (currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""borderStyle"", ""errorTipAbove""); currentToolTip[""text""] = currentToolTip[""text""]; } // Even if the error tip will fit onstage, we still need to // change the border style and get the error tip to relayout. else { if (currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""borderStyle"", ""errorTipAbove""); currentToolTip[""text""] = currentToolTip[""text""]; } if (currentToolTip.height + 2 < targetGlobalBounds.top) { // There's room to put it above the control. y = targetGlobalBounds.top - (currentToolTip.height + 2); } else { // No room above, put it below the control. y = targetGlobalBounds.bottom + 2; if (!isNaN(newWidth)) Object(toolTipClass).maxWidth = newWidth; if (currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""borderStyle"", ""errorTipBelow""); currentToolTip[""text""] = currentToolTip[""text""]; } } // Since the border style of the error tip may have changed, // we have to force a remeasurement and change its size. // This is because objects in the toolTips layer // don't undergo normal measurement and layout. sizeTip(currentToolTip) // If we changed the tooltip max size, we change it back. // Otherwise, if RTL, and x wasn't set for maxWidth, reposition // because the width may have changed during the remeasure. if (!isNaN(oldWidth)) Object(toolTipClass).maxWidth = oldWidth; else if (mirror) x = targetGlobalBounds.right + 2 - currentToolTip.width; } else { var sm:ISystemManager = getSystemManager(currentTarget); // Position the upper-left (upper-right) of the tooltip // at the lower-right (lower-left) of the arrow cursor. x = DisplayObject(sm).mouseX + 11; if (mirror) x -= currentToolTip.width; y = DisplayObject(sm).mouseY + 22; // If the tooltip is too wide to fit onstage, move it left (right). var toolTipWidth:Number = currentToolTip.width; if (mirror) { if (x < 2) x = 2; } else if (x + toolTipWidth > screenWidth) { x = screenWidth - toolTipWidth; } // If the tooltip is too tall to fit onstage, move it up. var toolTipHeight:Number = currentToolTip.height; if (y + toolTipHeight > screenHeight) y = screenHeight - toolTipHeight; var pos:Point = new Point(x, y); pos = DisplayObject(sm).localToGlobal(pos); pos = DisplayObject(sm.getSandboxRoot()).globalToLocal(pos); x = pos.x; y = pos.y; } currentToolTip.move(x, y); } /** * Shows a newly created, initialized, and positioned ToolTip. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set. * The ToolTipManager calls createTip(), * initializeTip(), and positionTip() * before this method.

* *

This method first dispatches a ""showToolTip"" * event from the object under the mouse. * This gives you a chance to do special processing on a * particular object's ToolTip just before it becomes visible. * It then makes the ToolTip visible, which triggers * the ToolTipManager's showEffect if one is specified. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function showTip():void { // Dispatch a ""showToolTip"" event // from the object displaying the tooltip. var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_SHOW); event.toolTip = currentToolTip; currentTarget.dispatchEvent(event); if (isError) { // Listen for a change event so we know when to hide the tip currentTarget.addEventListener(Event.CHANGE, changeHandler); } else { var sm:ISystemManager = getSystemManager(currentTarget); sm.addEventListener(MouseEvent.MOUSE_DOWN, systemManager_mouseDownHandler); } // Make the tooltip visible. // If showEffect exists, this effect will play. // When the effect ends, effectEndHandler() // will start the hideTimer. currentToolTip.visible = true; if (!showEffect) showEffectEnded(); } /** * Hides the current ToolTip. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function hideTip():void { // Dispatch a ""hideToolTip"" event // from the object that was displaying the tooltip. if (previousTarget) { var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_HIDE); event.toolTip = currentToolTip; previousTarget.dispatchEvent(event); } // Make the tooltip invisible. // If hideEffect exists, this effect will play. // When the effect ends, effectEndHandler() // will reset the ToolTipManager to a no-tip state. if (currentToolTip) currentToolTip.visible = false; // When to do this? if (isError) { if (currentTarget) currentTarget.removeEventListener(Event.CHANGE, changeHandler); } else { if (previousTarget) { var sm:ISystemManager = getSystemManager(previousTarget); sm.removeEventListener(MouseEvent.MOUSE_DOWN, systemManager_mouseDownHandler); } } if (!hideEffect) hideEffectEnded(); } /** * Removes any currently visible ToolTip. * If the ToolTip is starting to show or hide, this method * removes the ToolTip immediately without completing the effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function reset():void { // Reset the three timers, in case any are running. showTimer.reset(); hideTimer.reset(); // If there is a current tooltip... if (currentToolTip) { // Remove the event handlers for the effectEnd of the showEffect // and hideEffect, so that calling endEffectsForTarget() doesn't // trigger effectEndHandler(). if (showEffect || hideEffect) { currentToolTip.removeEventListener(EffectEvent.EFFECT_END, effectEndHandler); } // End any show or hide effects that might be playing on it. EffectManager.endEffectsForTarget(currentToolTip); var e:DynamicEvent; if (hasEventListener(""removeChild"")) { e = new DynamicEvent(""removeChild"", false, true); e.sm = currentToolTip.systemManager; e.toolTip = currentToolTip; } if (!e || dispatchEvent(e)) { // Remove it. var sm:ISystemManager = currentToolTip.systemManager as ISystemManager; sm.topLevelSystemManager.toolTipChildren.removeChild(currentToolTip as DisplayObject); } currentToolTip = null; scrubTimer.delay = scrubDelay; scrubTimer.reset(); if (scrubDelay > 0) { scrubTimer.delay = scrubDelay; scrubTimer.start(); } } } /** * Creates an instance of the ToolTip class with the specified text * and displays it at the specified location in stage coordinates. * *

ToolTips appear in their own layer, on top of everything * except cursors.

* *

The standard way of using ToolTips is to let the ToolTipManager * automatically show and hide them as the user moves the mouse over * the objects that have the toolTip property set. * You can turn off this automatic ToolTip management by setting * the ToolTipManager's enabled property to * false.

* *

By contrast, this method—along with hideToolTip()—gives * you programmatic control over ToolTips. * You can show them when and where you choose, * and you can even show more than one at once if you need to. * (The ToolTipManager never does this, because it is generally * confusing to the user).

* *

This method first creates a new instance of ToolTip and calls the * addChild() method to put it into the SystemManager's * toolTips layer. * If you are showing an error tip, it sets the appropriate styles. * Then it sets the text for the ToolTip, sizes the ToolTip based on * its text, and positions it where you specified.

* *

You must save the reference to the ToolTip that this method * returns so that you can pass it to the hideToolTip() method.

* * @param text The text to display in the ToolTip instance. * * @param x The horizontal coordinate of the ToolTip in stage coordinates. * In case of multiple stages, the relevant stage is determined * from the context argument. * * @param y The vertical coordinate of the ToolTip in stage coordinates. * In case of multiple stages, the relevant stage is determined * from the context argument. * * @param errorTipBorderStyle The border style of an error tip. This method * argument can be null, ""errorTipRight"", ""errorTipAbove"", or ""errorTipBelow"". * If it is null, then the createToolTip() method creates a normal ToolTip. If it is * ""errorTipRight"", ""errorTipAbove"", or ""errorTipBelow"", then the createToolTip() * method creates an error tip, and this parameter determines where the arrow * of the error tip points to (the error's target). For example, if you pass ""errorTipRight"", Flex * positions the error tip (via the x and y arguments) to the * right of the error target; the arrow is on the left edge of the error tip. * * @param context This property is not currently used. * * @return The newly created ToolTip. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function createToolTip(text:String, x:Number, y:Number, errorTipBorderStyle:String = null, context:IUIComponent = null):IToolTip { var toolTip:ToolTip = new ToolTip(); var sm:ISystemManager = context ? context.systemManager as ISystemManager: FlexGlobals.topLevelApplication.systemManager as ISystemManager; if (context is IFlexModule) toolTip.moduleFactory = IFlexModule(context).moduleFactory; else toolTip.moduleFactory = sm; var e:DynamicEvent; if (hasEventListener(""addChild"")) { e = new DynamicEvent(""addChild"", false, true); e.sm = sm; e.toolTip = toolTip; } if (!e || dispatchEvent(e)) { sm.topLevelSystemManager.toolTipChildren.addChild(toolTip as DisplayObject); } if (errorTipBorderStyle) { toolTip.setStyle(""styleName"", ""errorTip""); toolTip.setStyle(""borderStyle"", errorTipBorderStyle); } toolTip.text = text; sizeTip(toolTip); toolTip.move(x, y); // Ensure that tip is on screen? // Should x and y for error tip be tip of pointy border? // show effect? return toolTip as IToolTip; } /** * Destroys a specified ToolTip that was created by the createToolTip() method. * *

This method calls the removeChild() method to remove the specified * ToolTip from the SystemManager's ToolTips layer. * It will then be garbage-collected unless you keep a * reference to it.

* *

You should not call this method on the ToolTipManager's * currentToolTip.

* * @param toolTip The ToolTip instance to destroy. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function destroyToolTip(toolTip:IToolTip):void { var e:DynamicEvent; if (hasEventListener(""removeChild"")) { e = new DynamicEvent(""removeChild"", false, true); e.sm = toolTip.systemManager; e.toolTip = toolTip; } if (!e || dispatchEvent(e)) { // Remove it. var sm:ISystemManager = toolTip.systemManager as ISystemManager; sm.topLevelSystemManager.toolTipChildren.removeChild(toolTip as DisplayObject); } // hide effect? } /** * @private */ mx_internal function showEffectEnded():void { if (hideDelay == 0) { hideTip(); } else if (hideDelay < Infinity) { hideTimer.delay = hideDelay; hideTimer.start(); } if (currentTarget) { // Dispatch a ""toolTipShown"" event // from the object displaying the tooltip. var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_SHOWN); event.toolTip = currentToolTip; currentTarget.dispatchEvent(event); } } /** * @private */ mx_internal function hideEffectEnded():void { reset(); // Dispatch a ""toolTipEnd"" event // from the object that was displaying the tooltip. if (previousTarget) { var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_END); event.toolTip = currentToolTip; previousTarget.dispatchEvent(event); } } /** * @private */ mx_internal function getSystemManager( target:DisplayObject):ISystemManager { return target is IUIComponent ? IUIComponent(target).systemManager : null; } /** * @private */ private function getGlobalBounds(obj:DisplayObject, parent:DisplayObject, mirror:Boolean):Rectangle { var upperLeft:Point = new Point(0, 0); upperLeft = obj.localToGlobal(upperLeft); // If the layout has been mirrored, then the 0,0 is the uppper // right corner; compensate here. if (mirror) upperLeft.x -= obj.width; upperLeft = parent.globalToLocal(upperLeft); return new Rectangle(upperLeft.x, upperLeft.y, obj.width, obj.height); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * This handler is called when the mouse moves over an object * with a toolTip. */ mx_internal function toolTipMouseOverHandler(event:MouseEvent):void { checkIfTargetChanged(DisplayObject(event.target)); } /** * @private * This handler is called when the mouse moves out of an object * with a toolTip. */ mx_internal function toolTipMouseOutHandler(event:MouseEvent):void { checkIfTargetChanged(event.relatedObject); } /** * @private * This handler is called when the mouse moves over an object * with an errorString. */ mx_internal function errorTipMouseOverHandler(event:MouseEvent):void { checkIfTargetChanged(DisplayObject(event.target)); } /** * @private * This handler is called when the mouse moves out of an object * with an errorString. */ mx_internal function errorTipMouseOutHandler(event:MouseEvent):void { checkIfTargetChanged(event.relatedObject); } /** * @private * This handler is called when the showTimer fires. * It creates the tooltip and starts its showEffect. */ mx_internal function showTimer_timerHandler(event:TimerEvent):void { // Make sure we still have a currentTarget when the timer fires. if (currentTarget) { createTip(); initializeTip(); positionTip(); showTip(); } } /** * @private * This handler is called when the hideTimer fires. * It starts the hideEffect. */ mx_internal function hideTimer_timerHandler(event:TimerEvent):void { hideTip(); } /** * @private * This handler is called when the showEffect or hideEffect ends. * When the showEffect ends, it starts the hideTimer, * which will automatically start hiding the tooltip when it fires, * even if the mouse is still over the target. * When the hideEffect ends, the tooltip is removed. */ mx_internal function effectEndHandler(event:EffectEvent):void { if (event.effectInstance.effect == showEffect) showEffectEnded(); else if (event.effectInstance.effect == hideEffect) hideEffectEnded(); } /** * @private * This handler is called when the user clicks the mouse * while a normal tooltip is displayed. * It immediately hides the tooltip. */ mx_internal function systemManager_mouseDownHandler(event:MouseEvent):void { reset(); } /** * @private */ mx_internal function changeHandler(event:Event):void { reset(); } } } ",12257,False,2469.981317316555,median "/* GraphicsTest.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8glib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 16); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display // End of constructor list void u8g2_prepare(void) { u8g2.setFont(u8g2_font_6x10_tf); u8g2.setFontRefHeightExtendedText(); u8g2.setDrawColor(1); u8g2.setFontPosTop(); u8g2.setFontDirection(0); } void u8g2_box_title(uint8_t a) { u8g2.drawStr( 10+a*2, 5, ""U8g2""); u8g2.drawStr( 10, 20, ""GraphicsTest""); u8g2.drawFrame(0,0,u8g2.getDisplayWidth(),u8g2.getDisplayHeight() ); } void u8g2_box_frame(uint8_t a) { u8g2.drawStr( 0, 0, ""drawBox""); u8g2.drawBox(5,10,20,10); u8g2.drawBox(10+a,15,30,7); u8g2.drawStr( 0, 30, ""drawFrame""); u8g2.drawFrame(5,10+30,20,10); u8g2.drawFrame(10+a,15+30,30,7); } void u8g2_disc_circle(uint8_t a) { u8g2.drawStr( 0, 0, ""drawDisc""); u8g2.drawDisc(10,18,9); u8g2.drawDisc(24+a,16,7); u8g2.drawStr( 0, 30, ""drawCircle""); u8g2.drawCircle(10,18+30,9); u8g2.drawCircle(24+a,16+30,7); } void u8g2_r_frame(uint8_t a) { u8g2.drawStr( 0, 0, ""drawRFrame/Box""); u8g2.drawRFrame(5, 10,40,30, a+1); u8g2.drawRBox(50, 10,25,40, a+1); } void u8g2_string(uint8_t a) { u8g2.setFontDirection(0); u8g2.drawStr(30+a,31, "" 0""); u8g2.setFontDirection(1); u8g2.drawStr(30,31+a, "" 90""); u8g2.setFontDirection(2); u8g2.drawStr(30-a,31, "" 180""); u8g2.setFontDirection(3); u8g2.drawStr(30,31-a, "" 270""); } void u8g2_line(uint8_t a) { u8g2.drawStr( 0, 0, ""drawLine""); u8g2.drawLine(7+a, 10, 40, 55); u8g2.drawLine(7+a*2, 10, 60, 55); u8g2.drawLine(7+a*3, 10, 80, 55); u8g2.drawLine(7+a*4, 10, 100, 55); } void u8g2_triangle(uint8_t a) { uint16_t offset = a; u8g2.drawStr( 0, 0, ""drawTriangle""); u8g2.drawTriangle(14,7, 45,30, 10,40); u8g2.drawTriangle(14+offset,7-offset, 45+offset,30-offset, 57+offset,10-offset); u8g2.drawTriangle(57+offset*2,10, 45+offset*2,30, 86+offset*2,53); u8g2.drawTriangle(10+offset,40+offset, 45+offset,30+offset, 86+offset,53+offset); } void u8g2_ascii_1() { char s[2] = "" ""; uint8_t x, y; u8g2.drawStr( 0, 0, ""ASCII page 1""); for( y = 0; y < 6; y++ ) { for( x = 0; x < 16; x++ ) { s[0] = y*16 + x + 32; u8g2.drawStr(x*7, y*10+10, s); } } } void u8g2_ascii_2() { char s[2] = "" ""; uint8_t x, y; u8g2.drawStr( 0, 0, ""ASCII page 2""); for( y = 0; y < 6; y++ ) { for( x = 0; x < 16; x++ ) { s[0] = y*16 + x + 160; u8g2.drawStr(x*7, y*10+10, s); } } } void u8g2_extra_page(uint8_t a) { u8g2.drawStr( 0, 0, ""Unicode""); u8g2.setFont(u8g2_font_unifont_t_symbols); u8g2.setFontPosTop(); u8g2.drawUTF8(0, 24, ""☀ ☁""); switch(a) { case 0: case 1: case 2: case 3: u8g2.drawUTF8(a*3, 36, ""☂""); break; case 4: case 5: case 6: case 7: u8g2.drawUTF8(a*3, 36, ""☔""); break; } } void u8g2_xor(uint8_t a) { uint8_t i; u8g2.drawStr( 0, 0, ""XOR""); u8g2.setFontMode(1); u8g2.setDrawColor(2); for( i = 0; i < 5; i++) { u8g2.drawBox(10+i*16, 18 + (i&1)*4, 21,31); } u8g2.drawStr( 5+a, 19, ""XOR XOR XOR XOR""); u8g2.setDrawColor(0); u8g2.drawStr( 5+a, 29, ""CLR CLR CLR CLR""); u8g2.setDrawColor(1); u8g2.drawStr( 5+a, 39, ""SET SET SET SET""); u8g2.setFontMode(0); } #define cross_width 24 #define cross_height 24 static const unsigned char cross_bits[] U8X8_PROGMEM = { 0x00, 0x18, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0xC0, 0x00, 0x03, 0x38, 0x3C, 0x1C, 0x06, 0x42, 0x60, 0x01, 0x42, 0x80, 0x01, 0x42, 0x80, 0x06, 0x42, 0x60, 0x38, 0x3C, 0x1C, 0xC0, 0x00, 0x03, 0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x18, 0x00, }; #define cross_fill_width 24 #define cross_fill_height 24 static const unsigned char cross_fill_bits[] U8X8_PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x64, 0x00, 0x26, 0x84, 0x00, 0x21, 0x08, 0x81, 0x10, 0x08, 0x42, 0x10, 0x10, 0x3C, 0x08, 0x20, 0x00, 0x04, 0x40, 0x00, 0x02, 0x80, 0x00, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x00, 0x01, 0x40, 0x00, 0x02, 0x20, 0x00, 0x04, 0x10, 0x3C, 0x08, 0x08, 0x42, 0x10, 0x08, 0x81, 0x10, 0x84, 0x00, 0x21, 0x64, 0x00, 0x26, 0x18, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; #define cross_block_width 14 #define cross_block_height 14 static const unsigned char cross_block_bits[] U8X8_PROGMEM = { 0xFF, 0x3F, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0xC1, 0x20, 0xC1, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0xFF, 0x3F, }; void u8g2_bitmap_overlay(uint8_t a) { uint8_t frame_size = 28; u8g2.drawStr(0, 0, ""Bitmap overlay""); u8g2.drawStr(0, frame_size + 12, ""Solid / transparent""); u8g2.setBitmapMode(false /* solid */); u8g2.drawFrame(0, 10, frame_size, frame_size); u8g2.drawXBMP(2, 12, cross_width, cross_height, cross_bits); if(a & 4) u8g2.drawXBMP(7, 17, cross_block_width, cross_block_height, cross_block_bits); u8g2.setBitmapMode(true /* transparent*/); u8g2.drawFrame(frame_size + 5, 10, frame_size, frame_size); u8g2.drawXBMP(frame_size + 7, 12, cross_width, cross_height, cross_bits); if(a & 4) u8g2.drawXBMP(frame_size + 12, 17, cross_block_width, cross_block_height, cross_block_bits); } void u8g2_bitmap_modes(uint8_t transparent) { const uint8_t frame_size = 24; u8g2.drawBox(0, frame_size * 0.5, frame_size * 5, frame_size); u8g2.drawStr(frame_size * 0.5, 50, ""Black""); u8g2.drawStr(frame_size * 2, 50, ""White""); u8g2.drawStr(frame_size * 3.5, 50, ""XOR""); if(!transparent) { u8g2.setBitmapMode(false /* solid */); u8g2.drawStr(0, 0, ""Solid bitmap""); } else { u8g2.setBitmapMode(true /* transparent*/); u8g2.drawStr(0, 0, ""Transparent bitmap""); } u8g2.setDrawColor(0);// Black u8g2.drawXBMP(frame_size * 0.5, 24, cross_width, cross_height, cross_bits); u8g2.setDrawColor(1); // White u8g2.drawXBMP(frame_size * 2, 24, cross_width, cross_height, cross_bits); u8g2.setDrawColor(2); // XOR u8g2.drawXBMP(frame_size * 3.5, 24, cross_width, cross_height, cross_bits); } uint8_t draw_state = 0; void draw(void) { u8g2_prepare(); switch(draw_state >> 3) { case 0: u8g2_box_title(draw_state&7); break; case 1: u8g2_box_frame(draw_state&7); break; case 2: u8g2_disc_circle(draw_state&7); break; case 3: u8g2_r_frame(draw_state&7); break; case 4: u8g2_string(draw_state&7); break; case 5: u8g2_line(draw_state&7); break; case 6: u8g2_triangle(draw_state&7); break; case 7: u8g2_ascii_1(); break; case 8: u8g2_ascii_2(); break; case 9: u8g2_extra_page(draw_state&7); break; case 10: u8g2_xor(draw_state&7); break; case 11: u8g2_bitmap_modes(0); break; case 12: u8g2_bitmap_modes(1); break; case 13: u8g2_bitmap_overlay(draw_state&7); break; } } void setup(void) { /* U8g2 Project: SSD1306 Test Board */ pinMode(10, OUTPUT); pinMode(9, OUTPUT); digitalWrite(10, 0); digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); u8g2.begin(); //u8g2.setFlipMode(0); } void loop(void) { // picture loop u8g2.firstPage(); do { draw(); } while( u8g2.nextPage() ); // increase the state draw_state++; if ( draw_state >= 14*8 ) draw_state = 0; // delay between each page delay(150); } ",16140,True,3562.0734723864052,median "/* S&T GeoTronics LLC **** OPEN ENIGMA **** This code is provided as is. S&T GeoTronics LLC, it's Partners and Associates provide it freely, with no warranty of it's functionality, fitness for use or usefulness. In no way shall S&T GeoTronics LLC, it's Partners and Associates be liable for the use, misuse, or damages of any kind due to the use or misuse of this code or any associated hardware provided. Enigma Code. This Arduino Mega custom shield is programmed to replicate exactly the behavior of a true German M4 Enigma machine. It uses 4 16-Segment units, 5 LEDs, 26 Lamps setup as keyboard, 26 keyboard buttons & 10 Function keys. The 115 light emitting diodes are multi-plexed to minimize the amount of pins needed down to 38 and all 36 pushbuttons keys are sharing a total of 4 pins. Designed, assembled & programmed by Marc Tessier & James Sanderson 9/20/13 Modified for our Prototype PCB pair on 12/4/13. Modified to obey doublesteping and have M3 function 22 MAR 14 This code shall remain in public domain as regulated under the creative commons licence. */ // Define the variables unsigned long time = millis(); unsigned long otime = time; int inpin[4] = {A0, A1, A2, A3}; int inval[4] = {0, 0, 0, 0}; int keyval = 100; int kvalo = 100; boolean windex = 0; boolean windex1 = 0; boolean windex2 = 0; int lampval = 100; int procesval = 0; int procesvala = 0; int mode = 0; unsigned long mtime; int mdex =0; int behavior = 1; int plugred = 0; //Define Plug Board Pins int plug[26] = {A14, 49, A12, A15, 7, 53, 50, 52, 3, A6, A4, A11, A9, A10, 8, A7, 6, 4, 51, 10, 9, A5, 5, A8, A13, 2} ; // Define each Nixie character int dig1 = 37; int dig2 = 37; int dig3 = 37; int dig4 = 37; int data[3][40] ={ {36,36,36,36,18,39,19,36,6,4,14,19,17,14,13,8,2,18,36,4,13,8,6,12,0,36,12,0,17,10,36,30,36,13,3,19,36,36,36,36}, {36,36,36,36,18,39,19,36,6,4,14,19,17,14,13,8,2,18,36,4,13,8,6,12,0,36,12,0,17,10,36,30,36,36,3,19,36,36,36,36}, {36,36,36,36,18,39,19,36,6,4,14,19,17,14,13,8,2,18,36,4,13,8,6,12,0,36,12,0,17,10,36,29,36,36,3,19,36,36,36,36} }; // Define the 16-Segments Pins as 2 Arrays int segment[17] = {24,22,25,31,38,36,32,30,28,26,23,27,33,35,34,29,37}; //cathode array int anode[4] = {39,41,43,45}; //annode array commin annode // Define the 26 Lamps as a 2D Array int lamparray[26] [2] = {{12,38},{13,29},{13,33},{12,35},{11,35},{12,33},{12,31},{12,29},{11,25},{12,27}, {12,25},{13,23},{13,25},{13,27},{11,23},{13,38},{11,38},{11,33},{12,37},{11,31}, {11,27},{13,31},{11,37},{13,35},{13,37},{11,29}}; // Define the 12 Lamp Pins for initialization //int lamppin[12] = {2,3,4,5,6,7,8,9,10,11,12,13}; //2 to 10 cathode, 11 to 13 common annode int lamppin[3] = {11,12,13}; // Define each LTP587P Segments: A,B,C,D,E,F,G,H,K,M,N,P,R,S,T,U,dp boolean segmentvals[40][17] = { { 0,0,0,0,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = A 0 { 0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,1,1 }, // = B 1 { 0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = C 2 { 0,0,0,0,0,0,1,1,1,0,1,1,1,0,1,1,1 }, // = D 3 { 0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,0,1 }, // = E 4 { 0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = F 5 { 0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1 }, // = G 6 { 1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = H 7 { 0,0,1,1,0,0,1,1,1,0,1,1,1,0,1,1,1 }, // = I 8 { 1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1 }, // = J 9 { 1,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,1 }, // = K 10 { 1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = L 11 { 1,1,0,0,1,1,0,0,0,1,0,1,1,1,1,1,1 }, // = M 12 { 1,1,0,0,1,1,0,0,0,1,1,1,0,1,1,1,1 }, // = N 13 { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = O 14 { 0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = P 15 { 0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1,1 }, // = Q 16 { 0,0,0,1,1,1,0,0,1,1,1,0,0,1,1,0,1 }, // = R 17 { 0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0,1 }, // = S 18 { 0,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1 }, // = T 19 { 1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = U 20 { 1,1,1,1,1,1,0,0,1,1,0,1,1,1,0,1,1 }, // = V 21 { 1,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,1 }, // = W 22 { 1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1 }, // = X 23 { 1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1 }, // = Y 24 { 0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,1 }, // = Z 25 { 0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,1 }, // = 0 26 { 1,1,0,0,1,1,1,1,1,1,0,1,1,1,1,1,1 }, // = 1 27 { 0,0,0,1,0,0,0,1,1,1,1,0,1,1,1,0,1 }, // = 2 28 { 0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,1,1 }, // = 3 29 { 1,1,0,0,1,1,1,0,1,1,1,0,1,1,1,0,1 }, // = 4 30 { 0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0,1 }, // = 5 31 { 0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,0,1 }, // = 6 32 { 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // = 7 33 { 0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,0,1 }, // = 8 34 { 0,0,0,0,0,0,1,0,1,1,1,0,1,1,1,0,1 }, // = 9 35 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // = Space 36 { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // = Full Lit 37 { 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1 }, // = SS 38 { 0,1,1,1,0,0,0,1,0,0,1,1,0,1,1,0,1} }; // = & 39 // LTP587P Segments: A,B,C,D,E,F,G,H,K,M,N,P,R,S,T,U,dp // Define the 5 Mode LEDs int led1 = 40; int led2 = 42; int led3 = 44; int led4 = 46; int led5 = 48; //4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,23,20,18,15, 0, 8, 1,17, 2, 9 //Define the rotor values A B C D E F G H I J K L M N O P Q static const int rotorvals[12][78] = { { 4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,123,20,18,15, 0, 8, 1,17, 2, 9, 4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,123,20,18,15, 0, 8, 1,17, 2, 9, 4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,123,20,18,15, 0, 8, 1,17, 2, 9 }, // wheel 1 { 0, 9, 3,10,118, 8,17,20,23, 1,11, 7,22,19,12, 2,16, 6,25,13,15,24, 5,21,14, 4, 0, 9, 3,10,118, 8,17,20,23, 1,11, 7,22,19,12, 2,16, 6,25,13,15,24, 5,21,14, 4, 0, 9, 3,10,118, 8,17,20,23, 1,11, 7,22,19,12, 2,16, 6,25,13,15,24, 5,21,14, 4 }, // wheel 2 { 1, 3, 5, 7, 9,11, 2,15,17,19,23,21,25,13,24, 4, 8,22, 6, 0,10,112,20,18,16,14, 1, 3, 5, 7, 9,11, 2,15,17,19,23,21,25,13,24, 4, 8,22, 6, 0,10,112,20,18,16,14, 1, 3, 5, 7, 9,11, 2,15,17,19,23,21,25,13,24, 4, 8,22, 6, 0,10,112,20,18,16,14 }, // wheel 3 { 4,18,14,21,15,25, 9, 0,24,116,20, 8,17, 7,23,11,13, 5,19, 6,10, 3, 2,12,22, 1, 4,18,14,21,15,25, 9, 0,24,116,20, 8,17, 7,23,11,13, 5,19, 6,10, 3, 2,12,22, 1, 4,18,14,21,15,25, 9, 0,24,116,20, 8,17, 7,23,11,13, 5,19, 6,10, 3, 2,12,22, 1 }, // wheel 4 { 21,25, 1,17, 6, 8,19,24,20,15,18, 3,13, 7,11,23, 0,22,12, 9,16,14, 5, 4, 2,110, 21,25, 1,17, 6, 8,19,24,20,15,18, 3,13, 7,11,23, 0,22,12, 9,16,14, 5, 4, 2,110, 21,25, 1,17, 6, 8,19,24,20,15,18, 3,13, 7,11,23, 0,22,12, 9,16,14, 5, 4, 2,110 }, // wheel 5 { 9,15, 6,21,14,20,12, 5,24,16, 1, 4,113, 7,25,17, 3,10, 0,18,23,11, 8, 2,19,122, 9,15, 6,21,14,20,12, 5,24,16, 1, 4,113, 7,25,17, 3,10, 0,18,23,11, 8, 2,19,122, 9,15, 6,21,14,20,12, 5,24,16, 1, 4,113, 7,25,17, 3,10, 0,18,23,11, 8, 2,19,122 }, // wheel 6 { 13,25, 9, 7, 6,17, 2,23,12,24,18,22,101,14,20, 5, 0, 8,21,11,15, 4,10,16, 3,119, 13,25, 9, 7, 6,17, 2,23,12,24,18,22,101,14,20, 5, 0, 8,21,11,15, 4,10,16, 3,119, 13,25, 9, 7, 6,17, 2,23,12,24,18,22,101,14,20, 5, 0, 8,21,11,15, 4,10,16, 3,119 }, // wheel 7 { 5,10,16, 7,19,11,23,14, 2, 1, 9,18,115, 3,25,17, 0,12, 4,22,13, 8,20,24, 6,121, 5,10,16, 7,19,11,23,14, 2, 1, 9,18,115, 3,25,17, 0,12, 4,22,13, 8,20,24, 6,121, 5,10,16, 7,19,11,23,14, 2, 1, 9,18,115, 3,25,17, 0,12, 4,22,13, 8,20,24, 6,121 }, // wheel 8 { 11,4,24,9,21,2,13,8,23,22,15,1,16,12,3,17,19,0,10,25,6,5,20,7,14,18, 11,4,24,9,21,2,13,8,23,22,15,1,16,12,3,17,19,0,10,25,6,5,20,7,14,18, 11,4,24,9,21,2,13,8,23,22,15,1,16,12,3,17,19,0,10,25,6,5,20,7,14,18 }, // Beta { 5,18,14,10,0,13,20,4,17,7,12,1,19,8,24,2,22,11,16,15,25,23,21,6,9,3, 5,18,14,10,0,13,20,4,17,7,12,1,19,8,24,2,22,11,16,15,25,23,21,6,9,3, 5,18,14,10,0,13,20,4,17,7,12,1,19,8,24,2,22,11,16,15,25,23,21,6,9,3 }, // Gamma { 4,13,10,16,0,20,24,22,9,8,2,14,15,1,11,12,3,23,25,21,5,19,7,17,6,18, 4,13,10,16,0,20,24,22,9,8,2,14,15,1,11,12,3,23,25,21,5,19,7,17,6,18, 4,13,10,16,0,20,24,22,9,8,2,14,15,1,11,12,3,23,25,21,5,19,7,17,6,18}, // = UKW-B { 17,3,14,1,9,13,19,10,21,4,7,12,11,5,2,22,25,0,23,6,24,8,15,18,20,16, 17,3,14,1,9,13,19,10,21,4,7,12,11,5,2,22,25,0,23,6,24,8,15,18,20,16, 17,3,14,1,9,13,19,10,21,4,7,12,11,5,2,22,25,0,23,6,24,8,15,18,20,16 } // = UKW-C }; static const int rotorvali[10][78] = { { 20,22,24, 6, 0, 3, 5,15,21,25, 1, 4, 2,10,12,19, 7,23,18,11,17, 8,13,16,14, 9, 20,22,24, 6, 0, 3, 5,15,21,25, 1, 4, 2,10,12,19, 7,23,18,11,17, 8,13,16,14, 9, 20,22,24, 6, 0, 3, 5,15,21,25, 1, 4, 2,10,12,19, 7,23,18,11,17, 8,13,16,14, 9 }, //wheel 1 i // { 0, 9,15, 2,25,22,17,11, 5, 1, 3,10,14,19,24,20,16, 6, 4,13, 7,23,12, 8,21,18, 0, 9,15, 2,25,22,17,11, 5, 1, 3,10,14,19,24,20,16, 6, 4,13, 7,23,12, 8,21,18, 0, 9,15, 2,25,22,17,11, 5, 1, 3,10,14,19,24,20,16, 6, 4,13, 7,23,12, 8,21,18 }, //wheel 2 i { 19, 0, 6, 1,15, 2,18, 3,16, 4,20, 5,21,13,25, 7,24, 8,23, 9,22,11,17,10,14,12, 19, 0, 6, 1,15, 2,18, 3,16, 4,20, 5,21,13,25, 7,24, 8,23, 9,22,11,17,10,14,12, 19, 0, 6, 1,15, 2,18, 3,16, 4,20, 5,21,13,25, 7,24, 8,23, 9,22,11,17,10,14,12 }, //wheel 3 i { 7,25,22,21, 0,17,19,13,11, 6,20,15,23,16, 2, 4, 9,12, 1,18,10, 3,24,14, 8, 5, 7,25,22,21, 0,17,19,13,11, 6,20,15,23,16, 2, 4, 9,12, 1,18,10, 3,24,14, 8, 5, 7,25,22,21, 0,17,19,13,11, 6,20,15,23,16, 2, 4, 9,12, 1,18,10, 3,24,14, 8, 5 }, //wheel 4 i { 16, 2,24,11,23,22, 4,13, 5,19,25,14,18,12,21, 9,20, 3,10, 6, 8, 0,17,15, 7, 1, 16, 2,24,11,23,22, 4,13, 5,19,25,14,18,12,21, 9,20, 3,10, 6, 8, 0,17,15, 7, 1, 16, 2,24,11,23,22, 4,13, 5,19,25,14,18,12,21, 9,20, 3,10, 6, 8, 0,17,15, 7, 1 }, //wheel 5 i { 18,10,23,16,11, 7, 2,13,22, 0,17,21,06,12, 4, 1, 9,15,19,24, 5, 3, 25,20, 8,14, 18,10,23,16,11, 7, 2,13,22, 0,17,21,06,12, 4, 1, 9,15,19,24, 5, 3, 25,20, 8,14, 18,10,23,16,11, 7, 2,13,22, 0,17,21,06,12, 4, 1, 9,15,19,24, 5, 3, 25,20, 8,14 }, //wheel 6 i { 16,12,6,24,21,15,4,3,17,2,22,19,8,0,13,20,23,5,10,25,14,18,11,7,9,1, 16,12,6,24,21,15,4,3,17,2,22,19,8,0,13,20,23,5,10,25,14,18,11,7,9,1, 16,12,6,24,21,15,4,3,17,2,22,19,8,0,13,20,23,5,10,25,14,18,11,7,9,1 }, //wheel 7 i { 16,9,8,13,18,0,24,3,21,10,1,5,17,20,7,12,2,15,11,4,22,25,19,6,23,14, 16,9,8,13,18,0,24,3,21,10,1,5,17,20,7,12,2,15,11,4,22,25,19,6,23,14, 16,9,8,13,18,0,24,3,21,10,1,5,17,20,7,12,2,15,11,4,22,25,19,6,23,14 }, //wheel 8 i { 17,11,5,14,1,21,20,23,7,3,18,0,13,6,24,10,12,15,25,16,22,4,9,8,2,19, 17,11,5,14,1,21,20,23,7,3,18,0,13,6,24,10,12,15,25,16,22,4,9,8,2,19, 17,11,5,14,1,21,20,23,7,3,18,0,13,6,24,10,12,15,25,16,22,4,9,8,2,19 }, //Beta i { 4,11,15,25,7,0,23,9,13,24,3,17,10,5,2,19,18,8,1,12,6,22,16,21,14,20, 4,11,15,25,7,0,23,9,13,24,3,17,10,5,2,19,18,8,1,12,6,22,16,21,14,20, 4,11,15,25,7,0,23,9,13,24,3,17,10,5,2,19,18,8,1,12,6,22,16,21,14,20 } }; //Gamma i // Define a 2D Array for keeping the wheel locations & positions int wheel[4][3] = {{29,0,0},{28,0,0},{27,0,0},{1,0,0}}; int reflect[2] = {1,0}; // Define Array for plugbord values 25 x2 position 0 holds use position 1 holds value int plugu holds the total nomber of plugs used (10 max) int plugval [2][26] = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}}; int pluguse = 0; int paindex = 0; int pbindex = 1; int prindex = 0; int prtindex =0; void setup() { // Initialize all 29 LED pins as Output for (int index = 0; index <= 2; index++) { pinMode(lamppin[index], OUTPUT); digitalWrite(lamppin[index],1); } for (int index = 0 ; index <= 3; index++) { pinMode (anode[index], OUTPUT); digitalWrite (anode[index], 1); } for (int index = 0 ; index <= 16; index++) { pinMode (segment[index], OUTPUT); digitalWrite (segment[index], 1); } pinMode(led1,OUTPUT); pinMode(led2,OUTPUT); pinMode(led3,OUTPUT); pinMode(led4,OUTPUT); pinMode(led5,OUTPUT); //Set Initial Pin Mode For Plug Board Pins for (int index = 0 ; index <= 25; index++) { pinMode (plug[index], INPUT); } Serial.begin(9600); Serial3.begin(19200); delay(500); Serial3.write(29); Serial3.write(33); Serial3.write(0); Serial3.println(""""); Serial3.print("" S&T GeoTronics ENIGMA MARK 5 ""); Serial3.println(""""); Serial3.println(""""); Serial3.println(""""); // Serial3.write(27); // Serial3.write(14); Serial3.write(29); Serial3.write(33); Serial3.write(17); // Initialize all 4 pusbutton pins as Input for (int index = 0; index <= 3; index++) { pinMode(inpin[index], INPUT); } } void loop() { // Keyboard debounce & test for new key pressed time = millis(); if (time > otime + 100) {keyval = readkbde();} if(keyval == kvalo) {windex = 0;} kvalo = keyval; if ((mode == 0) && (keyval == 46) && (windex ==1)){ behavior ++; windex =0; if(behavior > 2) {behavior = 0; } } if((keyval == 45) && (windex ==1)) {modeselect();} // The whole Enigma machine operation revolves around which Operating Mode is current if(mode == 0) {mode0();} else if(mode == 1) {mode1();} else if(mode == 2) {mode2();} else if(mode == 3) {mode3();} else if(mode == 4) {mode4();} else if(mode == 5) {mode5();} else { } Serial.println(keyval); // for debuging prints keybord value to serial monitor// for run or del } // This function takes care of figuring out which key has been pressed & returns a unique Integer int readkbde() { int kval = 100; for (int index = 0; index <= 3; index++) { inval[index] = analogRead(inpin[index]); } //Reads analog input values if((inval[0] > 982) && (inval[1] > 973) && (inval[2] > 966) && (inval[3] > 973)) {kval = 100;} // no key press else if((inval[0] < 981) && (inval[0] > 903)) {kval = 49;} //up arrow 4 else if((inval[0] < 902) && (inval[0] > 831)) {kval = 48;} //up arrow 3 else if((inval[0] < 830) && (inval[0] > 762)) {kval = 47;} //up arrow 2 else if((inval[0] < 761) && (inval[0] > 693)) {kval = 46;} //up arrow 1 else if((inval[0] < 692) && (inval[0] > 622)) {kval = 45;} //mode else if((inval[0] < 621) && (inval[0] > 545)) {kval = 44;} //enter else if((inval[0] < 544) && (inval[0] > 458)) {kval = 43;} else if((inval[0] < 457) && (inval[0] > 358)) {kval = 42;} else if((inval[0] < 357) && (inval[0] > 237)) {kval = 41;} else if(inval[0] < 236 ) {kval = 40;} else if((inval[1] < 972) && (inval[1] > 875)) {kval = 16;} else if((inval[1] < 874) && (inval[1] > 784)) {kval = 22;} else if((inval[1] < 783) && (inval[1] > 696)) {kval = 4;} else if((inval[1] < 695) && (inval[1] > 605)) {kval = 17;} else if((inval[1] < 604) && (inval[1] > 507)) {kval = 19;} else if((inval[1] < 506) && (inval[1] > 395)) {kval = 25;} else if((inval[1] < 394) && (inval[1] > 261)) {kval = 20;} else if((inval[1] < 260) && (inval[1] > 94)) {kval = 8;} else if(inval[1] < 93 ) {kval = 14;} else if((inval[2] < 965) && (inval[2] > 855)) {kval = 0;} else if((inval[2] < 854) && (inval[2] > 752)) {kval = 18;} else if((inval[2] < 751) && (inval[2] > 650)) {kval = 3;} else if((inval[2] < 649) && (inval[2] > 542)) {kval = 5;} else if((inval[2] < 541) && (inval[2] > 421)) {kval = 6;} else if((inval[2] < 420) && (inval[2] > 278)) {kval = 7;} else if((inval[2] < 277) && (inval[2] > 100)) {kval = 9;} else if(inval[2] < 99 ) {kval = 10;} else if((inval[3] < 972) && (inval[3] > 875)) {kval = 15;} else if((inval[3] < 874) && (inval[3] > 784)) {kval = 24;} else if((inval[3] < 783) && (inval[3] > 696)) {kval = 23;} else if((inval[3] < 695) && (inval[3] > 605)) {kval = 2;} else if((inval[3] < 604) && (inval[3] > 507)) {kval = 21;} else if((inval[3] < 506) && (inval[3] > 395)) {kval = 1;} else if((inval[3] < 394) && (inval[3] > 261)) {kval = 13;} else if((inval[3] < 260) && (inval[3] > 94)) {kval = 12;} else if(inval[3] < 93 ) {kval = 11;} else {kval = 100;} if(kval < 99) {otime = millis();} //Starts key debounce timer if((kval >= 0) && (kval <= 99)) {windex = 1;} //windex showing true (1) indicates the return of a fresh key stroke Serial.println(kval); return kval; } // Function to change operating Mode void modeselect() { mode++; if(mode >=6) {mode = 0;} windex = 0; } // Default Mode: Enigma is a Typewriter void mode0() { if((keyval >= 0) && (keyval <= 25)) {lampval = keyval;} else {lampval = 100;} lampita(); delay(3); lampitb(); marquee(); } // Select the Rotors & the Reflector void mode1() { int index; digitalWrite(led1, HIGH); if(windex == 1) {if((keyval == 43) || (keyval == 46)){ if(behavior != 2) {wheel[3][0]++;windex = 0; if (wheel[3][0] > 2) {wheel[3][0] = 1; reflect[0]++; if (reflect[0] > 2) {reflect[0] = 1;}} } else {reflect[0]++; windex = 0; if (reflect[0] > 2) {reflect[0] = 1;} }}} if(windex == 1) {if(keyval == 47) { for(index = wheel[2][0];(index == wheel[1][0]) || (index == wheel[0][0]) || (index == wheel[2][0]); index++) {if(index > 33) {index = 26;} }wheel[2][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 48) { for(index = wheel[1][0];(index == wheel[2][0]) || (index == wheel[0][0]) || (index == wheel[1][0]); index++) {if(index > 33) {index = 26;} }wheel[1][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 49) { for(index = wheel[0][0];(index == wheel[2][0]) || (index == wheel[1][0]) || (index == wheel[0][0]); index++) {if(index > 33) {index = 26;} }wheel[0][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 42) { for(index = wheel[2][0];(index == wheel[1][0]) || (index == wheel[0][0]) || (index == wheel[2][0]); index--) {if(index < 28) {index = 35;} }wheel[2][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 41) { for(index = wheel[1][0];(index == wheel[2][0]) || (index == wheel[0][0]) || (index == wheel[1][0]); index--) {if(index < 28) {index = 35;} }wheel[1][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 40) { for(index = wheel[0][0];(index == wheel[2][0]) || (index == wheel[1][0]) || (index == wheel[0][0]); index--) {if(index < 28) {index = 35;} }wheel[0][0] = index; windex = 0;}} dig2 = wheel[2][0]; dig3 = wheel[1][0]; dig4 = wheel[0][0]; if(behavior != 2) { if( wheel[3][0] == 1 ) { dig1 = 1;} else {dig1 = 6;}} else{ dig1 = 36;} lampval = reflect[0]; lampita(); delay(3); lampitb(); nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led1, LOW); } // Position the Inner setting of each Rotor void mode2() { digitalWrite(led2, HIGH); if(windex == 1){ if(behavior != 2) { if(keyval == 46) {wheel[3][1]++; if(wheel[3][1] > 25) {wheel[3][1] = 0;}}} if(keyval == 47) {wheel[2][1]++; if(wheel[2][1] > 25) {wheel[2][1] = 0;}} if(keyval == 48) {wheel[1][1]++; if(wheel[1][1] > 25) {wheel[1][1] = 0;}} if(keyval == 49) {wheel[0][1]++; if(wheel[0][1] > 25) {wheel[0][1] = 0;}} if(behavior != 2) {if(keyval == 43) {wheel[3][1]--; if(wheel[3][1] < 0) {wheel[3][1] = 25;}}} if(keyval == 42) {wheel[2][1]--; if(wheel[2][1] < 0) {wheel[2][1] = 25;}} if(keyval == 41) {wheel[1][1]--; if(wheel[1][1] < 0) {wheel[1][1] = 25;}} if(keyval == 40) {wheel[0][1]--; if(wheel[0][1] < 0) {wheel[0][1] = 25;}} windex = 0; } dig2 = wheel[2][1]; dig3 = wheel[1][1]; dig4 = wheel[0][1]; if(behavior != 2) {dig1 =wheel[3][1];} else {dig1 = 36;} nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led2, LOW); } // Position the Start character of each Wheel void mode3() { digitalWrite(led3, HIGH); if(windex == 1){ if(behavior != 2) { if(keyval == 46) {wheel[3][2]++; if(wheel[3][2] > 25) {wheel[3][2] = 0;}}} // {reflect[1]++; if(reflect[1] > 25) {reflect[1] = 0;}}} if(keyval == 47) {wheel[2][2]++; if(wheel[2][2] > 25) {wheel[2][2] = 0;}} if(keyval == 48) {wheel[1][2]++; if(wheel[1][2] > 25) {wheel[1][2] = 0;}} if(keyval == 49) {wheel[0][2]++; if(wheel[0][2] > 25) {wheel[0][2] = 0;}} if(behavior != 2) {if(keyval == 43) {wheel[3][2]--; if(wheel[3][2] < 0) {wheel[3][2] = 25;}}} // {reflect[1]--; if(reflect[1] < 0) {reflect[1] = 25;}}} if(keyval == 42) {wheel[2][2]--; if(wheel[2][2] < 0) {wheel[2][2] = 25;}} if(keyval == 41) {wheel[1][2]--; if(wheel[1][2] < 0) {wheel[1][2] = 25;}} if(keyval == 40) {wheel[0][2]--; if(wheel[0][2] < 0) {wheel[0][2] = 25;}} windex = 0; } dig2 = wheel[2][2]; dig3 = wheel[1][2]; dig4 = wheel[0][2]; dig1 = wheel[3][2]; if (behavior == 2) {dig1 = 36;} nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led3, LOW); } // Define the Plugboard pairs void mode4() { if(plugred == 0) {readplugs(); } int index = 0; digitalWrite(led4, HIGH); if(pluguse <= 9) { if(plugval[0][paindex] == 1) {for(index = paindex;(index == paindex) || (index == pbindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} paindex = index;} if(plugval[0][pbindex] == 1) {for(index = pbindex;(index == pbindex) || (index == paindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} pbindex = index;} if(windex == 1) { if(keyval == 46) { for(index = paindex;(index == paindex) || (index == pbindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} paindex = index; windex = 0; } if(keyval == 43) { for(index = paindex;(index == paindex) || (index == pbindex) || (plugval[0][index] == 1); index--) {if(index < 1) {index = 26;}} paindex = index; windex = 0; } if(keyval == 49) { for(index = pbindex;(index == pbindex) || (index == paindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} pbindex = index; windex = 0; } if(keyval == 40) { for(index = pbindex;(index == pbindex) || (index == paindex) || (plugval[0][index] == 1); index--) {if(index < 1) {index = 26;}} pbindex = index; windex = 0; } if(keyval == 44) { plugval[0][paindex] = 1; plugval[1][paindex] = pbindex; plugval[0][pbindex] = 1; plugval[1][pbindex] = paindex; windex = 0; pluguse++;} } dig2 = 19; dig3 = 14; dig4 = pbindex; dig1 = paindex; nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; } else {done();} digitalWrite(led4, LOW); } // This is Normal Operation Mode to Encrypt/Decrypt void mode5() { int pv = 0; digitalWrite(led5, HIGH); if(keyval >= 26) {lampval = 100;} else { int windexb = windex; if((keyval >= 0) && (keyval <= 25)) { if(windex == 1){procesvala = keyval; indexwheels();}} procesval = procesvala; procesval = plugval[1][procesval]; // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[0][2] - wheel[0][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[0][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[0][2] - wheel[0][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[1][2] - wheel[1][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[1][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[1][2] - wheel[1][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[2][2] - wheel[2][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[2][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[2][2] - wheel[2][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[3][2] - wheel[3][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[3][0] +7][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[3][2] - wheel[3][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); procesval = rotorvals[reflect[0] + 9][procesval]; //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[3][2] - wheel[3][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[3][0] +7][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[3][2] - wheel[3][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[2][2] - wheel[2][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[2][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[2][2] - wheel[2][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[1][2] - wheel[1][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[1][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[1][2] - wheel[1][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[0][2] - wheel[0][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[0][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[0][2] - wheel[0][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); procesval = plugval[1][procesval]; if(windexb == 1) { Serial3.write(procesval + 65); prindex ++; if(prindex > 3) {Serial3.print("" ""); prtindex ++; prindex = 0; } if(prtindex > 2) {Serial3.println(""""); Serial3.println(""""); prtindex = 0;} } lampval = procesval; } windex = 0; //Serial.println(lampval); dig2 = wheel[2][2]; dig3 = wheel[1][2]; dig4 = wheel[0][2]; dig1 = wheel[3][2]; if (behavior == 2) {dig1 = 36;} lampita(); delay(3); lampitb(); nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led5, LOW); } // Helper Function to light the proper key void lampita() { if(lampval <= 25) { digitalWrite(lamparray[lampval][0],0); digitalWrite(lamparray[lampval][1],0); delay(1); }} void lampitb(){ if(lampval <= 25) { digitalWrite(lamparray[lampval][0],1); digitalWrite(lamparray[lampval][1],1); }} // Help Function to illuminate ""Nixies"" void nixisend() { sixteenSegWrite(0, dig1); sixteenSegWrite(1, dig2); sixteenSegWrite(2, dig3); sixteenSegWrite(3, dig4); } void marquee() { time = millis(); if( mtime < time) { mtime = time + 400; mdex++;} dig1 = data[behavior][mdex]; dig2 = data[behavior][mdex + 1]; dig3 = data[behavior][mdex + 2]; dig4 = data[behavior][mdex + 3]; if (mdex >= 35) {mdex = 0;} nixisend(); } // Function that actually turns on each of 17 appropriate segments on each ""Nixie"" void sixteenSegWrite(int digit, int character) { digitalWrite(anode[digit],0); for (int index = 0; index < 17; index++) { digitalWrite(segment[index], segmentvals[character][index]); } delay(3); for (int index =0; index <= 16; index++) { digitalWrite(segment[index], 1); } digitalWrite(anode[digit], 1); } void done() { dig1 = 3; dig2 = 14; dig3 = 13; dig4 = 4; nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; } void indexwheels() { if (behavior > 0){ if(rotorvals[wheel[1][0]-27][wheel[1][2]] >= 100) {windex1 = 1;if (behavior < 2) { windex2 = 1;}}} // Serial.print(rotorvals[wheel[0][0]-27][wheel[0][2]]); // Serial.print("" ""); Serial.print(wheel[0][0]-27); Serial.print("" ""); Serial.println(wheel[0][2]); if(rotorvals[wheel[0][0]-27][wheel[0][2]] >= 100) {windex1 = 1;} wheel[0][2]++; if(wheel[0][2] > 25) {wheel[0][2] = 0;} windex = 0; if(windex1 == 1){ if(rotorvals[wheel[1][0]-27][wheel[1][2]] >= 100) {windex2 = 1;} wheel[1][2]++; if(wheel[1][2] > 25) {wheel[1][2] = 0;}} windex1 = 0; if(windex2 == 1){ wheel[2][2]++; if(wheel[2][2] > 25) {wheel[2][2] = 0;} windex2 = 0; } } void readplugs() { for (int index = 0 ; index <= 24; index++) { pinMode(plug[index], OUTPUT); digitalWrite(plug[index], LOW); for (int indexb = (index +1); indexb <= 25; indexb++) { int plugvar = digitalRead(plug[indexb]); if (plugvar == 0) { pluguse ++; plugval[0] [index] = 1; plugval[0] [indexb] = 1; plugval[1] [index] = indexb; plugval[1] [indexb] = index; } } pinMode(plug[index], INPUT); } plugred = 1; } ",16301,True,2565.4097005089025,median "/* Weather.ino Demonstrates: - Weather icons from open-iconic set. - Text scrolling. - Partial screen update This example requires display height >= 64. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list #define SUN 0 #define SUN_CLOUD 1 #define CLOUD 2 #define RAIN 3 #define THUNDER 4 void drawWeatherSymbol(u8g2_uint_t x, u8g2_uint_t y, uint8_t symbol) { // fonts used: // u8g2_font_open_iconic_embedded_6x_t // u8g2_font_open_iconic_weather_6x_t // encoding values, see: https://github.com/olikraus/u8g2/wiki/fntgrpiconic switch(symbol) { case SUN: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 69); break; case SUN_CLOUD: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 65); break; case CLOUD: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 64); break; case RAIN: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 67); break; case THUNDER: u8g2.setFont(u8g2_font_open_iconic_embedded_6x_t); u8g2.drawGlyph(x, y, 67); break; } } void drawWeather(uint8_t symbol, int degree) { drawWeatherSymbol(0, 48, symbol); u8g2.setFont(u8g2_font_logisoso32_tf); u8g2.setCursor(48+3, 42); u8g2.print(degree); u8g2.print(""°C""); // requires enableUTF8Print() } /* Draw a string with specified pixel offset. The offset can be negative. Limitation: The monochrome font with 8 pixel per glyph */ void drawScrollString(int16_t offset, const char *s) { static char buf[36]; // should for screen with up to 256 pixel width size_t len; size_t char_offset = 0; u8g2_uint_t dx = 0; size_t visible = 0; u8g2.setDrawColor(0); // clear the scrolling area u8g2.drawBox(0, 49, u8g2.getDisplayWidth()-1, u8g2.getDisplayHeight()-1); u8g2.setDrawColor(1); // set the color for the text len = strlen(s); if ( offset < 0 ) { char_offset = (-offset)/8; dx = offset + char_offset*8; if ( char_offset >= u8g2.getDisplayWidth()/8 ) return; visible = u8g2.getDisplayWidth()/8-char_offset+1; strncpy(buf, s, visible); buf[visible] = '\\0'; u8g2.setFont(u8g2_font_8x13_mf); u8g2.drawStr(char_offset*8-dx, 62, buf); } else { char_offset = offset / 8; if ( char_offset >= len ) return; // nothing visible dx = offset - char_offset*8; visible = len - char_offset; if ( visible > u8g2.getDisplayWidth()/8+1 ) visible = u8g2.getDisplayWidth()/8+1; strncpy(buf, s+char_offset, visible); buf[visible] = '\\0'; u8g2.setFont(u8g2_font_8x13_mf); u8g2.drawStr(-dx, 62, buf); } } void draw(const char *s, uint8_t symbol, int degree) { int16_t offset = -(int16_t)u8g2.getDisplayWidth(); int16_t len = strlen(s); u8g2.clearBuffer(); // clear the internal memory drawWeather(symbol, degree); // draw the icon and degree only once for(;;) // then do the scrolling { drawScrollString(offset, s); // no clearBuffer required, screen will be partially cleared here u8g2.sendBuffer(); // transfer internal memory to the display delay(20); offset+=2; if ( offset > len*8+1 ) break; } } void setup(void) { /* U8g2 Project: SSD1306 Test Board */ pinMode(10, OUTPUT); pinMode(9, OUTPUT); digitalWrite(10, 0); digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); u8g2.enableUTF8Print(); } void loop(void) { draw(""What a beautiful day!"", SUN, 27); draw(""The sun's come out!"", SUN_CLOUD, 19); draw(""It's raining cats and dogs."", RAIN, 8); draw(""That sounds like thunder."", THUNDER, 12); draw(""It's stopped raining"", CLOUD, 15); } ",16372,True,4594.158388240772,median "////// Custom heart charactor byte heart[8] = { 0b01010, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000 }; ////////////////////////////// Player 1 Paddle Characters ////////////////////////////////// byte Apaddle1[8] = { 0b10000, 0b10110, 0b10110, 0b01010, 0b00111, 0b00111, 0b00111, 0b00000 }; byte Apaddle2[8] = { 0b00000, 0b10000, 0b10110, 0b10110, 0b01010, 0b00111, 0b00111, 0b00111 }; byte Apaddle3[8] = { 0b00000, 0b00000, 0b10000, 0b10110, 0b10110, 0b01010, 0b00111, 0b00111 }; byte Apaddle4[8] = { 0b00000, 0b00000, 0b00000, 0b10000, 0b10110, 0b10110, 0b01010, 0b00111 }; byte Apaddle5[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10110, 0b10110, 0b01010 }; byte Apaddle6[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10110, 0b10110 }; byte Apaddle7a[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b10110 }; byte Apaddle7b[8] = { 0b10110, 0b01010, 0b00111, 0b00111, 0b00111, 0b00000, 0b00000, 0b00000 }; byte Apaddle8a[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000 }; byte Apaddle8b[8] = { 0b10110, 0b10110, 0b01010, 0b00111, 0b00111, 0b00111, 0b00000, 0b00000 }; ////////////////////////////// Player 2 Paddle Characters ////////////////////////////////// byte Bpaddle1[8] = { 0b00001, 0b01101, 0b01101, 0b01010, 0b11100, 0b11100, 0b11100, 0b00000 }; byte Bpaddle2[8] = { 0b00000, 0b00001, 0b01101, 0b01101, 0b01010, 0b11100, 0b11100, 0b11100 }; byte Bpaddle3[8] = { 0b00000, 0b00000, 0b00001, 0b01101, 0b01101, 0b01010, 0b11100, 0b11100 }; byte Bpaddle4[8] = { 0b00000, 0b00000, 0b00000, 0b00001, 0b01101, 0b01101, 0b01010, 0b11100 }; byte Bpaddle5[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b01101, 0b01101, 0b01010 }; byte Bpaddle6[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b01101, 0b01101 }; byte Bpaddle7a[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b01101 }; byte Bpaddle7b[8] = { 0b01101, 0b01010, 0b11100, 0b11100, 0b11100, 0b00000, 0b00000, 0b00000 }; byte Bpaddle8a[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001 }; byte Bpaddle8b[8] = { 0b01101, 0b01101, 0b01010, 0b11100, 0b11100, 0b11100, 0b00000, 0b00000 }; /////////////////////////// Ball Characters ////////////////////////////////// // Row 1, Each Column byte ball00[8] = { 0b10000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball01[8] = { 0b01000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball02[8] = { 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball03[8] = { 0b00010, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball04[8] = { 0b00001, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; // Row 2, Each Column byte ball10[8] = { 0b00000, 0b10000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball11[8] = { 0b00000, 0b01000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball12[8] = { 0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball13[8] = { 0b00000, 0b00010, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball14[8] = { 0b00000, 0b00001, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; // Row 3, Each Column byte ball20[8] = { 0b00000, 0b00000, 0b10000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball21[8] = { 0b00000, 0b00000, 0b01000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball22[8] = { 0b00000, 0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball23[8] = { 0b00000, 0b00000, 0b00010, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball24[8] = { 0b00000, 0b00000, 0b00001, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; // Row 4, Each Column byte ball30[8] = { 0b00000, 0b00000, 0b00000, 0b10000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball31[8] = { 0b00000, 0b00000, 0b00000, 0b01000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball32[8] = { 0b00000, 0b00000, 0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball33[8] = { 0b00000, 0b00000, 0b00000, 0b00010, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball34[8] = { 0b00000, 0b00000, 0b00000, 0b00001, 0b00000, 0b00000, 0b00000, 0b00000 }; // Row 5, Each Column byte ball40[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b00000, 0b00000, 0b00000 }; byte ball41[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b01000, 0b00000, 0b00000, 0b00000 }; byte ball42[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, 0b00000, 0b00000, 0b00000 }; byte ball43[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00010, 0b00000, 0b00000, 0b00000 }; byte ball44[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b00000, 0b00000, 0b00000 }; // Row 6, Each Column byte ball50[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b00000, 0b00000 }; byte ball51[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01000, 0b00000, 0b00000 }; byte ball52[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, 0b00000, 0b00000 }; byte ball53[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00010, 0b00000, 0b00000 }; byte ball54[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b00000, 0b00000 }; // Row 7, Each Column byte ball60[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000, 0b00000 }; byte ball61[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01000, 0b00000 }; byte ball62[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, 0b00000 }; byte ball63[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00010, 0b00000 }; byte ball64[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001, 0b00000 }; // Row 8, Each Column byte ball70[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10000 }; byte ball71[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01000 }; byte ball72[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100 }; byte ball73[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00010 }; byte ball74[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00001 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // include the library: #include // LCD setup LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Arduino I/O Pins const int buttonUPP1 = 8; // Player one UP button Pin const int buttonDOWNP1 = 10; // Player one DOWN button Pin const int buttonUPP2 = 6; // Player two UP button Pin const int buttonDOWNP2 = 7; // Player two DOWN button Pin // Globals Variables int paddlePosP1 = 7; // Position of the player One paddle (initialized to middle pos of LCD) (14 possible positions) int paddlePosP2 = 7; // Position of the player Two paddle (initialized to middle pos of LCD) (14 possible positions) int upDownDir; // Up and Down Direction of the Ball int leftRightDir; // Left and Right Direction of the Ball int ballPos[2]; // X, Y coordinates of the ball int pointsP1; // Player One Score (3 is Maximum) int pointsP2; // Player Two Score (3 is Maximum) float distance; // Distance between successive positions of the ball in LCD float totalDistance; // Total distance from the ball's last boundary deflection point, this is used to properly calculate the ball's trajectory int angle; // Angle with respect to the horizontal (X) axis where the ball is moving float YaxisAngle; // Clockwise angle from the Vertical (Y) axis where the ball is moving boolean gameState; // Game State float difficultyPercent = 10; // Speed increase percentage when the player successfully hits the ball off their paddle int minAngle = 10; // Min trajectory angle for the ball int maxAngle = 50; // Max trajectory angle for the ball float initialDist = 1.0; // Initial Distance value that is used at the start of a game void setup() { gameState = false; // set up the lcd's number of columns and rows(16*2): lcd.begin(16, 2); // set buttons as input pinMode(buttonUPP1, INPUT); pinMode(buttonDOWNP1, INPUT); pinMode(buttonUPP2, INPUT); pinMode(buttonDOWNP2, INPUT); // calculate an initial trajectory angle for the ball startDir(); // set the ball's initial position to centre screen ballPos[0] = 39; ballPos[1] = 7; // initialize control variables to EASY Level Style distance = initialDist; totalDistance = distance; pointsP1 = 0; pointsP2 = 0; // clearing the LCD display lcd.clear(); Level(); } void loop() { // checks the game status if (gameState == true) // Game is started { Updateball(); // Updates the ball's position if (gameState == true) { playerPaddleUpdate(); // Updates the player's paddle position } delay(100); } } void Level() { String difficulty = ""No_Level""; int I = 0; String level[3] = { "" EASY "" ,"" MEDIUM "", "" HARD "" }; do { lcd.setCursor(0, 0); lcd.print(""ChooseDifficulty""); lcd.setCursor(0, 1); if (digitalRead(buttonUPP1) == HIGH) { I--; if (I < 0) I = 0; } else if (digitalRead(buttonDOWNP1) == HIGH) { I++; if (I > 2) I = 2; } lcd.print(level[I]); if (digitalRead(buttonUPP2) == HIGH || digitalRead(buttonDOWNP2) == HIGH) { difficulty = level[I]; if (difficulty == level[0]) { initialDist = 1.0; difficultyPercent = 10; } else if (difficulty == level[1]) { initialDist = 1.0; difficultyPercent = 30; } else if (difficulty == level[2]) { initialDist = 1.0; difficultyPercent = 50; } // Start a game (toggle game state) and Draw the game Scene gameState = true; Draw(); } } while (difficulty == ""No_Level""); } // Function for drawing the game Scene void Draw() { lcd.clear(); // Draw the ball in it's center position lcd.createChar(2, ball04); lcd.setCursor(7, 1); lcd.write(2); delay(250); } // Function for determining the ball's propagating angle void startDir() { // randomly get a 1 or -1 for the up or down and left or right directions and the ball's angle of travel from the X axis upDownDir = 0; leftRightDir = 0; while (upDownDir == 0) { upDownDir = random(-1, 2); } while (leftRightDir == 0) { leftRightDir = random(-1, 2); } // Randomly grab a game angle between Min and Max values randomSeed(analogRead(1)); angle = random(minAngle, maxAngle + 1); } //Updates the player's paddle position void playerPaddleUpdate() { // read the control buttons for paddle position int UPbtnP1 = digitalRead(buttonUPP1); int DOWNbtnP1 = digitalRead(buttonDOWNP1); int UPbtnP2 = digitalRead(buttonUPP2); int DOWNbtnP2 = digitalRead(buttonDOWNP2); // Updating paddle position for Player 1 and Player 2 (14 possible paddle positions) if (UPbtnP1 == HIGH) { paddlePosP1++; paddlePosP1 = constrain(paddlePosP1, 1, 14); //clear the P1 paddle lcd.setCursor(15, 0); lcd.print("" ""); lcd.setCursor(15, 1); lcd.print("" ""); } if (DOWNbtnP1 == HIGH) { paddlePosP1--; paddlePosP1 = constrain(paddlePosP1, 1, 14); //clear the P1 paddle lcd.setCursor(15, 0); lcd.print("" ""); lcd.setCursor(15, 1); lcd.print("" ""); } if (UPbtnP2 == HIGH) { paddlePosP2++; paddlePosP2 = constrain(paddlePosP2, 1, 14); //clear the P2 paddle lcd.setCursor(0, 0); lcd.print("" ""); lcd.setCursor(0, 1); lcd.print("" ""); } if (DOWNbtnP2 == HIGH) { paddlePosP2--; paddlePosP2 = constrain(paddlePosP2, 1, 14); //clear the P2 paddle lcd.setCursor(0, 0); lcd.print("" ""); lcd.setCursor(0, 1); lcd.print("" ""); } //draw new paddle for player 1 position using the correct custom LCD characters if (paddlePosP1 == 1) { lcd.createChar(6, Apaddle6); lcd.setCursor(15, 1); lcd.write(6); } else if (paddlePosP1 == 2) { lcd.createChar(7, Apaddle5); lcd.setCursor(15, 1); lcd.write(7); } else if (paddlePosP1 == 3) { lcd.createChar(6, Apaddle4); lcd.setCursor(15, 1); lcd.write(6); } else if (paddlePosP1 == 4) { lcd.createChar(7, Apaddle3); lcd.setCursor(15, 1); lcd.write(7); } else if (paddlePosP1 == 5) { lcd.createChar(6, Apaddle2); lcd.setCursor(15, 1); lcd.write(6); } else if (paddlePosP1 == 6) { lcd.createChar(7, Apaddle1); lcd.setCursor(15, 1); lcd.write(7); } else if (paddlePosP1 == 7) { lcd.createChar(6, Apaddle8a); lcd.setCursor(15, 0); lcd.write(6); lcd.createChar(7, Apaddle8b); lcd.setCursor(15, 1); lcd.write(7); } else if (paddlePosP1 == 8) { lcd.createChar(6, Apaddle7a); lcd.setCursor(15, 0); lcd.write(6); lcd.createChar(7, Apaddle7b); lcd.setCursor(15, 1); lcd.write(7); } else if (paddlePosP1 == 9) { lcd.createChar(6, Apaddle6); lcd.setCursor(15, 0); lcd.write(6); } else if (paddlePosP1 == 10) { lcd.createChar(7, Apaddle5); lcd.setCursor(15, 0); lcd.write(7); } else if (paddlePosP1 == 11) { lcd.createChar(6, Apaddle4); lcd.setCursor(15, 0); lcd.write(6); } else if (paddlePosP1 == 12) { lcd.createChar(7, Apaddle3); lcd.setCursor(15, 0); lcd.write(7); } else if (paddlePosP1 == 13) { lcd.createChar(6, Apaddle2); lcd.setCursor(15, 0); lcd.write(6); } else if (paddlePosP1 == 14) { lcd.createChar(7, Apaddle1); lcd.setCursor(15, 0); lcd.write(7); } //draw new paddle position for player 2 using the correct custom LCD characters if (paddlePosP2 == 1) { lcd.createChar(0, Bpaddle6); lcd.setCursor(0, 1); lcd.write((uint8_t)0); } else if (paddlePosP2 == 2) { lcd.createChar(1, Bpaddle5); lcd.setCursor(0, 1); lcd.write(1); } else if (paddlePosP2 == 3) { lcd.createChar(0, Bpaddle4); lcd.setCursor(0, 1); lcd.write((uint8_t)0); } else if (paddlePosP2 == 4) { lcd.createChar(1, Bpaddle3); lcd.setCursor(0, 1); lcd.write(1); } else if (paddlePosP2 == 5) { lcd.createChar(0, Bpaddle2); lcd.setCursor(0, 1); lcd.write((uint8_t)0); } else if (paddlePosP2 == 6) { lcd.createChar(1, Bpaddle1); lcd.setCursor(0, 1); lcd.write(1); } else if (paddlePosP2 == 7) { lcd.createChar(0, Bpaddle8a); lcd.setCursor(0, 0); lcd.write((uint8_t)0); lcd.createChar(1, Bpaddle8b); lcd.setCursor(0, 1); lcd.write(1); } else if (paddlePosP2 == 8) { lcd.createChar(0, Bpaddle7a); lcd.setCursor(0, 0); lcd.write((uint8_t)0); lcd.createChar(1, Bpaddle7b); lcd.setCursor(0, 1); lcd.write(1); } else if (paddlePosP2 == 9) { lcd.createChar(0, Bpaddle6); lcd.setCursor(0, 0); lcd.write((uint8_t)0); } else if (paddlePosP2 == 10) { lcd.createChar(1, Bpaddle5); lcd.setCursor(0, 0); lcd.write(1); } else if (paddlePosP2 == 11) { lcd.createChar(0, Bpaddle4); lcd.setCursor(0, 0); lcd.write((uint8_t)0); } else if (paddlePosP2 == 12) { lcd.createChar(1, Bpaddle3); lcd.setCursor(0, 0); lcd.write(1); } else if (paddlePosP2 == 13) { lcd.createChar(0, Bpaddle2); lcd.setCursor(0, 0); lcd.write((uint8_t)0); } else if (paddlePosP2 == 14) { lcd.createChar(1, Bpaddle1); lcd.setCursor(0, 0); lcd.write(1); } } // Function for updating the ball's position on the LCD(16*2) screen using one of 40 possible custom characters void Updateball() { int i; // Calculate the YaxisAngle of the ball's game angle (trajectory angle) if (upDownDir == 1 && leftRightDir == -1) { YaxisAngle = 90 - angle; } else if (upDownDir == -1 && leftRightDir == -1) { YaxisAngle = 90 + angle; } else if (upDownDir == -1 && leftRightDir == 1) { YaxisAngle = 270 - angle; } else { YaxisAngle = 270 + angle; } // Convert degrees to radians YaxisAngle = YaxisAngle * PI / 180.0; //Sin and Cos Functions draw the new pos for ball using ball's last deflection point along with total distance to better display the true game angle) int newX = sin(YaxisAngle) * totalDistance + (float)ballPos[0]; int newY = cos(YaxisAngle) * totalDistance + (float)ballPos[1]; int P = 0; // flag variable for p1 and p2 // Constrain the ball's position to be on the game Scene newX = constrain(newX, 5, 75); newY = constrain(newY, 0, 15); // Update the total distance between the ball and it's last deflection (bounce) point within the game totalDistance = totalDistance + distance; // Check if the ball has hit a top or bottom boundary if (newY == 0) // Hits the Bottom { upDownDir = 1; totalDistance = distance; ballPos[0] = newX; ballPos[1] = newY + 1; } else if (newY == 15) // Hits the Top { upDownDir = -1; totalDistance = distance; ballPos[0] = newX; ballPos[1] = newY - 1; } // Check if the ball has hit a left or right boundary and if so update it's Left/Right state value else if (newX == 5) // Hit the player 1's boundary { P = -1; // Speed up the ball each time it hit's the player's paddle distance = (1.0 + difficultyPercent / 100.0) * distance; // Check to see if the Collision has happened of ball and paddle if (newY == 0 && (paddlePosP2 == 1 || paddlePosP2 == 2)) { CollisionUpdate(newX, newY, P); } else if (newY == 1 && (paddlePosP2 == 1 || paddlePosP2 == 2 || paddlePosP2 == 3)) { CollisionUpdate(newX, newY, P); } else if (newY == 2 && (paddlePosP2 == 1 || paddlePosP2 == 2 || paddlePosP2 == 3 || paddlePosP2 == 4)) { CollisionUpdate(newX, newY, P); } else if (newY == 3 && (paddlePosP2 == 1 || paddlePosP2 == 2 || paddlePosP2 == 3 || paddlePosP2 == 4 || paddlePosP2 == 5)) { CollisionUpdate(newX, newY, P); } else if (newY == 4 && (paddlePosP2 == 2 || paddlePosP2 == 3 || paddlePosP2 == 4 || paddlePosP2 == 5 || paddlePosP2 == 6)) { CollisionUpdate(newX, newY, P); } else if (newY == 5 && (paddlePosP2 == 3 || paddlePosP2 == 4 || paddlePosP2 == 5 || paddlePosP2 == 6 || paddlePosP2 == 7)) { CollisionUpdate(newX, newY, P); } else if (newY == 6 && (paddlePosP2 == 4 || paddlePosP2 == 5 || paddlePosP2 == 6 || paddlePosP2 == 7 || paddlePosP2 == 8)) { CollisionUpdate(newX, newY, P); } else if (newY == 7 && (paddlePosP2 == 5 || paddlePosP2 == 6 || paddlePosP2 == 7 || paddlePosP2 == 8 || paddlePosP2 == 9)) { CollisionUpdate(newX, newY, P); } else if (newY == 8 && (paddlePosP2 == 6 || paddlePosP2 == 7 || paddlePosP2 == 8 || paddlePosP2 == 9 || paddlePosP2 == 10)) { CollisionUpdate(newX, newY, P); } else if (newY == 9 && (paddlePosP2 == 7 || paddlePosP2 == 8 || paddlePosP2 == 9 || paddlePosP2 == 10 || paddlePosP2 == 11)) { CollisionUpdate(newX, newY, P); } else if (newY == 10 && (paddlePosP2 == 8 || paddlePosP2 == 9 || paddlePosP2 == 10 || paddlePosP2 == 11 || paddlePosP2 == 12)) { CollisionUpdate(newX, newY, P); } else if (newY == 11 && (paddlePosP2 == 9 || paddlePosP2 == 10 || paddlePosP2 == 11 || paddlePosP2 == 12 || paddlePosP2 == 13)) { CollisionUpdate(newX, newY, P); } else if (newY == 12 && (paddlePosP2 == 10 || paddlePosP2 == 11 || paddlePosP2 == 12 || paddlePosP2 == 13 || paddlePosP2 == 14)) { CollisionUpdate(newX, newY, P); } else if (newY == 13 && (paddlePosP2 == 11 || paddlePosP2 == 12 || paddlePosP2 == 13 || paddlePosP2 == 14)) { CollisionUpdate(newX, newY, P); } else if (newY == 14 && (paddlePosP2 == 12 || paddlePosP2 == 13 || paddlePosP2 == 14)) { CollisionUpdate(newX, newY, P); } else if (newY == 15 && (paddlePosP2 == 13 || paddlePosP2 == 14)) { CollisionUpdate(newX, newY, P); } // The ball has crossed the player's boundary else { pointsP1++; lcd.clear(); lcd.setCursor(7, 0); lcd.print(""P1 :""); lcd.setCursor(7, 1); lcd.print(""P2 :""); // A point has been scored lcd.createChar(2, heart); lcd.setCursor(11, 1); for (i = 0; i < (3 - pointsP1); i++) { lcd.write(2); } lcd.setCursor(11, 0); for (i = 0; i < (3 - pointsP2); i++) { lcd.write(2); } delay(2000); lcd.clear(); //Reset the ball's position and control variables for the next point ballPos[0] = 39; ballPos[1] = 7; totalDistance = distance = initialDist; Draw(); // Determine a new game angle for this point startDir(); // Game is over, 3 points have been scored by the Player 1, reset the LCD to display the Start Game message if (pointsP1 == 3) { gameState = false; // Display Game Over Message and prints Player 2 Victory lcd.clear(); lcd.setCursor(0, 0); lcd.print(""!!!GAME OVER!!!""); delay(500); lcd.clear(); lcd.setCursor(0, 0); lcd.print("" P2 WINS ""); lcd.setCursor(0, 1); lcd.print("" Hold key ""); PlayAnim(); // Call setup to start the game over setup(); } } } else if (newX == 75) // Hit the player 1's boundary { P = 1; // Speed up the ball each time it hit's the player's paddle distance = (1.0 + difficultyPercent / 100.0) * distance; // Check to see if the Collision has happened of ball and paddle if (newY == 0 && (paddlePosP1 == 1 || paddlePosP1 == 2)) { CollisionUpdate(newX, newY, P); } else if (newY == 1 && (paddlePosP1 == 1 || paddlePosP1 == 2 || paddlePosP1 == 3)) { CollisionUpdate(newX, newY, P); } else if (newY == 2 && (paddlePosP1 == 1 || paddlePosP1 == 2 || paddlePosP1 == 3 || paddlePosP1 == 4)) { CollisionUpdate(newX, newY, P); } else if (newY == 3 && (paddlePosP1 == 1 || paddlePosP1 == 2 || paddlePosP1 == 3 || paddlePosP1 == 4 || paddlePosP1 == 5)) { CollisionUpdate(newX, newY, P); } else if (newY == 4 && (paddlePosP1 == 2 || paddlePosP1 == 3 || paddlePosP1 == 4 || paddlePosP1 == 5 || paddlePosP1 == 6)) { CollisionUpdate(newX, newY, P); } else if (newY == 5 && (paddlePosP1 == 3 || paddlePosP1 == 4 || paddlePosP1 == 5 || paddlePosP1 == 6 || paddlePosP1 == 7)) { CollisionUpdate(newX, newY, P); } else if (newY == 6 && (paddlePosP1 == 4 || paddlePosP1 == 5 || paddlePosP1 == 6 || paddlePosP1 == 7 || paddlePosP1 == 8)) { CollisionUpdate(newX, newY, P); } else if (newY == 7 && (paddlePosP1 == 5 || paddlePosP1 == 6 || paddlePosP1 == 7 || paddlePosP1 == 8 || paddlePosP1 == 9)) { CollisionUpdate(newX, newY, P); } else if (newY == 8 && (paddlePosP1 == 6 || paddlePosP1 == 7 || paddlePosP1 == 8 || paddlePosP1 == 9 || paddlePosP1 == 10)) { CollisionUpdate(newX, newY, P); } else if (newY == 9 && (paddlePosP1 == 7 || paddlePosP1 == 8 || paddlePosP1 == 9 || paddlePosP1 == 10 || paddlePosP1 == 11)) { CollisionUpdate(newX, newY, P); } else if (newY == 10 && (paddlePosP1 == 8 || paddlePosP1 == 9 || paddlePosP1 == 10 || paddlePosP1 == 11 || paddlePosP1 == 12)) { CollisionUpdate(newX, newY, P); } else if (newY == 11 && (paddlePosP1 == 9 || paddlePosP1 == 10 || paddlePosP1 == 11 || paddlePosP1 == 12 || paddlePosP1 == 13)) { CollisionUpdate(newX, newY, P); } else if (newY == 12 && (paddlePosP1 == 10 || paddlePosP1 == 11 || paddlePosP1 == 12 || paddlePosP1 == 13 || paddlePosP1 == 14)) { CollisionUpdate(newX, newY, P); } else if (newY == 13 && (paddlePosP1 == 11 || paddlePosP1 == 12 || paddlePosP1 == 13 || paddlePosP1 == 14)) { CollisionUpdate(newX, newY, P); } else if (newY == 14 && (paddlePosP1 == 12 || paddlePosP1 == 13 || paddlePosP1 == 14)) { CollisionUpdate(newX, newY, P); } else if (newY == 15 && (paddlePosP1 == 13 || paddlePosP1 == 14)) { CollisionUpdate(newX, newY, P); } // The ball has crossed the player's boundary else { pointsP2++; lcd.clear(); lcd.setCursor(7, 0); lcd.print(""P1 :""); lcd.setCursor(7, 1); lcd.print(""P2 :""); // A point has been scored lcd.createChar(2, heart); lcd.setCursor(11, 1); for (i = 0; i < (3 - pointsP1); i++) { lcd.write(2); } lcd.setCursor(11, 0); for (i = 0; i < (3 - pointsP2); i++) { lcd.write(2); } delay(2000); lcd.clear(); //Reset the ball's position and control variables for the next point ballPos[0] = 39; ballPos[1] = 7; totalDistance = distance = initialDist; Draw(); // Determine a new game angle for this point startDir(); // Game is over, 3 points have been scored by Player 2, reset the LCD to display the Start Game message if (pointsP2 == 3) { gameState = false; // Display Game Over Message and prints Player 2 Victory lcd.clear(); lcd.setCursor(0, 0); lcd.print(""!!!GAME OVER!!!""); delay(500); lcd.clear(); lcd.setCursor(0, 0); lcd.print("" P1 WINS ""); lcd.setCursor(0, 1); lcd.print("" Hold key ""); PlayAnim(); // Call setup to start the game over setup(); } } } // Check to make sure the Game is NOT over and then update the ball's LCD character if (gameState == true) { DrawBall(newX, newY); } } // Function to perform necessary updates/events when the ball hits the player's paddle void CollisionUpdate(int X, int Y, int P) { leftRightDir = 1 * P; totalDistance = distance; ballPos[0] = X - P; ballPos[1] = Y; } // Function to determine which one of the 40 possible custom LCD characters should be drawn (and where) on the LCD void DrawBall(int X, int Y) { int lcd_row; int lcd_col; // Determine which row of the LCD the ball's character is on if (Y <= 7) { lcd_row = 1; } else { lcd_row = 0; } //Determine which column of the LCD the ball's character is on if (X <= 4) { lcd_col = 0; } else if (X <= 9) { lcd_col = 1; } else if (X <= 14) { lcd_col = 2; } else if (X <= 19) { lcd_col = 3; } else if (X <= 24) { lcd_col = 4; } else if (X <= 29) { lcd_col = 5; } else if (X <= 34) { lcd_col = 6; } else if (X <= 39) { lcd_col = 7; } else if (X <= 44) { lcd_col = 8; } else if (X <= 49) { lcd_col = 9; } else if (X <= 54) { lcd_col = 10; } else if (X <= 59) { lcd_col = 11; } else if (X <= 64) { lcd_col = 12; } else if (X <= 69) { lcd_col = 13; } else if (X <= 74) { lcd_col = 14; } else { lcd_col = 15; } // Clear the LCD of the previous ball (the player's paddles) lcd.setCursor(1, 0); // 14 empty characters printed between the player's paddles lcd.print("" ""); lcd.setCursor(1, 1); lcd.print("" ""); // Determine the ball's position (single pixel) within a single LCD character int xpos = X - 5 * lcd_col; // Column position in the (8*5) character int ypos; // Row position in the (8*5) character if (Y == 0 || Y == 8) { ypos = 0; } else if (Y == 1 || Y == 9) { ypos = 1; } else if (Y == 2 || Y == 10) { ypos = 2; } else if (Y == 3 || Y == 11) { ypos = 3; } else if (Y == 4 || Y == 12) { ypos = 4; } else if (Y == 5 || Y == 13) { ypos = 5; } else if (Y == 6 || Y == 14) { ypos = 6; } else if (Y == 7 || Y == 15) { ypos = 7; } // Select the custom LCD character, of the 40 possible Characters , and display it in it's correct LCD column and row position if (xpos == 0 && ypos == 0) { lcd.createChar(2, ball70); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 1 && ypos == 0) { lcd.createChar(2, ball71); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 2 && ypos == 0) { lcd.createChar(2, ball72); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 3 && ypos == 0) { lcd.createChar(2, ball73); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 4 && ypos == 0) { lcd.createChar(2, ball74); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 0 && ypos == 1) { lcd.createChar(3, ball60); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 1 && ypos == 1) { lcd.createChar(3, ball61); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 2 && ypos == 1) { lcd.createChar(3, ball62); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 3 && ypos == 1) { lcd.createChar(3, ball63); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 4 && ypos == 1) { lcd.createChar(3, ball64); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 0 && ypos == 2) { lcd.createChar(4, ball50); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 1 && ypos == 2) { lcd.createChar(4, ball51); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 2 && ypos == 2) { lcd.createChar(4, ball52); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 3 && ypos == 2) { lcd.createChar(4, ball53); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 4 && ypos == 2) { lcd.createChar(4, ball54); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 0 && ypos == 3) { lcd.createChar(5, ball40); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 1 && ypos == 3) { lcd.createChar(5, ball41); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 2 && ypos == 3) { lcd.createChar(5, ball42); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 3 && ypos == 3) { lcd.createChar(5, ball43); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 4 && ypos == 3) { lcd.createChar(5, ball44); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 0 && ypos == 4) { lcd.createChar(2, ball30); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 1 && ypos == 4) { lcd.createChar(2, ball31); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 2 && ypos == 4) { lcd.createChar(2, ball32); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 3 && ypos == 4) { lcd.createChar(2, ball33); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 4 && ypos == 4) { lcd.createChar(2, ball34); lcd.setCursor(lcd_col, lcd_row); lcd.write(2); } else if (xpos == 0 && ypos == 5) { lcd.createChar(3, ball20); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 1 && ypos == 5) { lcd.createChar(3, ball21); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 2 && ypos == 5) { lcd.createChar(3, ball22); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 3 && ypos == 5) { lcd.createChar(3, ball23); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 4 && ypos == 5) { lcd.createChar(3, ball24); lcd.setCursor(lcd_col, lcd_row); lcd.write(3); } else if (xpos == 0 && ypos == 6) { lcd.createChar(4, ball10); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 1 && ypos == 6) { lcd.createChar(4, ball11); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 2 && ypos == 6) { lcd.createChar(4, ball12); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 3 && ypos == 6) { lcd.createChar(4, ball13); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 4 && ypos == 6) { lcd.createChar(4, ball14); lcd.setCursor(lcd_col, lcd_row); lcd.write(4); } else if (xpos == 0 && ypos == 7) { lcd.createChar(5, ball00); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 1 && ypos == 7) { lcd.createChar(5, ball01); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 2 && ypos == 7) { lcd.createChar(5, ball02); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 3 && ypos == 7) { lcd.createChar(5, ball03); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } else if (xpos == 4 && ypos == 7) { lcd.createChar(5, ball04); lcd.setCursor(lcd_col, lcd_row); lcd.write(5); } } void PlayAnim() { int UPbtnP1 = LOW; int DOWNbtnP1 = LOW; int UPbtnP2 = LOW; int DOWNbtnP2 = LOW; //Custom characters for the Animation byte ball02a[8] = { 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball12a[8] = { 0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball22a[8] = { 0b00000, 0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte ball32a[8] = { 0b00000, 0b00000, 0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000 }; //Custom characters for the Animation byte fire_shooter[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, 0b01110, 0b01110, }; byte fire_shotA[8] = { 0b00100, 0b01010, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, }; byte fire_shotB[8] = { 0b01010, 0b10001, 0b10001, 0b01010, 0b00100, 0b00000, 0b00000, 0b00000, }; byte clearChar[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; while (!(UPbtnP1 == HIGH || UPbtnP2 == HIGH || DOWNbtnP1 == HIGH || DOWNbtnP2 == HIGH)) { UPbtnP1 = digitalRead(buttonUPP1); DOWNbtnP1 = digitalRead(buttonDOWNP1); UPbtnP2 = digitalRead(buttonUPP2); DOWNbtnP2 = digitalRead(buttonDOWNP2); lcd.createChar(2, ball32); lcd.setCursor(1, 1); lcd.write(2); lcd.setCursor(14, 1); lcd.write(2); delay(80); lcd.createChar(2, ball22); lcd.setCursor(1, 1); lcd.write(2); lcd.setCursor(14, 1); lcd.write(2); delay(85); lcd.createChar(2, ball12); lcd.setCursor(1, 1); lcd.write(2); lcd.setCursor(14, 1); lcd.write(2); delay(90); lcd.createChar(2, ball02); lcd.setCursor(1, 1); lcd.write(2); lcd.setCursor(14, 1); lcd.write(2); delay(95); lcd.createChar(5, fire_shooter); lcd.setCursor(1, 1); lcd.write(5); lcd.setCursor(14, 1); lcd.write(5); lcd.createChar(2, ball72); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball62); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball52); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball42); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball32a); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball22a); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball12a); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); delay(100); lcd.createChar(2, ball02a); lcd.setCursor(1, 0); lcd.write(2); lcd.setCursor(14, 0); lcd.write(2); lcd.createChar(3, fire_shotA); lcd.setCursor(1, 0); lcd.write(3); lcd.setCursor(14, 0); lcd.write(3); delay(200); lcd.createChar(3, fire_shotB); lcd.setCursor(1, 0); lcd.write(3); lcd.setCursor(14, 0); lcd.write(3); } }",16256,True,2715.233459922174,median "/** * VERSION: 1.698 * DATE: 2012-03-29 * AS3 (AS2 version is also available) * UPDATES AND DOCS AT: http://www.greensock.com/timelinemax/ **/ package com.greensock { import com.greensock.core.*; import com.greensock.events.TweenEvent; import flash.events.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *
    *
  • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
  • * *
  • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
  • * *
  • nest timelines within timelines as deeply as you want.
  • * *
  • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
  • * *
  • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
  • * *
  • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
  • * *
  • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
  • * *
  • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
  • * *
  • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
  • * *
  • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
  • * *
  • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
  • * *
  • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
  • * *
  • get the active tweens in the timeline with getActive().
  • * *
  • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
  • * *
  • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
  • *
* * EXAMPLE:

* * import com.greensock.~~;

* * //create the timeline and add an onComplete call to myFunction when the timeline completes
* var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

* * //add a tween
* myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

* * //add another tween at the end of the timeline (makes sequencing easy)
* myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

* * //repeat the entire timeline twice
* myTimeline.repeat = 2;

* * //delay the repeat by 0.5 seconds each time.
* myTimeline.repeatDelay = 0.5;

* * //pause the timeline (stop() works too)
* myTimeline.pause();

* * //reverse it anytime...
* myTimeline.reverse();

* * //Add a ""spin"" label 3-seconds into the timeline.
* myTimeline.addLabel(""spin"", 3);

* * //insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
* myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

* * //go to the ""spin"" label and play the timeline from there...
* myTimeline.gotoAndPlay(""spin"");

* * //call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
* myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

* * //nest another TimelineMax inside your timeline...
* var nestedTimeline:TimelineMax = new TimelineMax();
* nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
* myTimeline.append(nestedTimeline);

* * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

* * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

* * You can use the constructor's vars object to do all the setup too, like:

* * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

* * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

* * * NOTES: *
    *
  • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
  • *
  • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
  • *
* * Copyright 2012, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version:Number = 1.698; /** @private **/ protected var _repeat:int; /** @private **/ protected var _repeatDelay:Number; /** @private **/ protected var _cyclesComplete:int; /** @private **/ protected var _dispatcher:EventDispatcher; /** @private **/ protected var _hasUpdateListener:Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo:Boolean; /** * Constructor.

* * SPECIAL PROPERTIES
* The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
    *
  • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
  • * *
  • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
  • * *
  • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
  • * *
  • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
  • * *
  • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
  • * *
  • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
      *
    • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
    • *
    • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
    • *
    • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
    • *
    The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
  • * *
  • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
  • * *
  • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
  • * *
  • onStartParams : Array An Array of parameters to pass the onStart function.
  • * *
  • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
  • * *
  • onUpdateParams : Array An Array of parameters to pass the onUpdate function
  • * *
  • onComplete : Function A function that should be called when the timeline has finished
  • * *
  • onCompleteParams : Array An Array of parameters to pass the onComplete function
  • * *
  • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
  • * *
  • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
  • * *
  • onRepeat : Function A function that should be called every time the timeline repeats
  • * *
  • onRepeatParams : Array An Array of parameters to pass the onRepeat function
  • * *
  • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
  • * *
  • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
  • * *
  • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
  • * *
  • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
  • * *
  • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
  • * *
  • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
  • * *
  • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
  • *
* * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars:Object=null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return TweenLite instance */ public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite { var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a:Array = getTweensOf(callback, false), success:Boolean; var i:int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

* * myTimeline.tweenTo(""myLabel2"");

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

* * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite { var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

* * var playheadTweens:TimelineMax = new TimelineMax();
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite { var tl:TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number { return t / d; } /** @private **/ override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevTotalTime:Number = this.cachedTotalTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused; if (time >= totalDur) { if ((prevTotalTime != totalDur || this.cachedDuration == 0) && _rawPrevTime != time) { this.cachedTotalTime = totalDur; if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); } else { this.cachedTime = this.cachedDuration; forceChildrenToEnd(this.cachedDuration, suppressEvents); } isComplete = !this.hasPausedChild() && !this.cachedReversed; rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime > 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } else if (time == 0 && !this.initted) { force = true; } if (prevTotalTime != 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration:Number = this.cachedDuration + _repeatDelay; var prevCycles:int = _cyclesComplete; if ((_cyclesComplete = (this.cachedTotalTime / cycleDuration) >> 0) == (this.cachedTotalTime / cycleDuration) && _cyclesComplete != 0) { _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } repeated = Boolean(prevCycles != _cyclesComplete); if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { this.cachedTime = this.cachedTotalTime - (_cyclesComplete * cycleDuration); //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } else { _cyclesComplete = 0; } if (repeated && !isComplete && (this.cachedTotalTime != prevTotalTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap:Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTime == prevTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTotalTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { //already rendered, so ignore } else if (this.cachedTime > prevTime) { tween = _firstChild; while (tween) { next = tween.nextNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array { var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int, tween:TweenCore; var l:int = all.length; var cnt:int = 0; for (i = 0; i < l; i += 1) { tween = all[i]; //note: we cannot just check tween.active because timelines that contain paused children will continue to have ""active"" set to true even after the playhead passes their end point (technically a timeline can only be considered complete after all of its children have completed too, but paused tweens are...well...just waiting and until they're unpaused we don't know where their end point will be). if (!tween.cachedPaused && tween.timeline.cachedTotalTime >= tween.cachedStartTime && tween.timeline.cachedTotalTime < tween.cachedStartTime + tween.cachedTotalDuration / tween.cachedTimeScale && !OverwriteManager.getGlobalPaused(tween.timeline)) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate():void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var l:int = labels.length; for (var i:int = 0; i < l; i += 1) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var i:int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray():Array { var a:Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e:Event):Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** @inheritDoc **/ override public function set currentProgress(n:Number):void { this.currentTime = this.duration * n; } /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress():Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n:Number):void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration():Number { if (this.cacheIsDirty) { var temp:Number = super.totalDuration; //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @private **/ override public function set currentTime(n:Number):void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat():int { return _repeat; } public function set repeat(n:int):void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay():Number { return _repeatDelay; } public function set repeatDelay(n:Number):void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel():String { return getLabelBefore(this.cachedTime + 0.00000001); } } }",12342,False,2101.7591575743168,median "package com.smbc.characters.base { import com.explodingRabbit.utils.CustomTimer; import com.smbc.characters.Character; import com.smbc.characters.Luigi; import com.smbc.characters.Mario; import com.smbc.data.AnimationTimers; import com.smbc.data.GameSettings; import com.smbc.data.GameStates; import com.smbc.data.MusicType; import com.smbc.data.PickupInfo; import com.smbc.data.SoundNames; import com.smbc.enemies.Bloopa; import com.smbc.enemies.Enemy; import com.smbc.enums.ClassicDamageResponse; import com.smbc.enums.DamageResponse; import com.smbc.graphics.BmdSkinCont; import com.smbc.ground.*; import com.smbc.level.Level; import com.smbc.level.TitleLevel; import com.smbc.main.GlobVars; import com.smbc.main.LevObj; import com.smbc.messageBoxes.GridMenuBox; import com.smbc.pickups.BowserAxe; import com.smbc.pickups.Pickup; import com.smbc.pickups.Vine; import com.smbc.projectiles.*; import com.smbc.sound.*; import flash.display.*; import flash.events.*; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import nl.stroep.utils.ImageSaver; public class MarioBase extends Character { private const DIE_TMR_DEL_NORMAL:int = 3000; private const DIE_TMR_DEL_PIT:int = 3000; public static const IND_CI_Mario:int = 1; public static const IND_CI_MarioFireBall:int = 6; public static const IND_CI_MarioFireFlowerNormal:int = 7; public static const IND_CI_MarioFireFlowerUnderGround:int = 8; public static const IND_CI_MarioStar:int = 9; public static const IND_CI_MarioPortrait:int = 4; private const REPL_COLOR_1_1:uint = 0xFFD82800; private const REPL_COLOR_2_1:uint = 0xFF7B6601; // brown private const REPL_COLOR_3_1:uint = 0xFFFC9838; private const REPL_COLOR_1_2:uint = REPL_COLOR_1_1; private const REPL_COLOR_2_2:uint = REPL_COLOR_2_1; private const REPL_COLOR_3_2:uint = REPL_COLOR_3_1; private const REPL_COLOR_1_3:uint = 0xFFFCD8A8; private const REPL_COLOR_2_3:uint = REPL_COLOR_1_1; private const REPL_COLOR_3_3:uint = REPL_COLOR_3_1; private static const PAL_COL_NORMAL:int = 1; private static const PAL_COL_FIRE_FLOWER:int = 3; private static const SKIN_APPEARANCE_NUM_SMALL:int = 0; private static const SKIN_APPEARANCE_NUM_BIG:int = 1; private static const SKIN_APPEARANCE_NUM_FIRE_POWER:int = 2; protected static const MARIO_FIRE_FLOWER:String = PickupInfo.MARIO_FIRE_FLOWER; private const ANIM_TMR_FOR_FREEZE:CustomTimer = AnimationTimers.ANIM_MIN_FAST_TMR; private const ANIM_TMR_FOR_TAKE_DAMAGE:CustomTimer = AnimationTimers.ANIM_MODERATE_TMR; private const ANIM_TMR_FOR_JUMP:CustomTimer = AnimationTimers.ANIM_FAST_TMR; private const SWIM_ANIM_TMR:CustomTimer = AnimationTimers.ANIM_MODERATE_TMR; private var walkAnimTmr1:CustomTimer = AnimationTimers.ANIM_VERY_SLOW_TMR; private var walkAnimTmr2:CustomTimer = AnimationTimers.ANIM_SLOW_TMR; private var walkAnimTmr3:CustomTimer = AnimationTimers.ANIM_MODERATE_TMR; private var runAnimTmr1:CustomTimer = AnimationTimers.ANIM_MIN_FAST_TMR; private var runAnimTmr2:CustomTimer = AnimationTimers.ANIM_FAST_TMR; public static const SFX_MARIO_FIREBALL:String = SoundNames.SFX_MARIO_FIREBALL; public static const SFX_MARIO_JUMP_BIG:String = SoundNames.SFX_MARIO_JUMP_BIG public static const SFX_MARIO_JUMP_SMALL:String = SoundNames.SFX_MARIO_JUMP_SMALL; public static const SFX_GAME_PIPE:String = SoundNames.SFX_GAME_PIPE; public static const SFX_GAME_STOMP:String = SoundNames.SFX_GAME_STOMP; public static const MFX_MARIO_DIE:String = SoundNames.MFX_MARIO_DIE; public static const MAX_WALK_SPEED:int = 175; private const MAX_RUN_SPEED:int = 300; private const JUMP_HEIGHT_RUN_SPEED:int = 175; private static const NO_DAMAGE_TMR_DEL:int = 2500; private const FLAG_POLE_X_OFS:int = 6; private const FLAG_POLE_SLIDE_ANIM_TMR:CustomTimer = AnimationTimers.ANIM_MIN_FAST_TMR; private const MIN_WALK_SPEED:int = 40; // 40 private const MAX_FIREBALLS_ON_SCREEN:int = 2; private const WALK_TMR_1_MIN_VX:int = 0; private const WALK_TMR_2_MIN_VX:int = 50; private const WALK_TMR_3_MIN_VX:int = 100; private const RUN_TMR_1_MIN_VX:int = MAX_WALK_SPEED - 10; private const RUN_TMR_2_MIN_VX:int = 220; private const MIN_RUN_OVER_GAP_SPEED:int = RUN_TMR_2_MIN_VX; private const BASE_FL_WALK:String = ""walk""; private const BASE_FL_WALK_SHOOT:String = ""walkShoot""; private static const FL_CLIMB_START:String = ""climbStart""; private static const FL_CLIMB_END:String = ""climbEnd""; private static const FL_CROUCH:String = ""crouch""; private static const FL_DIE:String = ""die""; private static const FL_JUMP_START:String = ""jumpStart""; private static const FL_JUMP_END:String = ""jumpEnd""; private static const FL_FALL_START:String = ""fallStart""; private static const FL_FALL_END:String = ""fallEnd""; private static const FL_GROW_START:String = ""growStart""; private static const FL_GROW_END:String = ""growEnd""; private static const FL_SHOOT:String = ""shoot""; private static const FL_PIPE:String = ""pipe""; private static const FL_PIPE_2:String = ""pipe_2""; private static const FL_SKID:String = ""skid""; private static const FL_STAND:String = ""stand""; private static const FL_STAND_UP:String = ""standUp""; private static const FL_STAND_UP_2:String = ""standUp_2""; private static const FL_TAKE_DAMAGE_START:String = ""takeDamageStart""; private static const FL_TAKE_DAMAGE_END:String = ""takeDamageEnd""; private static const FL_WALK_START:String = ""walk-1""; private static const FL_WALK_END_NES:String = ""walk-3""; private static const FL_WALK_END_NORMAL:String = ""walk-4""; private static const FL_WALK_SHOOT_START:String = ""walkShoot-1""; private static const FL_WALK_SHOOT_END:String = ""walkShoot-3""; private static const FL_WALK_DUR_TEST_FRAME:String = ""walk-4_2""; private static const FL_SMALL_CROUCH_TEST_FRAME:String = FL_CROUCH + ""_1""; private static const FL_FALL_TEST_FRAME:String = FL_FALL_START+""_2""; private static const ST_SKID:String = ""skid""; private var hitMainAnimTmr:CustomTimer; private var singleFirePowerFrame:Boolean; // private static const FX_WALK:Number = .02; // private static const FX_RUN_CROUCH:Number = .02; private static const FX_RUN_TO_WALK:Number = .02; private var fxSkid:Number; private static const FX_DUNGEON_GOT_AXE:Number = .0001; private static const AX_PIT_VACUUM_SLOW_SPEED:int = 700; private static const AX_PIT_VACUUM:int = 575; private var jumpPwrDef:Number; private var jumpPwrRun:Number; public static const JUMP_PWR:int = 630; //630 private const JUMP_PWR_RUN:int = 700; private const JUMP_PWR_WATER:int = 200; public static const GRAVITY_NAME:String = ""GRAVITY""; private var skidThreshold:int; private var paddleFastSpeed:Number = 100; private const DIE_BOOST:int = 500; private const DIE_GRAVITY:int = 1200; private const DIE_VY_MAX_PSV:int = 540; private var dieFreezeTmr:CustomTimer; private const DIE_FREEZE_TMR_DUR:int = 250; private const CLIMB_OFFSET_X:int = 0; private const SHOOT_TMR:CustomTimer = new CustomTimer(75,1); private var shoot:Boolean; private var justCrouched:Boolean; private const SECONDS_LEFT_DUNGEON:String = SoundNames.BGM_MARIO_DUNGEON_FAST; private const SECONDS_LEFT_OVER_WORLD:String = SoundNames.BGM_MARIO_OVER_WORLD_FAST; private const SECONDS_LEFT_UNDER_GROUND:String = SoundNames.BGM_MARIO_UNDER_GROUND_FAST; private const SECONDS_LEFT_WATER:String = SoundNames.BGM_MARIO_WATER_FAST; private const SND_MUSIC_WIN:String = SoundNames.MFX_MARIO_WIN; private const SND_MUSIC_WIN_DUNGEON:String = SoundNames.MFX_MARIO_WIN_CASTLE; private const NSF_STR_DIE:String = MusicInfo.CHAR_STR_MARIO + MusicInfo.TYPE_DIE; private var useEnterPipeVxMax:Boolean; private const BLOOPA_NO_HURT_Y:int = Level.GLOB_STG_BOT - Level.levelInstance.TILE_SIZE*2; private var frameBmd:BitmapData = new BitmapData(50,50); private var frameBmp:Bitmap = new Bitmap(frameBmd); private var bmdArr:Vector. = new Vector.(); private var jumpRise:Boolean; private var jumpEnd:Number; private var jumpEndMin:Number; private var fxWalk:Number; private static const JUMP_SPEED_NORMAL_NAME:String = ""JUMP_SPEED_NORMAL""; private static const JUMP_SPEED_RUN_NAME:String = ""JUMP_SPEED_RUN""; private static const JUMP_HEIGHT_MIN_NAME:String = ""JUMP_HEIGHT_MIN""; private static const JUMP_HEIGHT_NORMAL_STR:String = ""JUMP_HEIGHT_NORMAL""; private static const JUMP_HEIGHT_RUN_STR:String = ""JUMP_HEIGHT_RUN""; private static const VY_MAX_PSV_NORMAL_NAME:String = ""VY_MAX_PSV_NORMAL""; private static const AX_DEFAULT_NAME:String = ""AX_DEFAULT""; private static const AX_RUN_NAME:String = ""AX_RUN""; private static const FX_SKID_NAME:String = ""FX_SKID""; private static const FX_WALK_NAME:String = ""FX_WALK""; private static const FX_RUN_CROUCH_NAME:String = ""FX_RUN_CROUCH""; private static const FY_NAME:String = ""FY""; private static const SKID_THRESHOLD_NAME:String = ""SKID_THRESHOLD""; private static const FEATHER_NAME:String = ""featherStg""; private static const FEATHER_FRAMES_SHOW_ARR:Array = [ ""stand_2"", ""standUp_2"", ""pipe_2"", ""walk-1_2"", ""walk-2_2"", ""walk-3_2"", ""walkShoot-1_2"", ""walkShoot-2_2"", ""walkShoot-3_2"", ""jumpStart_2"",""jumpEnd_2"", ""skid_2"", ""shoot_2"", ""swimStillStart_2"",""swimStillEnd_2"",""paddleFastStart_2"",""paddleFast-2_2"",""paddleFast-3_2"",""paddleFast-4_2"", ""paddleFast-5_2"",""paddleFast-6_2"",""paddleFast-7_2"",""paddleFastEnd_2"",""paddleSlowStart_2"",""paddleSlow-2_2"",""paddleSlow-3_2"", ""paddleSlow-4_2"",""paddleSlow-5_2"",""paddleSlow-6_2"",""paddleSlow-7_2"",""paddleSlow-8_2"",""paddleSlow-9_2"",""paddleSlowEnd_2"", ""climbStart_2"",""climbEnd_2"" ]; protected var appearanceNum:int; protected static const APPEARANCE_NUM_SMALL:int = 1, APPEARANCE_NUM_BIG:int = 2; private var appearancePossibilities:String; private static const AP_BIG_ONLY:String = ""bigOnly"", AP_SMALL_ONLY:String = ""smallOnly"", AP_BIG_AND_SMALL:String = ""bigAndSmall""; private var hasFallFrame:Boolean; private var hasSmallCrouchFrame:Boolean; protected static const SKIN_PREVIEW_SIZE_BIG:Point = new Point(26,36); protected static const SKIN_PREVIEW_SIZE_SMALL:Point = new Point(26,26); public function MarioBase() { _dieTmrDel = DIE_TMR_DEL_NORMAL; recolorsCharSkin = true; super(); _isGoodSwimmer = true; bmdArr.push(frameBmd); walkStartLab = FL_WALK_START; // walkEndLab = FL_WALK_END_NORMAL; for each (var ct:CustomTimer in level.ALL_ANIM_TMRS_DCT) { ACTIVE_ANIM_TMRS_DCT.addItem(ct); } /*var bgt:int = level.bgmType; if (bgt == MusicType.DUNGEON) _secondsLeftSnd = SECONDS_LEFT_DUNGEON; else if (bgt == MusicType.OVER_WORLD) _secondsLeftSnd = SECONDS_LEFT_OVER_WORLD; else if (bgt == MusicType.UNDER_GROUND) _secondsLeftSnd = SECONDS_LEFT_UNDER_GROUND; else if (bgt == MusicType.WATER) _secondsLeftSnd = SECONDS_LEFT_WATER;*/ _secondsLeftSndIsBgm = true; if (level.levNum != STAT_MNGR.DUNGEON_LEVEL_NUM) _sndWinMusic = SND_MUSIC_WIN; else _sndWinMusic = SND_MUSIC_WIN_DUNGEON; } override protected function setObjsToRemoveFromFrames():void { super.setObjsToRemoveFromFrames(); removeObjsFromFrames(FEATHER_NAME,FEATHER_FRAMES_SHOW_ARR,true ); } override public function setStats():void { inColor1_1 = REPL_COLOR_1_1; inColor2_1 = REPL_COLOR_2_1; inColor3_1 = REPL_COLOR_3_1; inColor1_2 = REPL_COLOR_1_2; inColor2_2 = REPL_COLOR_2_2; inColor3_2 = REPL_COLOR_3_2; inColor1_3 = REPL_COLOR_1_3; inColor2_3 = REPL_COLOR_2_3; inColor3_3 = REPL_COLOR_3_3; fxWalk = classObj[FX_WALK_NAME]; if (level.waterLevel) jumpPwr = JUMP_PWR_WATER; else jumpPwr = JUMP_PWR; jumpPwrDef = jumpPwr; jumpPwrRun = JUMP_PWR_RUN; gravity = classObj[GRAVITY_NAME]; walksSlowUnderWater = true; if (level.waterLevel) { defGravity = 700; gravity = 350; defGravityWater = gravity; } defSpringPwr = 400; boostSpringPwr = 950; ax = classObj[AX_DEFAULT_NAME]; fx = fxWalk; fy = classObj[FY_NAME]; fxSkid = classObj[FX_SKID_NAME]; vxMaxDef = MAX_WALK_SPEED; if (level.waterLevel) vyMaxPsv = 400; else vyMaxPsv = classObj[VY_MAX_PSV_NORMAL_NAME]; vxMax = vxMaxDef; vyMaxNgv = 4000; // vxMin = 5; numParFrames = 4; skidThreshold = classObj[SKID_THRESHOLD_NAME]; super.setStats(); _canStomp = true; canStompUnderWater = false; setStopFrame(FL_STAND); changeBrickState(); SHOOT_TMR.addEventListener(TimerEvent.TIMER_COMPLETE,shootTmrHandler,false,0,true); addTmr(SHOOT_TMR); noDamageTmr.delay = NO_DAMAGE_TMR_DEL; } override protected function startAndDamageFcts(start:Boolean = false):void { super.startAndDamageFcts(start); if (!start) changeAppearance(); } override public function changedToThisChar():void { super.changedToThisChar(); setStopFrame(FL_STAND); } override public function forceWaterStats():void { defGravity = 700; gravity = 350; defGravityWater = gravity; vyMaxPsv = 400; jumpPwr = 200; jumpPwrDef = jumpPwr; super.forceWaterStats(); if (!onGround) setPlayFrame(""swimStillStart""); } override public function convLab(_fLab:String):String { return _fLab + ""_"" +appearanceNum.toString(); } protected function changeAppearance(forceAppearanceNum:int = -1, forcePalCol:int = -1):void { var palCol:int; if ( upgradeIsActive(MARIO_FIRE_FLOWER) ) { palCol = PAL_COL_FIRE_FLOWER; appearanceNum = APPEARANCE_NUM_BIG; } else if ( upgradeIsActive(MUSHROOM) ) { palCol = PAL_COL_NORMAL; appearanceNum = APPEARANCE_NUM_BIG; } else { palCol = PAL_COL_NORMAL; appearanceNum = APPEARANCE_NUM_SMALL; } if (forceAppearanceNum >= 0) appearanceNum = forceAppearanceNum; if (forcePalCol >= 0) palCol = forcePalCol; // for skins that have only big or only small if (appearancePossibilities == AP_SMALL_ONLY) appearanceNum = APPEARANCE_NUM_SMALL; else if (appearancePossibilities == AP_BIG_ONLY) appearanceNum = APPEARANCE_NUM_BIG; // if (GridMenuBox.instance != null) // { // appearanceNum = APPEARANCE_NUM_BIG // graphicsMngr.recolorCharacterSheet(charNum,PAL_COL_NORMAL,[IND_CI_Mario]); // } // else graphicsMngr.recolorCharacterSheet(charNum,palCol,[IND_CI_Mario,IND_CI_MarioPortrait]); defColors = paletteMain.extractRowsAsPalette(0,palCol); if (skinNum == 2 || skinNum == 12 || skinNum == 14) { var show:Boolean; if (upgradeIsActive(MARIO_FIRE_FLOWER) && forceAppearanceNum == -1) show = true; removeObjsFromFrames(FEATHER_NAME,FEATHER_FRAMES_SHOW_ARR, false, int(show) ); } } override public function forceNonwaterStats():void { gravity = 1400; vyMaxPsv = classObj[VY_MAX_PSV_NORMAL_NAME]; jumpPwr = 630; jumpPwrDef = jumpPwr; _canStomp = true; super.forceNonwaterStats(); } override public function hitPickup(pickup:Pickup,showAnimation:Boolean = true):void { var hasFireFlower:Boolean = upgradeIsActive(MARIO_FIRE_FLOWER); if (pickup.type == MARIO_FIRE_FLOWER && !upgradeIsActive(MUSHROOM) ) pickup.type = MUSHROOM; super.hitPickup(pickup,showAnimation); switch(pickup.type) { case MUSHROOM: { changeAppearance(); break; } case MARIO_FIRE_FLOWER: { if ( !upgradeIsActive(MUSHROOM) ) hitPickup( new Pickup(MUSHROOM) ); else if (!hasFireFlower) { super.getMushroom(); changeAppearance(); } break; } case PickupInfo.STAR: { /*if (ImageSaver.INSTANCE.recording) { ImageSaver.INSTANCE.store(game); GameSettings.changeMapPalette(0); graphicsMngr.changeCharacterSkin(this,2); // level.toggleScreenScroll(); ImageSaver.INSTANCE.store(game); }*/ break; } } } override protected function movePlayer():void { if (rhtBtn && !lftBtn && !wallOnRight && cState != ST_CROUCH) { if (justCrouched) { justCrouched = false; return; } if (cState == ST_VINE) { if (exitVine) getOffVine(); else return; } vx += ax*dt; if (onGround) { scaleX = 1; if (vx < 0) vx *= Math.pow(fxSkid,dt); } else if (level.waterLevel) scaleX = 1; } else if (lftBtn && !rhtBtn && !wallOnLeft && cState != ST_CROUCH) { if (justCrouched) { justCrouched = false; return; } if (cState == ST_VINE) { if (exitVine) getOffVine(); else return; } vx -= ax*dt; if (onGround) { scaleX = -1; if (vx > 0) vx *= Math.pow(fxSkid,dt); } else if (level.waterLevel) scaleX = -1; } else if (cState == ST_SKID) vx *= Math.pow(fxSkid,dt); else if (cState == ST_CROUCH || atkBtn && ( (lftBtn && rhtBtn) || (!lftBtn && !rhtBtn && onGround) ) ) { vx *= Math.pow(classObj[FX_RUN_CROUCH_NAME],dt); if ( (vx > 0 && vx < MIN_WALK_SPEED) || (vx < 0 && vx > -MIN_WALK_SPEED) ) vx = 0; } else if ( (lftBtn && rhtBtn) || (!lftBtn && !rhtBtn && onGround) ) { vx *= Math.pow(fxWalk,dt); if ( (vx > 0 && vx < MIN_WALK_SPEED) || (vx < 0 && vx > -MIN_WALK_SPEED) ) vx = 0; } if (atkBtn && !level.waterLevel && currentFrameLabel != convLab(FL_CROUCH)) { vxMax = MAX_RUN_SPEED; } if (vx > vxMax) vx = vxMax; if (vx < -vxMax) vx = -vxMax; if (!atkBtn) { if (vx > vxMaxDef || vx < -vxMaxDef) { if (rhtBtn || lftBtn) vx *= Math.pow(FX_RUN_TO_WALK,dt); } else vxMax = vxMaxDef; } if (onGround) { if (vx > 0) { if (vx >= WALK_TMR_1_MIN_VX && vx <= WALK_TMR_2_MIN_VX) mainAnimTmr = walkAnimTmr1; else if (vx > WALK_TMR_2_MIN_VX && vx <= WALK_TMR_3_MIN_VX) mainAnimTmr = walkAnimTmr2; else if (vx > WALK_TMR_3_MIN_VX && vx <= RUN_TMR_1_MIN_VX) mainAnimTmr = walkAnimTmr3; else if (vx > RUN_TMR_1_MIN_VX && vx <= RUN_TMR_2_MIN_VX) mainAnimTmr = runAnimTmr1; else mainAnimTmr = runAnimTmr2; } else { if (vx <= WALK_TMR_1_MIN_VX && vx >= -WALK_TMR_2_MIN_VX) mainAnimTmr = walkAnimTmr1; else if (vx < -WALK_TMR_2_MIN_VX && vx >= -WALK_TMR_3_MIN_VX) mainAnimTmr = walkAnimTmr2; else if (vx < -WALK_TMR_3_MIN_VX && vx >= -RUN_TMR_1_MIN_VX) mainAnimTmr = walkAnimTmr3; else if (vx < -RUN_TMR_1_MIN_VX && vx >= -RUN_TMR_2_MIN_VX) mainAnimTmr = runAnimTmr1; else mainAnimTmr = runAnimTmr2; } if (mainAnimTmr == runAnimTmr2) canCrossSmallGaps = true; else canCrossSmallGaps = false; } else if (!level.waterLevel) if (this is Mario && skinNum == 5) mainAnimTmr = ANIM_VERY_SLOW_TMR; else mainAnimTmr = ANIM_TMR_FOR_JUMP; else mainAnimTmr = SWIM_ANIM_TMR; if (cState == ST_VINE || cState == ST_FLAG_SLIDE) { if (vy == 0) stopAnim = true; else stopAnim = false; mainAnimTmr = vineAnimTmr; } if (useEnterPipeVxMax) vxMax = ENTER_PIPE_VX_MAX; if (onGround && vx == 0 && cState != ST_CROUCH) { if (rhtBtn && wallOnRight) scaleX = 1; else if (lftBtn && wallOnLeft) scaleX = -1; } } override public function activateWatchModeEnterPipe():void { super.activateWatchModeEnterPipe(); useEnterPipeVxMax = true; } public function getRealBounds(displayObject:DisplayObject):Rectangle { var bounds:Rectangle; var boundsDispO:Rectangle = displayObject.getBounds( displayObject ); var bitmapData:BitmapData = new BitmapData( int( boundsDispO.width + 0.5 ), int( boundsDispO.height + 0.5 ), true, 0 ); var matrix:Matrix = new Matrix(); matrix.translate( -boundsDispO.x, -boundsDispO.y); bitmapData.draw( displayObject, matrix, new ColorTransform( 1, 1, 1, 1, 255, -255, -255, 255 ) ); bounds = bitmapData.getColorBoundsRect( 0xFF000000, 0xFF000000 ); bounds.x += boundsDispO.x; bounds.y += boundsDispO.y; bitmapData.dispose(); return bounds; } // CHECKSTATE override protected function checkState():void { if (cState == ST_VINE) { checkVineBtns(); checkVinePosition(); return; } else if (cState == ST_DIE) return; if (onGround) { if (atkBtn) ax = classObj[AX_RUN_NAME]; else ax = classObj[AX_DEFAULT_NAME]; jumped = false; if (vx == 0 && !lftBtn && !rhtBtn && (!canCrouch() || (canCrouch() && !dwnBtn))) { setState(ST_STAND); if (!upgradeIsActive(MARIO_FIRE_FLOWER) || !shoot) { if (!upBtn) setStopFrame(FL_STAND); else setStopFrame(FL_STAND_UP); } else setStopFrame(FL_SHOOT); } else if (canCrouch() && dwnBtn) { setState(ST_CROUCH); justCrouched = true; setStopFrame(FL_CROUCH); } else if (vx > skidThreshold && lftBtn) { setState(ST_SKID); setStopFrame(FL_SKID); } else if (vx < -skidThreshold && rhtBtn) { setState(ST_SKID); setStopFrame(FL_SKID); } else if (cState == ST_SKID && vx >= 0 && lftBtn) setStopFrame(FL_SKID); else if (cState == ST_SKID && vx <= 0 && rhtBtn) setStopFrame(FL_SKID); else if ((pulledLeft && !rhtBtn && !lftBtn) || (pulledRight && !lftBtn && !rhtBtn)) { setState(ST_STAND); setStopFrame(FL_STAND); } else if (upgradeIsActive(MARIO_FIRE_FLOWER) && cState == ST_WALK) { if (!shoot) setPlayFrame(getParFrame(BASE_FL_WALK)) else if (!singleFirePowerFrame) setPlayFrame(getParFrame(BASE_FL_WALK_SHOOT)); } else if (cState != ST_WALK) { if (!upgradeIsActive(MARIO_FIRE_FLOWER) ) setPlayFrame(FL_WALK_START); else if (!shoot) setPlayFrame(FL_WALK_START); else if (!singleFirePowerFrame) setPlayFrame(FL_WALK_SHOOT_START); setState(ST_WALK); } } else // not onGround { if (level.waterLevel) { if (cState != ""paddle"" && cState != ""jump"") { setPlayFrame(""swimStillStart""); setState(ST_JUMP); } if (pulledLeft || pulledRight) { if ( (vx > 0 && vx < 60) || (vx < 0 && vx > -60) ) ax = AX_PIT_VACUUM_SLOW_SPEED; else ax = AX_PIT_VACUUM; } else ax = classObj[AX_DEFAULT_NAME]; } else // not underwater && not on ground { setState(ST_JUMP); if (!jumped && !hasFallFrame) stopAnim = true; if (jumpRise) { if (ny <= jumpEnd) { ny = jumpEnd; setJumpRise(false); } else if (releasedJumpBtn && ny <= jumpEndMin) { ny = jumpEndMin; setJumpRise(false); } } var cl:String = currentLabel; if (cl == convLab(FL_STAND) || cl == convLab(FL_CLIMB_START) || cl == convLab(FL_CLIMB_END)) setPlayFrame(FL_JUMP_START); else if (cl == convLab(FL_SKID)) setStopFrame(walkEndLab); if (frictionY) { if (vy < 0) vy *= Math.pow(fy,dt); else frictionY = false; } if (hasFallFrame && vy >= 0 && cl != convLab(FL_FALL_START) && cl != convLab(FL_FALL_END) && cl != convLab(FL_CROUCH) && !shoot) setPlayFrame(FL_FALL_START); } } if (stuckInWall && !disableStuckInWallShift && jumpRise) setJumpRise(false); } private function canCrouch():Boolean { if (hasSmallCrouchFrame || upgradeIsActive(MUSHROOM)) return true; return false; } override public function gravityPull():void { if (lastOnGround && !onGround && !jumped && (vx > -MIN_RUN_OVER_GAP_SPEED && vx < MIN_RUN_OVER_GAP_SPEED ) ) { FALL_BTWN_TMR.reset(); FALL_BTWN_TMR.start(); _fallBtwn = true; } // trace(""gravity pull""); originalGravityPull(); } override protected function originalGravityPull():void { // trace(""original gravity pull""); super.originalGravityPull(); // trace(""vy: ""+vy); /*if (vy < -50) { vy -= 800*dt; }*/ } // JUMP override protected function jump():void { onGround = false; if (!level.waterLevel) { if (Math.abs(vx) >= JUMP_HEIGHT_RUN_SPEED) //Adjusted to allow Mario to jump higher sooner, for accuracy and ability to pass levels (JUMP_HEIGHT_RUN_SPEED = MAX_RUN_SPEED * 0.63) { jumpEnd = ny - classObj[JUMP_HEIGHT_RUN_STR]; vy = -classObj[JUMP_SPEED_RUN_NAME]; } else { jumpEnd = ny - classObj[JUMP_HEIGHT_NORMAL_STR]; vy = -classObj[JUMP_SPEED_NORMAL_NAME]; } jumpEndMin = ny - classObj[JUMP_HEIGHT_MIN_NAME]; setJumpRise(true); } else vy = -jumpPwr; jumped = true; releasedJumpBtn = false; frictionY = false; if (!level.waterLevel) { if (!upgradeIsActive(MUSHROOM)) { if (dwnBtn && hasSmallCrouchFrame) setStopFrame(FL_CROUCH) else setPlayFrame(FL_JUMP_START); SND_MNGR.playSound(SFX_MARIO_JUMP_SMALL); } else { if (dwnBtn) setStopFrame(FL_CROUCH) else { setPlayFrame(FL_JUMP_START); mainAnimTmr = ANIM_TMR_FOR_JUMP; } SND_MNGR.playSound(SFX_MARIO_JUMP_BIG); } setHitPoints(); } else // if (level.waterLevel) { SND_MNGR.playSound(SFX_GAME_STOMP); if (vx > paddleFastSpeed || vx < -paddleFastSpeed) setPlayFrame(""paddleFastStart""); else setPlayFrame(""paddleSlowStart""); setState(""paddle""); } } // RELJUMPBTN override public function relJmpBtn():void { super.relJmpBtn(); if (!releasedJumpBtn) { //vyMaxNgv = Math.abs(vy); releasedJumpBtn = true; if (ny <= jumpEndMin) { frictionY = true; setJumpRise(false); } } } private function get fireBallsOnScreenCount():int { var fireBallCount:int = 0; for each(var projectile:Projectile in level.PLAYER_PROJ_DCT) { if (projectile is MarioFireBall) fireBallCount++; } return fireBallCount; } override public function pressAtkBtn():void { if (cState == ST_VINE) return; super.pressAtkBtn(); if (upgradeIsActive(MARIO_FIRE_FLOWER) && fireBallsOnScreenCount < MAX_FIREBALLS_ON_SCREEN && currentFrameLabel != convLab(FL_CROUCH)) { level.addToLevel(new MarioFireBall(this)); if (SHOOT_TMR.running) SHOOT_TMR.reset(); SHOOT_TMR.start(); shoot = true; var cl:String = currentLabel; hitFrameLabel = cl.substring(0,cl.length-2); if (singleFirePowerFrame) setStopFrame(FL_SHOOT); else if (!onGround) setStopFrame(FL_SHOOT); else checkState(); } } override public function pressSpcBtn():void { if (cState == ST_VINE) return; super.pressSpcBtn(); // if (GameSettings.DEBUG_MODE) // { // pressRhtBtn(); // pressAtkBtn(); // vx = vxMax; // } } private function shootTmrHandler(e:TimerEvent):void { SHOOT_TMR.reset(); if (shoot) { shoot = false; if (singleFirePowerFrame && cState == ST_WALK) { setPlayFrame(FL_WALK_START); return; } if (onGround) checkState(); else if (!level.waterLevel) { if (jumped) setPlayFrame(FL_JUMP_START); else setStopFrame(hitFrameLabel); } else setPlayFrame(hitFrameLabel); } } override protected function getMushroom():void { if (GS_MNGR.gameState == GameStates.CHARACTER_SELECT) return; // setStopFrame(FL_JUMP); // if (pState > 1) // super.getMushroom(); // else // { var cl:String = currentLabel; hitFrameLabel = cl.substring(0,cl.length-2); hitStopAnim = stopAnim; hitMainAnimTmr = mainAnimTmr; setState(ST_GET_MUSHROOM); mainAnimTmr = ANIM_TMR_FOR_FREEZE; gotoAndStop(FL_GROW_START); stopAnim = false; freezeGame(); // } } // MegaMan overrides this function and does not call super override protected function getMushroomEnd():void { // if (pState != 1) // super.getMushroomEnd(); // else // { // pState++; if (!upgradeIsActive(MARIO_FIRE_FLOWER)) { setStopFrame(hitFrameLabel); mainAnimTmr = hitMainAnimTmr; stopAnim = hitStopAnim; setState(ST_NEUTRAL); checkState(); } else super.getMushroomEnd(); shoot = false; changeBrickState(); } override protected function changeBrickState():void { if (!upgradeIsActive(MUSHROOM)) brickState = BRICK_BOUNCER; else brickState = BRICK_BREAKER; } override protected function takeDamageStart(source:LevObj):void { super.takeDamageStart(source); SND_MNGR.playSound(SFX_GAME_PIPE); freezeGame(); STAT_MNGR.removeCharUpgrade(charNum,MARIO_FIRE_FLOWER); setDamageInfoArr(); setState(ST_TAKE_DAMAGE); lockState = true; hitAnimation(); alpha = TD_ALPHA; if ( GameSettings.classicMode && GameSettings.classicDamageResponse == ClassicDamageResponse.LoseCurrent && upgradeIsActive(MUSHROOM) ) { lockFrame = true; stopAnim = true; startReplaceColor(); } else { lockFrame = false; mainAnimTmr = ANIM_TMR_FOR_TAKE_DAMAGE; gotoAndStop(FL_TAKE_DAMAGE_START); stopAnim = false; } } override protected function hitAnimation():void { } override protected function swapPs():void { if (cState == ST_TAKE_DAMAGE && nPState == PS_NORMAL) return; super.swapPs(); } override protected function takeDamageEnd():void { super.takeDamageEnd(); if (!starPwr) endReplaceColor(); if (nPState != 1) return; shoot = false; checkFrame(); } override public function hitEnemy(enemy:Enemy,side:String):void { if (enemy is Bloopa && ny == BLOOPA_NO_HURT_Y && onGround) return; super.hitEnemy(enemy,side); } override protected function enterPipeVert():void { super.enterPipeVert(); // if (canCrouch()) setStopFrame(FL_PIPE); } override public function groundAbove(g:Ground):void { setJumpRise(false); if (cState == ST_CROUCH) hitCeiling = true; else super.groundAbove(g); } private function setJumpRise(value:Boolean):void { if (jumpRise && !value && !onGround) // deactivate { if (!underWater) { defyGrav = false; if (releasedJumpBtn) frictionY = true; } /*else { vyMax = VY_MAX_WATER; if (!jmpBtn) vxMax = VX_MAX_WATER_NORMAL; else vxMax = VX_MAX_WATER_BOOST; }*/ } else if (!jumpRise && value) // activate { defyGrav = true; lastOnGround = false; frictionY = false; } jumpRise = value; } private function determineAppearancePossibilities():void { appearancePossibilities = AP_BIG_AND_SMALL; // if (this is Mario) // { // if (skinNum == Mario.SKIN_MARIO_SMB2_NES) // appearancePossibilities = AP_BIG_ONLY; // else if (skinNum == Mario.SKIN_MARIO_SMAS_SNES) // appearancePossibilities = AP_SMALL_ONLY; // } // else if (this is Luigi) // { // // } } override public function setCurrentBmdSkin(bmc:BmdSkinCont, characterInitiating:Boolean = false):void { super.setCurrentBmdSkin(bmc); determineAppearancePossibilities(); var stopAnimTemp:Boolean = stopAnim; changeAppearance(); // var cf:int = currentFrame; // gotoAndStop(FL_WALK_DUR_TEST_FRAME); // gotoAndStop(cf); // removeObjsFromFrames(FEATHER_NAME, [ FL_WALK_DUR_TEST_FRAME ], false, int(false) ); if ( frameIsEmpty(FL_WALK_DUR_TEST_FRAME) ) { walkEndLab = FL_WALK_END_NES; } else walkEndLab = FL_WALK_END_NORMAL; if (bmc.skinNum == 0) singleFirePowerFrame = false; else { singleFirePowerFrame = true; if (upgradeIsActive(MARIO_FIRE_FLOWER) && shoot) setStopFrame(FL_SHOOT); } if (cState == ST_WALK && !shoot) setPlayFrame(FL_WALK_START); stopAnim = stopAnimTemp; if (!frameIsEmpty(FL_FALL_TEST_FRAME)) hasFallFrame = true; else { hasFallFrame = false; var cl:String = currentLabel; if (cl == convLab(FL_FALL_START) || cl == convLab(FL_FALL_END)) setStopFrame(walkStartLab); } if (!frameIsEmpty(FL_SMALL_CROUCH_TEST_FRAME)) hasSmallCrouchFrame = true; else { hasSmallCrouchFrame = false; if (cl == convLab(FL_SMALL_CROUCH_TEST_FRAME)) setStopFrame(FL_STAND); } // if (this is Luigi && (skinNum == 4 || skinNum == 5)) if (skinNum == 4 || skinNum == 5) { walkAnimTmr1 = AnimationTimers.ANIM_VERY_SLOW_TMR; walkAnimTmr2 = AnimationTimers.ANIM_SLOW_TMR; walkAnimTmr3 = AnimationTimers.ANIM_SLOW_TMR; runAnimTmr1 = AnimationTimers.ANIM_MODERATE_TMR; runAnimTmr2 = AnimationTimers.ANIM_MIN_FAST_TMR; } else { walkAnimTmr1 = AnimationTimers.ANIM_VERY_SLOW_TMR; walkAnimTmr2 = AnimationTimers.ANIM_SLOW_TMR; walkAnimTmr3 = AnimationTimers.ANIM_MODERATE_TMR; runAnimTmr1 = AnimationTimers.ANIM_MIN_FAST_TMR; runAnimTmr2 = AnimationTimers.ANIM_FAST_TMR; } checkState(); } override protected function playDefaultPickupSoundEffect():void { SND_MNGR.playSound(SoundNames.SFX_GAME_POWER_UP); } override protected function prepareDrawCharacter(skinAppearanceState:int = -1):void { // skinAppearanceState = SKIN_APPEARANCE_NUM_FIRE_POWER; // trace(""mario luigi skin: ""+skinAppearanceState); switch (skinAppearanceState) { case SKIN_APPEARANCE_NUM_SMALL: { changeAppearance(APPEARANCE_NUM_SMALL, PAL_COL_NORMAL); break; } case SKIN_APPEARANCE_NUM_BIG: { changeAppearance(APPEARANCE_NUM_BIG, PAL_COL_NORMAL); break; } case SKIN_APPEARANCE_NUM_FIRE_POWER: { changeAppearance(APPEARANCE_NUM_BIG, PAL_COL_FIRE_FLOWER); break; } default: { changeAppearance(); } } drawFrameLabel = convLab(FL_STAND); super.prepareDrawCharacter(skinAppearanceState); } override protected function initiateNormalDeath(source:LevObj = null):void { super.initiateNormalDeath(source); SND_MNGR.changeMusic(MusicType.DIE); setJumpRise(false); stopAnim = true; stopHit = true; stopUpdate = true; changeAppearance(APPEARANCE_NUM_SMALL, PAL_COL_NORMAL); setStopFrame(""die""); lockFrame = true; onGround = false; gravity = DIE_GRAVITY; dieFreezeTmr = new CustomTimer(DIE_FREEZE_TMR_DUR,1); addTmr(dieFreezeTmr); dieFreezeTmr.addEventListener(TimerEvent.TIMER_COMPLETE,dieFreezeTmrLsr,false,0,true); dieFreezeTmr.start(); } override protected function initiatePitDeath():void { _dieTmrDel = DIE_TMR_DEL_PIT; super.initiatePitDeath(); SND_MNGR.changeMusic( MusicType.DIE ); } override public function slideDownFlagPole():void { super.slideDownFlagPole(); shoot = false; setPlayFrame(""climbStart""); nx = level.flagPole.hMidX; mainAnimTmr = FLAG_POLE_SLIDE_ANIM_TMR; } override public function stopFlagPoleSlide():void { super.stopFlagPoleSlide(); scaleX = -scaleX; setStopFrame(""climbStart""); lockFrame = true; } override public function getAxe(axe:BowserAxe):void { super.getAxe(axe); if (level.levNum == STAT_MNGR.DUNGEON_LEVEL_NUM) fxWalk = FX_DUNGEON_GOT_AXE; } override protected function getOnVine(_vine:Vine):void { var right:Boolean; if (nx > _vine.hMidX) right = true; super.getOnVine(_vine); if (right) { nx += CLIMB_OFFSET_X; scaleX = -1; } else { nx -= CLIMB_OFFSET_X; scaleX = 1; } } override protected function flagDelayTmrLsr(e:TimerEvent):void { lockFrame = false; super.flagDelayTmrLsr(e); nx += FLAG_POLE_X_OFS; this.x = nx; level.rightScrollPosOvRd = localToGlobal(ZERO_PT).x; if (level.waterLevel) { setPlayFrame(""swimStillStart""); setState(ST_JUMP); jumped = true; //checkState(); } } private function dieFreezeTmrLsr(e:TimerEvent):void { dieFreezeTmr.stop(); dieFreezeTmr.removeEventListener(TimerEvent.TIMER_COMPLETE,dieFreezeTmrLsr); dieFreezeTmr = null; EVENT_MNGR.startDieTmr(DIE_TMR_DEL_NORMAL); stopUpdate = false; gravity = DIE_GRAVITY; vyMaxPsv = DIE_VY_MAX_PSV; vy = -DIE_BOOST; jumped = true; frictionY = false; } override public function pressJmpBtn():void { if (cState == ST_VINE) return; if (onGround || (level.waterLevel && underWater)) jump(); /*else if (GameSettings.DEBUG_MODE && !onGround && !onSpring) { bounce(null); SND_MNGR.playSound(SoundNames.SFX_GAME_STOMP); }*/ super.pressJmpBtn(); } override public function fallenCharSelScrn():void { super.fallenCharSelScrn(); cancelCheckState = true; setStopFrame(FL_DIE); } // CHECKFRAME override public function checkFrame():void { var cf:int = currentFrame; var cfl:String = currentFrameLabel; if ((cState == ""walk"" || cState == ""pipe"") && cf == getLabNum(walkEndLab) + 1) setPlayFrame(FL_WALK_START); else if (cState == ST_GET_MUSHROOM && cfl == FL_GROW_END) { setStopFrame(hitFrameLabel); } else if ( cf == getLabNum(FL_JUMP_END) + 1 && !underWater ) setPlayFrame(FL_JUMP_START); else if ( cf == getLabNum(FL_FALL_END) + 1 && !underWater ) setPlayFrame(FL_FALL_START); else if (cState == ST_TAKE_DAMAGE && cfl == FL_TAKE_DAMAGE_END) { gotoAndStop(hitFrameLabel+""_1""); stopAnim = true; } else if (cState == ST_FLAG_SLIDE || cState == ST_VINE) { if (cf == getLabNum(FL_CLIMB_END) + 1) setPlayFrame(FL_CLIMB_START); } else if (level.waterLevel) { if (cState == ""jump"" && cf == getLabNum(""swimStillEnd"") + 1) setPlayFrame(""swimStillStart""); else if (cState == ""paddle"") { if (cf == getLabNum(""paddleSlowEnd"") + 1 || currentFrame == getLabNum(""paddleFastEnd"") + 1) { setPlayFrame(""swimStillStart""); setState(""jump""); } } } super.checkFrame(); } override protected function get currentSkinAppearanceNum():int { if (level is TitleLevel) return SKIN_APPEARANCE_NUM_SMALL; if ( upgradeIsActive(MARIO_FIRE_FLOWER) ) return SKIN_APPEARANCE_NUM_FIRE_POWER; else if ( upgradeIsActive(MUSHROOM) ) return SKIN_APPEARANCE_NUM_BIG; else return SKIN_APPEARANCE_NUM_SMALL; } override public function cleanUp():void { super.cleanUp(); if (fellInPit) { changeAppearance(); } } override public function checkStgPos():void { if (dead) return; super.checkStgPos(); } override protected function removeListeners():void { super.removeListeners(); SHOOT_TMR.removeEventListener(TimerEvent.TIMER_COMPLETE,shootTmrHandler); } override protected function reattachLsrs():void { super.reattachLsrs(); SHOOT_TMR.addEventListener(TimerEvent.TIMER_COMPLETE,shootTmrHandler,false,0,true); } } }",12253,False,2226.6276907518773,median "/* Feathers Copyright 2012-2015 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.controls.popups.CalloutPopUpContentManager; import feathers.controls.popups.DropDownPopUpContentManager; import feathers.controls.popups.IPersistentPopUpContentManager; import feathers.controls.popups.IPopUpContentManager; import feathers.controls.popups.IPopUpContentManagerWithPrompt; import feathers.controls.popups.VerticalCenteredPopUpContentManager; import feathers.core.FeathersControl; import feathers.core.IFocusDisplayObject; import feathers.core.IToggle; import feathers.core.PropertyProxy; import feathers.data.ListCollection; import feathers.events.CollectionEventType; import feathers.events.FeathersEventType; import feathers.skins.IStyleProvider; import feathers.system.DeviceCapabilities; import flash.ui.Keyboard; import starling.core.Starling; import starling.events.Event; import starling.events.EventDispatcher; import starling.events.KeyboardEvent; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; import starling.utils.SystemUtil; /** * Dispatched when the pop-up list is opened. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType starling.events.Event.OPEN */ [Event(name=""open"",type=""starling.events.Event"")] /** * Dispatched when the pop-up list is closed. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType starling.events.Event.CLOSE */ [Event(name=""close"",type=""starling.events.Event"")] /** * Dispatched when the selected item changes. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Displays a button that may be triggered to display a pop-up list. * The list may be customized to display in different ways, such as a * drop-down, in a Callout, or as a modal overlay. * *

The following example creates a picker list, gives it a data provider, * tells the item renderer how to interpret the data, and listens for when * the selection changes:

* * * var list:PickerList = new PickerList(); * * list.dataProvider = new ListCollection( * [ * { text: ""Milk"", thumbnail: textureAtlas.getTexture( ""milk"" ) }, * { text: ""Eggs"", thumbnail: textureAtlas.getTexture( ""eggs"" ) }, * { text: ""Bread"", thumbnail: textureAtlas.getTexture( ""bread"" ) }, * { text: ""Chicken"", thumbnail: textureAtlas.getTexture( ""chicken"" ) }, * ]); * * list.listProperties.itemRendererFactory = function():IListItemRenderer * { * var renderer:DefaultListItemRenderer = new DefaultListItemRenderer(); * renderer.labelField = ""text""; * renderer.iconSourceField = ""thumbnail""; * return renderer; * }; * * list.addEventListener( Event.CHANGE, list_changeHandler ); * * this.addChild( list ); * * @see ../../../help/picker-list.html How to use the Feathers PickerList component */ public class PickerList extends FeathersControl implements IFocusDisplayObject { /** * @private */ protected static const INVALIDATION_FLAG_BUTTON_FACTORY:String = ""buttonFactory""; /** * @private */ protected static const INVALIDATION_FLAG_LIST_FACTORY:String = ""listFactory""; /** * The default value added to the styleNameList of the button. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_BUTTON:String = ""feathers-picker-list-button""; /** * The default value added to the styleNameList of the pop-up * list. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_LIST:String = ""feathers-picker-list-list""; /** * The default IStyleProvider for all PickerList * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * @private */ protected static function defaultButtonFactory():Button { return new Button(); } /** * @private */ protected static function defaultListFactory():List { return new List(); } /** * Constructor. */ public function PickerList() { super(); } /** * The default value added to the styleNameList of the * button. This variable is protected so that sub-classes * can customize the button style name in their constructors instead of * using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_BUTTON. * *

To customize the button style name without subclassing, see * customButtonStyleName.

* * @see #customButtonStyleName * @see feathers.core.FeathersControl#styleNameList */ protected var buttonStyleName:String = DEFAULT_CHILD_STYLE_NAME_BUTTON; /** * The default value added to the styleNameList of the * pop-up list. This variable is protected so that * sub-classes can customize the list style name in their constructors * instead of using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_LIST. * *

To customize the pop-up list name without subclassing, see * customListStyleName.

* * @see #customListStyleName * @see feathers.core.FeathersControl#styleNameList */ protected var listStyleName:String = DEFAULT_CHILD_STYLE_NAME_LIST; /** * The button sub-component. * *

For internal use in subclasses.

* * @see #buttonFactory * @see #createButton() */ protected var button:Button; /** * The list sub-component. * *

For internal use in subclasses.

* * @see #listFactory * @see #createList() */ protected var list:List; /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return PickerList.globalStyleProvider; } /** * @private */ protected var _dataProvider:ListCollection; /** * The collection of data displayed by the list. * *

The following example passes in a data provider and tells the item * renderer how to interpret the data:

* * * list.dataProvider = new ListCollection( * [ * { text: ""Milk"", thumbnail: textureAtlas.getTexture( ""milk"" ) }, * { text: ""Eggs"", thumbnail: textureAtlas.getTexture( ""eggs"" ) }, * { text: ""Bread"", thumbnail: textureAtlas.getTexture( ""bread"" ) }, * { text: ""Chicken"", thumbnail: textureAtlas.getTexture( ""chicken"" ) }, * ]); * * list.listProperties.itemRendererFactory = function():IListItemRenderer * { * var renderer:DefaultListItemRenderer = new DefaultListItemRenderer(); * renderer.labelField = ""text""; * renderer.iconSourceField = ""thumbnail""; * return renderer; * }; * * @default null */ public function get dataProvider():ListCollection { return this._dataProvider; } /** * @private */ public function set dataProvider(value:ListCollection):void { if(this._dataProvider == value) { return; } var oldSelectedIndex:int = this.selectedIndex; var oldSelectedItem:Object = this.selectedItem; if(this._dataProvider) { this._dataProvider.removeEventListener(CollectionEventType.RESET, dataProvider_multipleEventHandler); this._dataProvider.removeEventListener(CollectionEventType.ADD_ITEM, dataProvider_multipleEventHandler); this._dataProvider.removeEventListener(CollectionEventType.REMOVE_ITEM, dataProvider_multipleEventHandler); this._dataProvider.removeEventListener(CollectionEventType.REPLACE_ITEM, dataProvider_multipleEventHandler); } this._dataProvider = value; if(this._dataProvider) { this._dataProvider.addEventListener(CollectionEventType.RESET, dataProvider_multipleEventHandler); this._dataProvider.addEventListener(CollectionEventType.ADD_ITEM, dataProvider_multipleEventHandler); this._dataProvider.addEventListener(CollectionEventType.REMOVE_ITEM, dataProvider_multipleEventHandler); this._dataProvider.addEventListener(CollectionEventType.REPLACE_ITEM, dataProvider_multipleEventHandler); } if(!this._dataProvider || this._dataProvider.length == 0) { this.selectedIndex = -1; } else { this.selectedIndex = 0; } //this ensures that Event.CHANGE will dispatch for selectedItem //changing, even if selectedIndex has not changed. if(this.selectedIndex == oldSelectedIndex && this.selectedItem != oldSelectedItem) { this.dispatchEventWith(Event.CHANGE); } this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _ignoreSelectionChanges:Boolean = false; /** * @private */ protected var _selectedIndex:int = -1; /** * The index of the currently selected item. Returns -1 if * no item is selected. * *

The following example selects an item by its index:

* * * list.selectedIndex = 2; * *

The following example clears the selected index:

* * * list.selectedIndex = -1; * *

The following example listens for when selection changes and * requests the selected index:

* * * function list_changeHandler( event:Event ):void * { * var list:PickerList = PickerList( event.currentTarget ); * var index:int = list.selectedIndex; * * } * list.addEventListener( Event.CHANGE, list_changeHandler ); * * @default -1 * * @see #selectedItem */ public function get selectedIndex():int { return this._selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { if(this._selectedIndex == value) { return; } this._selectedIndex = value; this.invalidate(INVALIDATION_FLAG_SELECTED); this.dispatchEventWith(Event.CHANGE); } /** * The currently selected item. Returns null if no item is * selected. * *

The following example changes the selected item:

* * * list.selectedItem = list.dataProvider.getItemAt(0); * *

The following example clears the selected item:

* * * list.selectedItem = null; * *

The following example listens for when selection changes and * requests the selected item:

* * * function list_changeHandler( event:Event ):void * { * var list:PickerList = PickerList( event.currentTarget ); * var item:Object = list.selectedItem; * * } * list.addEventListener( Event.CHANGE, list_changeHandler ); * * @default null * * @see #selectedIndex */ public function get selectedItem():Object { if(!this._dataProvider || this._selectedIndex < 0 || this._selectedIndex >= this._dataProvider.length) { return null; } return this._dataProvider.getItemAt(this._selectedIndex); } /** * @private */ public function set selectedItem(value:Object):void { if(!this._dataProvider) { this.selectedIndex = -1; return; } this.selectedIndex = this._dataProvider.getItemIndex(value); } /** * @private */ protected var _prompt:String; /** * Text displayed by the button sub-component when no items are * currently selected. * *

In the following example, a prompt is given to the picker list * and the selected item is cleared to display the prompt:

* * * list.prompt = ""Select an Item""; * list.selectedIndex = -1; * * @default null */ public function get prompt():String { return this._prompt; } /** * @private */ public function set prompt(value:String):void { if(this._prompt == value) { return; } this._prompt = value; this.invalidate(INVALIDATION_FLAG_SELECTED); } /** * @private */ protected var _labelField:String = ""label""; /** * The field in the selected item that contains the label text to be * displayed by the picker list's button control. If the selected item * does not have this field, and a labelFunction is not * defined, then the picker list will default to calling * toString() on the selected item. To omit the * label completely, define a labelFunction that returns an * empty string. * *

Important: This value only affects the selected * item displayed by the picker list's button control. It will not * affect the label text of the pop-up list's item renderers.

* *

In the following example, the label field is changed:

* * * list.labelField = ""text""; * * @default ""label"" * * @see #labelFunction */ public function get labelField():String { return this._labelField; } /** * @private */ public function set labelField(value:String):void { if(this._labelField == value) { return; } this._labelField = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _labelFunction:Function; /** * A function used to generate label text for the selected item * displayed by the picker list's button control. If this * function is not null, then the labelField will be * ignored. * *

Important: This value only affects the selected * item displayed by the picker list's button control. It will not * affect the label text of the pop-up list's item renderers.

* *

The function is expected to have the following signature:

*
function( item:Object ):String
* *

All of the label fields and functions, ordered by priority:

*
    *
  1. labelFunction
  2. *
  3. labelField
  4. *
* *

In the following example, the label field is changed:

* * * list.labelFunction = function( item:Object ):String * { * return item.firstName + "" "" + item.lastName; * }; * * @default null * * @see #labelField */ public function get labelFunction():Function { return this._labelFunction; } /** * @private */ public function set labelFunction(value:Function):void { this._labelFunction = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _popUpContentManager:IPopUpContentManager; /** * A manager that handles the details of how to display the pop-up list. * *

In the following example, a pop-up content manager is provided:

* * * list.popUpContentManager = new CalloutPopUpContentManager(); * * @default null */ public function get popUpContentManager():IPopUpContentManager { return this._popUpContentManager; } /** * @private */ public function set popUpContentManager(value:IPopUpContentManager):void { if(this._popUpContentManager == value) { return; } if(this._popUpContentManager is EventDispatcher) { var dispatcher:EventDispatcher = EventDispatcher(this._popUpContentManager); dispatcher.removeEventListener(Event.OPEN, popUpContentManager_openHandler); dispatcher.removeEventListener(Event.CLOSE, popUpContentManager_closeHandler); } this._popUpContentManager = value; if(this._popUpContentManager is EventDispatcher) { dispatcher = EventDispatcher(this._popUpContentManager); dispatcher.addEventListener(Event.OPEN, popUpContentManager_openHandler); dispatcher.addEventListener(Event.CLOSE, popUpContentManager_closeHandler); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _typicalItemWidth:Number = NaN; /** * @private */ protected var _typicalItemHeight:Number = NaN; /** * @private */ protected var _typicalItem:Object = null; /** * Used to auto-size the list. If the list's width or height is NaN, the * list will try to automatically pick an ideal size. This item is * used in that process to create a sample item renderer. * *

The following example provides a typical item:

* * * list.typicalItem = { text: ""A typical item"", thumbnail: texture }; * list.itemRendererProperties.labelField = ""text""; * list.itemRendererProperties.iconSourceField = ""thumbnail""; * * @default null */ public function get typicalItem():Object { return this._typicalItem; } /** * @private */ public function set typicalItem(value:Object):void { if(this._typicalItem == value) { return; } this._typicalItem = value; this._typicalItemWidth = NaN; this._typicalItemHeight = NaN; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _buttonFactory:Function; /** * A function used to generate the picker list's button sub-component. * The button must be an instance of Button. This factory * can be used to change properties on the button when it is first * created. For instance, if you are skinning Feathers components * without a theme, you might use this factory to set skins and other * styles on the button. * *

The function should have the following signature:

*
function():Button
* *

In the following example, a custom button factory is passed to the * picker list:

* * * list.buttonFactory = function():Button * { * var button:Button = new Button(); * button.defaultSkin = new Image( upTexture ); * button.downSkin = new Image( downTexture ); * return button; * }; * * @default null * * @see feathers.controls.Button * @see #buttonProperties */ public function get buttonFactory():Function { return this._buttonFactory; } /** * @private */ public function set buttonFactory(value:Function):void { if(this._buttonFactory == value) { return; } this._buttonFactory = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _customButtonStyleName:String; /** * A style name to add to the picker list's button sub-component. * Typically used by a theme to provide different styles to different * picker lists. * *

In the following example, a custom button style name is passed to * the picker list:

* * * list.customButtonStyleName = ""my-custom-button""; * *

In your theme, you can target this sub-component style name to * provide different styles than the default:

* * * getStyleProviderForClass( Button ).setFunctionForStyleName( ""my-custom-button"", setCustomButtonStyles ); * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_BUTTON * @see feathers.core.FeathersControl#styleNameList * @see #buttonFactory * @see #buttonProperties */ public function get customButtonStyleName():String { return this._customButtonStyleName; } /** * @private */ public function set customButtonStyleName(value:String):void { if(this._customButtonStyleName == value) { return; } this._customButtonStyleName = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _buttonProperties:PropertyProxy; /** * An object that stores properties for the picker's button * sub-component, and the properties will be passed down to the button * when the picker validates. For a list of available * properties, refer to * feathers.controls.Button. * *

If the subcomponent has its own subcomponents, their properties * can be set too, using attribute @ notation. For example, * to set the skin on the thumb which is in a SimpleScrollBar, * which is in a List, you can use the following syntax:

*
list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);
* *

Setting properties in a buttonFactory function * instead of using buttonProperties will result in better * performance.

* *

In the following example, the button properties are passed to the * picker list:

* * * list.buttonProperties.defaultSkin = new Image( upTexture ); * list.buttonProperties.downSkin = new Image( downTexture ); * * @default null * * @see #buttonFactory * @see feathers.controls.Button */ public function get buttonProperties():Object { if(!this._buttonProperties) { this._buttonProperties = new PropertyProxy(childProperties_onChange); } return this._buttonProperties; } /** * @private */ public function set buttonProperties(value:Object):void { if(this._buttonProperties == value) { return; } if(!value) { value = new PropertyProxy(); } if(!(value is PropertyProxy)) { var newValue:PropertyProxy = new PropertyProxy(); for(var propertyName:String in value) { newValue[propertyName] = value[propertyName]; } value = newValue; } if(this._buttonProperties) { this._buttonProperties.removeOnChangeCallback(childProperties_onChange); } this._buttonProperties = PropertyProxy(value); if(this._buttonProperties) { this._buttonProperties.addOnChangeCallback(childProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _listFactory:Function; /** * A function used to generate the picker list's pop-up list * sub-component. The list must be an instance of List. * This factory can be used to change properties on the list when it is * first created. For instance, if you are skinning Feathers components * without a theme, you might use this factory to set skins and other * styles on the list. * *

The function should have the following signature:

*
function():List
* *

In the following example, a custom list factory is passed to the * picker list:

* * * list.listFactory = function():List * { * var popUpList:List = new List(); * popUpList.backgroundSkin = new Image( texture ); * return popUpList; * }; * * @default null * * @see feathers.controls.List * @see #listProperties */ public function get listFactory():Function { return this._listFactory; } /** * @private */ public function set listFactory(value:Function):void { if(this._listFactory == value) { return; } this._listFactory = value; this.invalidate(INVALIDATION_FLAG_LIST_FACTORY); } /** * @private */ protected var _customListStyleName:String; /** * A style name to add to the picker list's list sub-component. * Typically used by a theme to provide different styles to different * picker lists. * *

In the following example, a custom list style name is passed to the * picker list:

* * * list.customListStyleName = ""my-custom-list""; * *

In your theme, you can target this sub-component style name to provide * different styles than the default:

* * * getStyleProviderForClass( List ).setFunctionForStyleName( ""my-custom-list"", setCustomListStyles ); * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_LIST * @see feathers.core.FeathersControl#styleNameList * @see #listFactory * @see #listProperties */ public function get customListStyleName():String { return this._customListStyleName; } /** * @private */ public function set customListStyleName(value:String):void { if(this._customListStyleName == value) { return; } this._customListStyleName = value; this.invalidate(INVALIDATION_FLAG_LIST_FACTORY); } /** * @private */ protected var _listProperties:PropertyProxy; /** * An object that stores properties for the picker's pop-up list * sub-component, and the properties will be passed down to the pop-up * list when the picker validates. For a list of available * properties, refer to * feathers.controls.List. * *

If the subcomponent has its own subcomponents, their properties * can be set too, using attribute @ notation. For example, * to set the skin on the thumb which is in a SimpleScrollBar, * which is in a List, you can use the following syntax:

*
list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);
* *

Setting properties in a listFactory function * instead of using listProperties will result in better * performance.

* *

In the following example, the list properties are passed to the * picker list:

* * * list.listProperties.backgroundSkin = new Image( texture ); * * @default null * * @see #listFactory * @see feathers.controls.List */ public function get listProperties():Object { if(!this._listProperties) { this._listProperties = new PropertyProxy(childProperties_onChange); } return this._listProperties; } /** * @private */ public function set listProperties(value:Object):void { if(this._listProperties == value) { return; } if(!value) { value = new PropertyProxy(); } if(!(value is PropertyProxy)) { var newValue:PropertyProxy = new PropertyProxy(); for(var propertyName:String in value) { newValue[propertyName] = value[propertyName]; } value = newValue; } if(this._listProperties) { this._listProperties.removeOnChangeCallback(childProperties_onChange); } this._listProperties = PropertyProxy(value); if(this._listProperties) { this._listProperties.addOnChangeCallback(childProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _toggleButtonOnOpenAndClose:Boolean = false; /** * Determines if the isSelected property of the picker * list's button sub-component is toggled when the list is opened and * closed, if the class used to create the thumb implements the * IToggle interface. Useful for skinning to provide a * different appearance for the button based on whether the list is open * or not. * *

In the following example, the button is toggled on open and close:

* * * list.toggleButtonOnOpenAndClose = true; * * @default false * * @see feathers.core.IToggle * @see feathers.controls.ToggleButton */ public function get toggleButtonOnOpenAndClose():Boolean { return this._toggleButtonOnOpenAndClose; } /** * @private */ public function set toggleButtonOnOpenAndClose(value:Boolean):void { if(this._toggleButtonOnOpenAndClose == value) { return; } this._toggleButtonOnOpenAndClose = value; if(this.button is IToggle) { if(this._toggleButtonOnOpenAndClose && this._popUpContentManager.isOpen) { IToggle(this.button).isSelected = true; } else { IToggle(this.button).isSelected = false; } } } /** * @inheritDoc */ public function get baseline():Number { if(!this.button) { return this.scaledActualHeight; } return this.scaleY * (this.button.y + this.button.baseline); } /** * @private */ protected var _isOpenListPending:Boolean = false; /** * @private */ protected var _isCloseListPending:Boolean = false; /** * Using labelField and labelFunction, * generates a label from the selected item to be displayed by the * picker list's button control. * *

Important: This value only affects the selected * item displayed by the picker list's button control. It will not * affect the label text of the pop-up list's item renderers.

*/ public function itemToLabel(item:Object):String { if(this._labelFunction != null) { var labelResult:Object = this._labelFunction(item); if(labelResult is String) { return labelResult as String; } return labelResult.toString(); } else if(this._labelField != null && item && item.hasOwnProperty(this._labelField)) { labelResult = item[this._labelField]; if(labelResult is String) { return labelResult as String; } return labelResult.toString(); } else if(item is String) { return item as String; } else if(item) { return item.toString(); } return """"; } /** * @private */ protected var _buttonHasFocus:Boolean = false; /** * @private */ protected var _buttonTouchPointID:int = -1; /** * @private */ protected var _listIsOpenOnTouchBegan:Boolean = false; /** * Opens the pop-up list, if it isn't already open. */ public function openList():void { this._isCloseListPending = false; if(this._popUpContentManager.isOpen) { return; } if(!this._isValidating && this.isInvalid()) { this._isOpenListPending = true; return; } this._isOpenListPending = false; if(this._popUpContentManager is IPopUpContentManagerWithPrompt) { IPopUpContentManagerWithPrompt(this._popUpContentManager).prompt = this._prompt; } this._popUpContentManager.open(this.list, this); this.list.scrollToDisplayIndex(this._selectedIndex); this.list.validate(); if(this._focusManager) { this._focusManager.focus = this.list; this.stage.addEventListener(KeyboardEvent.KEY_UP, stage_keyUpHandler); this.list.addEventListener(FeathersEventType.FOCUS_OUT, list_focusOutHandler); } } /** * Closes the pop-up list, if it is open. */ public function closeList():void { this._isOpenListPending = false; if(!this._popUpContentManager.isOpen) { return; } if(!this._isValidating && this.isInvalid()) { this._isCloseListPending = true; return; } this._isCloseListPending = false; this.list.validate(); //don't clean up anything from openList() in closeList(). The list //may be closed by removing it from the PopUpManager, which would //result in closeList() never being called. //instead, clean up in the Event.REMOVED_FROM_STAGE listener. this._popUpContentManager.close(); } /** * @inheritDoc */ override public function dispose():void { if(this.list) { this.closeList(); this.list.dispose(); this.list = null; } if(this._popUpContentManager) { this._popUpContentManager.dispose(); this._popUpContentManager = null; } //clearing selection now so that the data provider setter won't //cause a selection change that triggers events. this._selectedIndex = -1; this.dataProvider = null; super.dispose(); } /** * @private */ override public function showFocus():void { if(!this.button) { return; } this.button.showFocus(); } /** * @private */ override public function hideFocus():void { if(!this.button) { return; } this.button.hideFocus(); } /** * @private */ override protected function initialize():void { if(!this._popUpContentManager) { if(SystemUtil.isDesktop) { this.popUpContentManager = new DropDownPopUpContentManager(); } else if(DeviceCapabilities.isTablet(Starling.current.nativeStage)) { this.popUpContentManager = new CalloutPopUpContentManager(); } else { this.popUpContentManager = new VerticalCenteredPopUpContentManager(); } } } /** * @private */ override protected function draw():void { var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var selectionInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SELECTED); var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); var buttonFactoryInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_BUTTON_FACTORY); var listFactoryInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_LIST_FACTORY); if(buttonFactoryInvalid) { this.createButton(); } if(listFactoryInvalid) { this.createList(); } if(buttonFactoryInvalid || stylesInvalid || selectionInvalid) { //this section asks the button to auto-size again, if our //explicit dimensions aren't set. //set this before buttonProperties is used because it might //contain width or height changes. if(this.explicitWidth !== this.explicitWidth) //isNaN { this.button.width = NaN; } if(this.explicitHeight !== this.explicitHeight) //isNaN { this.button.height = NaN; } } if(buttonFactoryInvalid || stylesInvalid) { this._typicalItemWidth = NaN; this._typicalItemHeight = NaN; this.refreshButtonProperties(); } if(listFactoryInvalid || stylesInvalid) { this.refreshListProperties(); } if(listFactoryInvalid || dataInvalid) { var oldIgnoreSelectionChanges:Boolean = this._ignoreSelectionChanges; this._ignoreSelectionChanges = true; this.list.dataProvider = this._dataProvider; this._ignoreSelectionChanges = oldIgnoreSelectionChanges; } if(buttonFactoryInvalid || listFactoryInvalid || stateInvalid) { this.button.isEnabled = this._isEnabled; this.list.isEnabled = this._isEnabled; } if(buttonFactoryInvalid || dataInvalid || selectionInvalid) { this.refreshButtonLabel(); } if(listFactoryInvalid || dataInvalid || selectionInvalid) { oldIgnoreSelectionChanges = this._ignoreSelectionChanges; this._ignoreSelectionChanges = true; this.list.selectedIndex = this._selectedIndex; this._ignoreSelectionChanges = oldIgnoreSelectionChanges; } sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid; if(buttonFactoryInvalid || stylesInvalid || sizeInvalid || selectionInvalid) { this.layout(); } //final validation to avoid juggler next frame issues //also, to ensure that property changes on the pop-up list are fully //committed this.list.validate(); this.handlePendingActions(); } /** * If the component's dimensions have not been set explicitly, it will * measure its content and determine an ideal size for itself. If the * explicitWidth or explicitHeight member * variables are set, those value will be used without additional * measurement. If one is set, but not the other, the dimension with the * explicit value will not be measured, but the other non-explicit * dimension will still need measurement. * *

Calls setSizeInternal() to set up the * actualWidth and actualHeight member * variables used for layout.

* *

Meant for internal use, and subclasses may override this function * with a custom implementation.

*/ protected function autoSizeIfNeeded():Boolean { var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { return false; } var buttonWidth:Number; var buttonHeight:Number; if(this._typicalItem) { if(this._typicalItemWidth !== this._typicalItemWidth || //isNaN this._typicalItemHeight !== this._typicalItemHeight) //isNaN { var oldWidth:Number = this.button.width; var oldHeight:Number = this.button.height; this.button.width = NaN; this.button.height = NaN; if(this._typicalItem) { this.button.label = this.itemToLabel(this._typicalItem); } this.button.validate(); this._typicalItemWidth = this.button.width; this._typicalItemHeight = this.button.height; this.refreshButtonLabel(); this.button.width = oldWidth; this.button.height = oldHeight; } buttonWidth = this._typicalItemWidth; buttonHeight = this._typicalItemHeight; } else { this.button.validate(); buttonWidth = this.button.width; buttonHeight = this.button.height; } var newWidth:Number = this.explicitWidth; var newHeight:Number = this.explicitHeight; if(needsWidth) { if(buttonWidth === buttonWidth) //!isNaN { newWidth = buttonWidth; } else { newWidth = 0; } } if(needsHeight) { if(buttonHeight === buttonHeight) //!isNaN { newHeight = buttonHeight; } else { newHeight = 0; } } return this.setSizeInternal(newWidth, newHeight, false); } /** * Creates and adds the button sub-component and * removes the old instance, if one exists. * *

Meant for internal use, and subclasses may override this function * with a custom implementation.

* * @see #button * @see #buttonFactory * @see #customButtonStyleName */ protected function createButton():void { if(this.button) { this.button.removeFromParent(true); this.button = null; } var factory:Function = this._buttonFactory != null ? this._buttonFactory : defaultButtonFactory; var buttonStyleName:String = this._customButtonStyleName != null ? this._customButtonStyleName : this.buttonStyleName; this.button = Button(factory()); if(this.button is ToggleButton) { //we'll control the value of isSelected manually ToggleButton(this.button).isToggle = false; } this.button.styleNameList.add(buttonStyleName); this.button.addEventListener(TouchEvent.TOUCH, button_touchHandler); this.button.addEventListener(Event.TRIGGERED, button_triggeredHandler); this.addChild(this.button); } /** * Creates and adds the list sub-component and * removes the old instance, if one exists. * *

Meant for internal use, and subclasses may override this function * with a custom implementation.

* * @see #list * @see #listFactory * @see #customListStyleName */ protected function createList():void { if(this.list) { this.list.removeFromParent(false); //disposing separately because the list may not have a parent this.list.dispose(); this.list = null; } var factory:Function = this._listFactory != null ? this._listFactory : defaultListFactory; var listStyleName:String = this._customListStyleName != null ? this._customListStyleName : this.listStyleName; this.list = List(factory()); this.list.focusOwner = this; this.list.styleNameList.add(listStyleName); this.list.addEventListener(Event.CHANGE, list_changeHandler); this.list.addEventListener(Event.TRIGGERED, list_triggeredHandler); this.list.addEventListener(Event.REMOVED_FROM_STAGE, list_removedFromStageHandler); } /** * @private */ protected function refreshButtonLabel():void { if(this._selectedIndex >= 0) { this.button.label = this.itemToLabel(this.selectedItem); } else { this.button.label = this._prompt; } } /** * @private */ protected function refreshButtonProperties():void { for(var propertyName:String in this._buttonProperties) { var propertyValue:Object = this._buttonProperties[propertyName]; this.button[propertyName] = propertyValue; } } /** * @private */ protected function refreshListProperties():void { for(var propertyName:String in this._listProperties) { var propertyValue:Object = this._listProperties[propertyName]; this.list[propertyName] = propertyValue; } } /** * @private */ protected function layout():void { this.button.width = this.actualWidth; this.button.height = this.actualHeight; //final validation to avoid juggler next frame issues this.button.validate(); } /** * @private */ protected function handlePendingActions():void { if(this._isOpenListPending) { this.openList(); } if(this._isCloseListPending) { this.closeList(); } } /** * @private */ override protected function focusInHandler(event:Event):void { super.focusInHandler(event); this._buttonHasFocus = true; this.button.dispatchEventWith(FeathersEventType.FOCUS_IN); } /** * @private */ override protected function focusOutHandler(event:Event):void { if(this._buttonHasFocus) { this.button.dispatchEventWith(FeathersEventType.FOCUS_OUT); this._buttonHasFocus = false; } super.focusOutHandler(event); } /** * @private */ protected function childProperties_onChange(proxy:PropertyProxy, name:String):void { this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected function button_touchHandler(event:TouchEvent):void { if(this._buttonTouchPointID >= 0) { var touch:Touch = event.getTouch(this.button, TouchPhase.ENDED, this._buttonTouchPointID); if(!touch) { return; } this._buttonTouchPointID = -1; //the button will dispatch Event.TRIGGERED before this touch //listener is called, so it is safe to clear this flag. //we're clearing it because Event.TRIGGERED may also be //dispatched after keyboard input. this._listIsOpenOnTouchBegan = false; } else { touch = event.getTouch(this.button, TouchPhase.BEGAN); if(!touch) { return; } this._buttonTouchPointID = touch.id; this._listIsOpenOnTouchBegan = this._popUpContentManager.isOpen; } } /** * @private */ protected function button_triggeredHandler(event:Event):void { if(this._focusManager && this._listIsOpenOnTouchBegan) { return; } if(this._popUpContentManager.isOpen) { this.closeList(); return; } this.openList(); } /** * @private */ protected function list_changeHandler(event:Event):void { if(this._ignoreSelectionChanges || this._popUpContentManager is IPersistentPopUpContentManager) { return; } this.selectedIndex = this.list.selectedIndex; } /** * @private */ protected function popUpContentManager_openHandler(event:Event):void { if(this._toggleButtonOnOpenAndClose && this.button is IToggle) { IToggle(this.button).isSelected = true; } this.dispatchEventWith(Event.OPEN); } /** * @private */ protected function popUpContentManager_closeHandler(event:Event):void { if(this._popUpContentManager is IPersistentPopUpContentManager) { this.selectedIndex = this.list.selectedIndex; } if(this._toggleButtonOnOpenAndClose && this.button is IToggle) { IToggle(this.button).isSelected = false; } this.dispatchEventWith(Event.CLOSE); } /** * @private */ protected function list_removedFromStageHandler(event:Event):void { if(this._focusManager) { this.list.stage.removeEventListener(KeyboardEvent.KEY_UP, stage_keyUpHandler); this.list.removeEventListener(FeathersEventType.FOCUS_OUT, list_focusOutHandler); } } /** * @private */ protected function list_focusOutHandler(event:Event):void { if(!this._popUpContentManager.isOpen) { return; } this.closeList(); } /** * @private */ protected function list_triggeredHandler(event:Event):void { if(!this._isEnabled || this._popUpContentManager is IPersistentPopUpContentManager) { return; } this.closeList(); } /** * @private */ protected function dataProvider_multipleEventHandler():void { //we need to ensure that the pop-up list has received the new //selected index, or it might update the selected index to an //incorrect value after an item is added, removed, or replaced. this.validate(); } /** * @private */ protected function stage_keyUpHandler(event:KeyboardEvent):void { if(!this._popUpContentManager.isOpen) { return; } if(event.keyCode == Keyboard.ENTER) { this.closeList(); } } } }",12449,False,2458.750219835993,median "package com.junkbyte.console.view { import flash.text.TextField; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.events.KeyboardEvent; import flash.ui.Keyboard; import flash.geom.ColorTransform; import com.junkbyte.console.vos.Log; import com.junkbyte.console.Console; import com.junkbyte.console.core.LogReferences; import flash.geom.Rectangle; import com.junkbyte.console.core.Remoting; import flash.events.TextEvent; import flash.net.FileReference; import flash.system.System; import flash.system.Security; import flash.system.SecurityPanel; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.text.TextFieldType; import flash.events.FocusEvent; public class MainPanel extends ConsolePanel { public function MainPanel(param1:Console) { this._extraMenus = new Object(); super(param1); var _loc2_:int = style.menuFontSize; console.cl.addCLCmd(""filter"",this.setFilterText,""Filter console logs to matching string. When done, click on the * (global channel) at top."",true); console.cl.addCLCmd(""filterexp"",this.setFilterRegExp,""Filter console logs to matching regular expression"",true); console.cl.addCLCmd(""clearhistory"",this.clearCommandLineHistory,""Clear history of commands you have entered."",true); name = NAME; minWidth = 50; minHeight = 18; this._traceField = makeTF(""traceField""); this._traceField.wordWrap = true; this._traceField.multiline = true; this._traceField.y = _loc2_; this._traceField.addEventListener(Event.SCROLL,this.onTraceScroll); addChild(this._traceField); txtField = makeTF(""menuField""); txtField.wordWrap = true; txtField.multiline = true; txtField.autoSize = TextFieldAutoSize.RIGHT; txtField.height = _loc2_ + 6; txtField.y = -2; registerTFRoller(txtField,this.onMenuRollOver); addChild(txtField); this._cmdBG = new Shape(); this._cmdBG.name = ""commandBackground""; this._cmdBG.graphics.beginFill(style.commandLineColor,0.1); this._cmdBG.graphics.drawRoundRect(0,0,100,18,_loc2_,_loc2_); this._cmdBG.scale9Grid = new Rectangle(9,9,80,1); addChild(this._cmdBG); var _loc3_:TextFormat = new TextFormat(style.menuFont,style.menuFontSize,style.highColor); this._cmdField = new TextField(); this._cmdField.name = ""commandField""; this._cmdField.type = TextFieldType.INPUT; this._cmdField.x = 40; this._cmdField.height = _loc2_ + 6; this._cmdField.addEventListener(KeyboardEvent.KEY_DOWN,this.commandKeyDown); this._cmdField.addEventListener(KeyboardEvent.KEY_UP,this.commandKeyUp); this._cmdField.addEventListener(FocusEvent.FOCUS_IN,this.updateCmdHint); this._cmdField.addEventListener(FocusEvent.FOCUS_OUT,this.onCmdFocusOut); this._cmdField.defaultTextFormat = _loc3_; addChild(this._cmdField); this._hintField = makeTF(""hintField"",true); this._hintField.mouseEnabled = false; this._hintField.x = this._cmdField.x; this._hintField.autoSize = TextFieldAutoSize.LEFT; addChild(this._hintField); this.setHints(); _loc3_.color = style.commandLineColor; this._cmdPrefx = new TextField(); this._cmdPrefx.name = ""commandPrefx""; this._cmdPrefx.type = TextFieldType.DYNAMIC; this._cmdPrefx.x = 2; this._cmdPrefx.height = _loc2_ + 6; this._cmdPrefx.selectable = false; this._cmdPrefx.defaultTextFormat = _loc3_; this._cmdPrefx.addEventListener(MouseEvent.MOUSE_DOWN,this.onCmdPrefMouseDown); this._cmdPrefx.addEventListener(MouseEvent.MOUSE_MOVE,this.onCmdPrefRollOverOut); this._cmdPrefx.addEventListener(MouseEvent.ROLL_OUT,this.onCmdPrefRollOverOut); addChild(this._cmdPrefx); this._bottomLine = new Shape(); this._bottomLine.name = ""blinkLine""; this._bottomLine.alpha = 0.2; addChild(this._bottomLine); this._scroll = new Sprite(); this._scroll.name = ""scroller""; this._scroll.tabEnabled = false; this._scroll.y = _loc2_ + 4; this._scroll.buttonMode = true; this._scroll.addEventListener(MouseEvent.MOUSE_DOWN,this.onScrollbarDown,false,0,true); this._scroller = new Sprite(); this._scroller.name = ""scrollbar""; this._scroller.tabEnabled = false; this._scroller.y = style.controlSize; this._scroller.graphics.beginFill(style.controlColor,1); this._scroller.graphics.drawRect(-style.controlSize,0,style.controlSize,30); this._scroller.graphics.beginFill(0,0); this._scroller.graphics.drawRect(-style.controlSize * 2,0,style.controlSize * 2,30); this._scroller.graphics.endFill(); this._scroller.addEventListener(MouseEvent.MOUSE_DOWN,this.onScrollerDown,false,0,true); this._scroll.addChild(this._scroller); addChild(this._scroll); this._cmdField.visible = false; this._cmdPrefx.visible = false; this._cmdBG.visible = false; this.updateCLScope(""""); init(640,100,true); registerDragger(txtField); if(console.so[CL_HISTORY] is Array) { this._cmdsHistory = console.so[CL_HISTORY]; } else { console.so[CL_HISTORY] = this._cmdsHistory = new Array(); } if((config.rememberFilterSettings) && console.so[VIEWING_CH_HISTORY] is Array) { this._viewingChannels = console.so[VIEWING_CH_HISTORY]; } else { console.so[VIEWING_CH_HISTORY] = this._viewingChannels = new Array(); } if((config.rememberFilterSettings) && console.so[IGNORED_CH_HISTORY] is Array) { this._ignoredChannels = console.so[IGNORED_CH_HISTORY]; } if(this._viewingChannels.length > 0 || this._ignoredChannels == null) { console.so[IGNORED_CH_HISTORY] = this._ignoredChannels = new Array(); } if((config.rememberFilterSettings) && console.so[PRIORITY_HISTORY] is uint) { this._priority = console.so[PRIORITY_HISTORY]; } addEventListener(MouseEvent.MOUSE_WHEEL,this.onMouseWheel,false,0,true); addEventListener(TextEvent.LINK,this.linkHandler,false,0,true); addEventListener(Event.ADDED_TO_STAGE,this.stageAddedHandle,false,0,true); addEventListener(Event.REMOVED_FROM_STAGE,this.stageRemovedHandle,false,0,true); } public static const NAME:String = ""mainPanel""; private static const CL_HISTORY:String = ""clhistory""; private static const VIEWING_CH_HISTORY:String = ""viewingChannels""; private static const IGNORED_CH_HISTORY:String = ""ignoredChannels""; private static const PRIORITY_HISTORY:String = ""priority""; private var _traceField:TextField; private var _cmdPrefx:TextField; private var _cmdField:TextField; private var _hintField:TextField; private var _cmdBG:Shape; private var _bottomLine:Shape; private var _mini:Boolean; private var _shift:Boolean; private var _ctrl:Boolean; private var _alt:Boolean; private var _scroll:Sprite; private var _scroller:Sprite; private var _scrolldelay:uint; private var _scrolldir:int; private var _scrolling:Boolean; private var _scrollHeight:Number; private var _selectionStart:int; private var _selectionEnd:int; private var _viewingChannels:Array; private var _ignoredChannels:Array; private var _extraMenus:Object; private var _cmdsInd:int = -1; private var _priority:uint; private var _filterText:String; private var _filterRegExp:RegExp; private var _clScope:String = """"; private var _needUpdateMenu:Boolean; private var _needUpdateTrace:Boolean; private var _lockScrollUpdate:Boolean; private var _atBottom:Boolean = true; private var _enteringLogin:Boolean; private var _hint:String; private var _cmdsHistory:Array; public function addMenu(param1:String, param2:Function, param3:Array, param4:String) : void { if(param1) { param1 = param1.replace(new RegExp(""[^\\\\w]*"",""g""),""""); if(param2 == null) { delete this._extraMenus[param1]; true; } else { this._extraMenus[param1] = new Array(param2,param3,param4); } this._needUpdateMenu = true; } else { console.report(""ERROR: Invalid add menu params."",9); } } private function stageAddedHandle(param1:Event = null) : void { stage.addEventListener(MouseEvent.MOUSE_DOWN,this.onStageMouseDown,true,0,true); stage.addEventListener(KeyboardEvent.KEY_UP,this.keyUpHandler,false,0,true); stage.addEventListener(KeyboardEvent.KEY_DOWN,this.keyDownHandler,false,0,true); } private function stageRemovedHandle(param1:Event = null) : void { stage.removeEventListener(MouseEvent.MOUSE_DOWN,this.onStageMouseDown,true); stage.removeEventListener(KeyboardEvent.KEY_UP,this.keyUpHandler); stage.removeEventListener(KeyboardEvent.KEY_DOWN,this.keyDownHandler); } private function onStageMouseDown(param1:MouseEvent) : void { this._shift = param1.shiftKey; this._ctrl = param1.ctrlKey; this._alt = param1.altKey; } private function onMouseWheel(param1:MouseEvent) : void { var _loc2_:* = 0; if(this._shift) { _loc2_ = console.config.style.traceFontSize + (param1.delta > 0?1:-1); if(_loc2_ > 10 && _loc2_ < 20) { console.config.style.traceFontSize = _loc2_; console.config.style.updateStyleSheet(); this.updateToBottom(); param1.stopPropagation(); } } } private function onCmdPrefRollOverOut(param1:MouseEvent) : void { console.panels.tooltip(param1.type == MouseEvent.MOUSE_MOVE?""Current scope::(CommandLine)"":"""",this); } private function onCmdPrefMouseDown(param1:MouseEvent) : void { var e:MouseEvent = param1; try { stage.focus = this._cmdField; this.setCLSelectionAtEnd(); } catch(err:Error) { } } private function keyDownHandler(param1:KeyboardEvent) : void { if(param1.keyCode == Keyboard.SHIFT) { this._shift = true; } if(param1.keyCode == Keyboard.CONTROL) { this._ctrl = true; } if(param1.keyCode == 18) { this._alt = true; } } private function keyUpHandler(param1:KeyboardEvent) : void { var e:KeyboardEvent = param1; if(e.keyCode == Keyboard.SHIFT) { this._shift = false; } else if(e.keyCode == Keyboard.CONTROL) { this._ctrl = false; } else if(e.keyCode == 18) { this._alt = false; } if((e.keyCode == Keyboard.TAB || e.keyCode == Keyboard.ENTER) && (parent.visible) && (visible) && (this._cmdField.visible)) { try { stage.focus = this._cmdField; this.setCLSelectionAtEnd(); } catch(err:Error) { } } } public function requestLogin(param1:Boolean = true) : void { var _loc2_:ColorTransform = new ColorTransform(); if(param1) { console.commandLine = true; console.report(""//"",-2); console.report(""// Enter remoting password in CommandLine below..."",-2); this.updateCLScope(""Password""); _loc2_.color = style.controlColor; this._cmdBG.transform.colorTransform = _loc2_; this._traceField.transform.colorTransform = new ColorTransform(0.7,0.7,0.7); } else { this.updateCLScope(""""); this._cmdBG.transform.colorTransform = _loc2_; this._traceField.transform.colorTransform = _loc2_; } this._cmdField.displayAsPassword = param1; this._enteringLogin = param1; } public function update(param1:Boolean) : void { if(this._bottomLine.alpha > 0) { this._bottomLine.alpha = this._bottomLine.alpha - 0.25; } if(style.showCommandLineScope) { if(this._clScope != console.cl.scopeString) { this._clScope = console.cl.scopeString; this.updateCLScope(this._clScope); } } else if(this._clScope != null) { this._clScope = """"; this.updateCLScope(""""); } if(param1) { this._bottomLine.alpha = 1; this._needUpdateMenu = true; this._needUpdateTrace = true; } if(this._needUpdateTrace) { this._needUpdateTrace = false; this._updateTraces(true); } if(this._needUpdateMenu) { this._needUpdateMenu = false; this._updateMenu(); } } public function updateToBottom() : void { this._atBottom = true; this._needUpdateTrace = true; } private function _updateTraces(param1:Boolean = false) : void { if(this._atBottom) { this.updateBottom(); } else if(!param1) { this.updateFull(); } if(this._selectionStart != this._selectionEnd) { if(this._atBottom) { this._traceField.setSelection(this._traceField.text.length - this._selectionStart,this._traceField.text.length - this._selectionEnd); } else { this._traceField.setSelection(this._traceField.text.length - this._selectionEnd,this._traceField.text.length - this._selectionStart); } this._selectionEnd = -1; this._selectionStart = -1; } } private function updateFull() : void { var _loc1_:* = """"; var _loc2_:Log = console.logs.first; var _loc3_:* = !(this._viewingChannels.length == 1); var _loc4_:Boolean = this._priority == 0 && this._viewingChannels.length == 0; while(_loc2_) { if((_loc4_) || (this.lineShouldShow(_loc2_))) { _loc1_ = _loc1_ + this.makeLine(_loc2_,_loc3_); } _loc2_ = _loc2_.next; } this._lockScrollUpdate = true; this._traceField.htmlText = """" + _loc1_ + """"; this._lockScrollUpdate = false; this.updateScroller(); } public function setPaused(param1:Boolean) : void { if((param1) && (this._atBottom)) { this._atBottom = false; this._updateTraces(); this._traceField.scrollV = this._traceField.maxScrollV; } else if(!param1) { this._atBottom = true; this.updateBottom(); } this.updateMenu(); } private function updateBottom() : void { var _loc6_:* = 0; var _loc1_:* = """"; var _loc2_:int = Math.round(this._traceField.height / style.traceFontSize); var _loc3_:int = Math.round(this._traceField.width * 5 / style.traceFontSize); var _loc4_:Log = console.logs.last; var _loc5_:* = !(this._viewingChannels.length == 1); while(_loc4_) { if(this.lineShouldShow(_loc4_)) { _loc6_ = Math.ceil(_loc4_.text.length / _loc3_); if((_loc4_.html) || _loc2_ >= _loc6_) { _loc1_ = this.makeLine(_loc4_,_loc5_) + _loc1_; _loc2_ = _loc2_ - _loc6_; if(_loc2_ <= 0) { break; } } else { _loc4_ = _loc4_.clone(); _loc4_.text = _loc4_.text.substring(Math.max(0,_loc4_.text.length - _loc3_ * _loc2_)); _loc1_ = this.makeLine(_loc4_,_loc5_) + _loc1_; break; } } _loc4_ = _loc4_.prev; } this._lockScrollUpdate = true; this._traceField.htmlText = """" + _loc1_ + """"; this._traceField.scrollV = this._traceField.maxScrollV; this._lockScrollUpdate = false; this.updateScroller(); } private function lineShouldShow(param1:Log) : Boolean { return (this._priority == 0 || param1.priority >= this._priority) && ((this.chShouldShow(param1.ch)) || (this._filterText && this._viewingChannels.indexOf(Console.FILTER_CHANNEL) >= 0 && param1.text.toLowerCase().indexOf(this._filterText) >= 0) || (this._filterRegExp && this._viewingChannels.indexOf(Console.FILTER_CHANNEL) >= 0) && param1.text.search(this._filterRegExp) >= 0); } private function chShouldShow(param1:String) : Boolean { return (this._viewingChannels.length == 0 || this._viewingChannels.indexOf(param1) >= 0) && (this._ignoredChannels.length == 0 || this._ignoredChannels.indexOf(param1) < 0); } public function get reportChannel() : String { return this._viewingChannels.length == 1?this._viewingChannels[0]:Console.CONSOLE_CHANNEL; } public function setViewingChannels(... rest) : void { var _loc3_:Object = null; var _loc4_:String = null; var _loc2_:Array = new Array(); for each(_loc3_ in rest) { _loc2_.push(Console.MakeChannelName(_loc3_)); } if(this._viewingChannels[0] == LogReferences.INSPECTING_CHANNEL && (!_loc2_ || !(_loc2_[0] == this._viewingChannels[0]))) { console.refs.exitFocus(); } this._ignoredChannels.splice(0); this._viewingChannels.splice(0); if(_loc2_.indexOf(Console.GLOBAL_CHANNEL) < 0 && _loc2_.indexOf(null) < 0) { for each(_loc4_ in _loc2_) { if(_loc4_) { this._viewingChannels.push(_loc4_); } } } this.updateToBottom(); console.panels.updateMenu(); } public function get viewingChannels() : Array { return this._viewingChannels; } public function setIgnoredChannels(... rest) : void { var _loc3_:Object = null; var _loc4_:String = null; var _loc2_:Array = new Array(); for each(_loc3_ in rest) { _loc2_.push(Console.MakeChannelName(_loc3_)); } if(this._viewingChannels[0] == LogReferences.INSPECTING_CHANNEL) { console.refs.exitFocus(); } this._ignoredChannels.splice(0); this._viewingChannels.splice(0); if(_loc2_.indexOf(Console.GLOBAL_CHANNEL) < 0 && _loc2_.indexOf(null) < 0) { for each(_loc4_ in _loc2_) { if(_loc4_) { this._ignoredChannels.push(_loc4_); } } } this.updateToBottom(); console.panels.updateMenu(); } public function get ignoredChannels() : Array { return this._ignoredChannels; } private function setFilterText(param1:String = """") : void { if(param1) { this._filterRegExp = null; this._filterText = LogReferences.EscHTML(param1.toLowerCase()); this.startFilter(); } else { this.endFilter(); } } private function setFilterRegExp(param1:String = """") : void { if(param1) { this._filterText = null; this._filterRegExp = new RegExp(LogReferences.EscHTML(param1),""gi""); this.startFilter(); } else { this.endFilter(); } } private function startFilter() : void { console.clear(Console.FILTER_CHANNEL); console.logs.addChannel(Console.FILTER_CHANNEL); this.setViewingChannels(Console.FILTER_CHANNEL); } private function endFilter() : void { this._filterRegExp = null; this._filterText = null; if(this._viewingChannels.length == 1 && this._viewingChannels[0] == Console.FILTER_CHANNEL) { this.setViewingChannels(Console.GLOBAL_CHANNEL); } } private function makeLine(param1:Log, param2:Boolean) : String { var _loc3_:* = ""

""; if(param2) { _loc3_ = _loc3_ + param1.chStr; } if(config.showLineNumber) { _loc3_ = _loc3_ + param1.lineStr; } if(config.showTimestamp) { _loc3_ = _loc3_ + param1.timeStr; } var _loc4_:String = ""p"" + param1.priority; return _loc3_ + ""<"" + _loc4_ + "">"" + this.addFilterText(param1.text) + ""

""; } private function addFilterText(param1:String) : String { var _loc2_:Object = null; var _loc3_:* = 0; var _loc4_:String = null; var _loc5_:String = null; var _loc6_:* = 0; if(this._filterRegExp) { this._filterRegExp.lastIndex = 0; _loc2_ = this._filterRegExp.exec(param1); while(_loc2_ != null) { _loc3_ = _loc2_.index; _loc4_ = _loc2_[0]; if(_loc4_.search(""<|>"") >= 0) { this._filterRegExp.lastIndex = this._filterRegExp.lastIndex - (_loc4_.length - _loc4_.search(""<|>"")); } else if(param1.lastIndexOf(""<"",_loc3_) <= param1.lastIndexOf("">"",_loc3_)) { param1 = param1.substring(0,_loc3_) + """" + param1.substring(_loc3_,_loc3_ + _loc4_.length) + """" + param1.substring(_loc3_ + _loc4_.length); this._filterRegExp.lastIndex = this._filterRegExp.lastIndex + 7; } _loc2_ = this._filterRegExp.exec(param1); } } else if(this._filterText) { _loc5_ = param1.toLowerCase(); _loc6_ = _loc5_.lastIndexOf(this._filterText); while(_loc6_ >= 0) { param1 = param1.substring(0,_loc6_) + """" + param1.substring(_loc6_,_loc6_ + this._filterText.length) + """" + param1.substring(_loc6_ + this._filterText.length); _loc6_ = _loc5_.lastIndexOf(this._filterText,_loc6_ - 2); } } return param1; } private function onTraceScroll(param1:Event = null) : void { var _loc3_:* = 0; if((this._lockScrollUpdate) || (this._shift)) { return; } var _loc2_:* = this._traceField.scrollV >= this._traceField.maxScrollV; if(!console.paused && !(this._atBottom == _loc2_)) { _loc3_ = this._traceField.maxScrollV - this._traceField.scrollV; this._selectionStart = this._traceField.text.length - this._traceField.selectionBeginIndex; this._selectionEnd = this._traceField.text.length - this._traceField.selectionEndIndex; this._atBottom = _loc2_; this._updateTraces(); this._traceField.scrollV = this._traceField.maxScrollV - _loc3_; } this.updateScroller(); } private function updateScroller() : void { if(this._traceField.maxScrollV <= 1) { this._scroll.visible = false; } else { this._scroll.visible = true; if(this._atBottom) { this.scrollPercent = 1; } else { this.scrollPercent = (this._traceField.scrollV - 1) / (this._traceField.maxScrollV - 1); } } } private function onScrollbarDown(param1:MouseEvent) : void { if((this._scroller.visible) && this._scroller.mouseY > 0 || !this._scroller.visible && this._scroll.mouseY > this._scrollHeight / 2) { this._scrolldir = 3; } else { this._scrolldir = -3; } this._traceField.scrollV = this._traceField.scrollV + this._scrolldir; this._scrolldelay = 0; addEventListener(Event.ENTER_FRAME,this.onScrollBarFrame,false,0,true); stage.addEventListener(MouseEvent.MOUSE_UP,this.onScrollBarUp,false,0,true); } private function onScrollBarFrame(param1:Event) : void { this._scrolldelay++; if(this._scrolldelay > 10) { this._scrolldelay = 9; if(this._scrolldir < 0 && this._scroller.y > this._scroll.mouseY || this._scrolldir > 0 && this._scroller.y + this._scroller.height < this._scroll.mouseY) { this._traceField.scrollV = this._traceField.scrollV + this._scrolldir; } } } private function onScrollBarUp(param1:Event) : void { removeEventListener(Event.ENTER_FRAME,this.onScrollBarFrame); stage.removeEventListener(MouseEvent.MOUSE_UP,this.onScrollBarUp); } private function get scrollPercent() : Number { return (this._scroller.y - style.controlSize) / (this._scrollHeight - 30 - style.controlSize * 2); } private function set scrollPercent(param1:Number) : void { this._scroller.y = style.controlSize + (this._scrollHeight - 30 - style.controlSize * 2) * param1; } private function onScrollerDown(param1:MouseEvent) : void { var _loc2_:* = NaN; this._scrolling = true; if(!console.paused && (this._atBottom)) { this._atBottom = false; _loc2_ = this.scrollPercent; this._updateTraces(); this.scrollPercent = _loc2_; } this._scroller.startDrag(false,new Rectangle(0,style.controlSize,0,this._scrollHeight - 30 - style.controlSize * 2)); stage.addEventListener(MouseEvent.MOUSE_MOVE,this.onScrollerMove,false,0,true); stage.addEventListener(MouseEvent.MOUSE_UP,this.onScrollerUp,false,0,true); param1.stopPropagation(); } private function onScrollerMove(param1:MouseEvent) : void { this._lockScrollUpdate = true; this._traceField.scrollV = Math.round(this.scrollPercent * (this._traceField.maxScrollV - 1) + 1); this._lockScrollUpdate = false; } private function onScrollerUp(param1:MouseEvent) : void { this._scroller.stopDrag(); stage.removeEventListener(MouseEvent.MOUSE_MOVE,this.onScrollerMove); stage.removeEventListener(MouseEvent.MOUSE_UP,this.onScrollerUp); this._scrolling = false; this.onTraceScroll(); } override public function set width(param1:Number) : void { this._lockScrollUpdate = true; super.width = param1; this._traceField.width = param1 - 4; txtField.width = param1 - 6; this._cmdField.width = width - 15 - this._cmdField.x; this._cmdBG.width = param1; this._bottomLine.graphics.clear(); this._bottomLine.graphics.lineStyle(1,style.controlColor); this._bottomLine.graphics.moveTo(10,-1); this._bottomLine.graphics.lineTo(param1 - 10,-1); this._scroll.x = param1; this._atBottom = true; this.updateCLSize(); this._needUpdateMenu = true; this._needUpdateTrace = true; this._lockScrollUpdate = false; } override public function set height(param1:Number) : void { this._lockScrollUpdate = true; var _loc2_:int = style.menuFontSize; var _loc3_:Number = _loc2_ + 6 + style.traceFontSize; if(height != param1) { this._mini = param1 < (this._cmdField.visible?_loc3_ + _loc2_ + 4:_loc3_); } super.height = param1; var _loc4_:Boolean = (this._mini) || !style.topMenu; this.updateTraceFHeight(); this._traceField.y = _loc4_?0:_loc2_; this._traceField.height = param1 - (this._cmdField.visible?_loc2_ + 4:0) - (_loc4_?0:_loc2_); var _loc5_:Number = param1 - (_loc2_ + 6); this._cmdField.y = _loc5_; this._cmdPrefx.y = _loc5_; this._hintField.y = this._cmdField.y - this._hintField.height; this._cmdBG.y = _loc5_; this._bottomLine.y = this._cmdField.visible?_loc5_:param1; this._scroll.y = _loc4_?6:_loc2_ + 4; var _loc6_:uint = style.controlSize; this._scrollHeight = this._bottomLine.y - (this._cmdField.visible?0:_loc6_ * 2) - this._scroll.y; this._scroller.visible = this._scrollHeight > 40; this._scroll.graphics.clear(); if(this._scrollHeight >= 10) { this._scroll.graphics.beginFill(style.controlColor,0.7); this._scroll.graphics.drawRect(-_loc6_,0,_loc6_,_loc6_); this._scroll.graphics.drawRect(-_loc6_,this._scrollHeight - _loc6_,_loc6_,_loc6_); this._scroll.graphics.beginFill(style.controlColor,0.25); this._scroll.graphics.drawRect(-_loc6_,_loc6_,_loc6_,this._scrollHeight - _loc6_ * 2); this._scroll.graphics.beginFill(0,0); this._scroll.graphics.drawRect(-_loc6_ * 2,_loc6_ * 2,_loc6_ * 2,this._scrollHeight - _loc6_ * 2); this._scroll.graphics.endFill(); } this._atBottom = true; this._needUpdateTrace = true; this._lockScrollUpdate = false; } private function updateTraceFHeight() : void { var _loc1_:Boolean = (this._mini) || !style.topMenu; this._traceField.y = _loc1_?0:txtField.y + txtField.height - 6; this._traceField.height = Math.max(0,height - (this._cmdField.visible?style.menuFontSize + 4:0) - this._traceField.y); } public function updateMenu(param1:Boolean = false) : void { if(param1) { this._updateMenu(); } else { this._needUpdateMenu = true; } } private function _updateMenu() : void { var _loc2_:* = false; var _loc3_:String = null; var _loc1_:* = """"; if((this._mini) || !style.topMenu) { _loc1_ = _loc1_ + "" ‹""; } else { if(!console.panels.channelsPanel) { _loc1_ = _loc1_ + this.getChannelsLink(true); } _loc1_ = _loc1_ + "" ""; for(_loc3_ in this._extraMenus) { _loc1_ = _loc1_ + ("""" + _loc3_ + "" ""); _loc2_ = true; } if(_loc2_) { _loc1_ = _loc1_ + ""¦ ""; } _loc1_ = _loc1_ + this.doActive(""F"",console.fpsMonitor > 0); _loc1_ = _loc1_ + this.doActive("" M"",console.memoryMonitor > 0); _loc1_ = _loc1_ + this.doActive("" CL"",this.commandLine); if(console.remoter.remoting != Remoting.RECIEVER) { if(config.displayRollerEnabled) { _loc1_ = _loc1_ + this.doActive("" Ro"",console.displayRoller); } if(config.rulerToolEnabled) { _loc1_ = _loc1_ + this.doActive("" RL"",console.panels.rulerActive); } } _loc1_ = _loc1_ + "" ¦""; _loc1_ = _loc1_ + "" Sv""; _loc1_ = _loc1_ + ("" P"" + this._priority + """"); _loc1_ = _loc1_ + this.doActive("" P"",console.paused); _loc1_ = _loc1_ + "" C X ›""; } _loc1_ = _loc1_ + "" ""; txtField.htmlText = _loc1_; txtField.scrollH = txtField.maxScrollH; this.updateTraceFHeight(); } public function getChannelsLink(param1:Boolean = false) : String { var _loc7_:String = null; var _loc8_:String = null; var _loc2_:* = """"; var _loc3_:Array = console.logs.getChannels(); var _loc4_:int = _loc3_.length; if((param1) && _loc4_ > style.maxChannelsInMenu) { _loc4_ = style.maxChannelsInMenu; } var _loc5_:Boolean = this._viewingChannels.length > 0 || this._ignoredChannels.length > 0; var _loc6_:* = 0; while(_loc6_ < _loc4_) { _loc7_ = _loc3_[_loc6_]; _loc8_ = !_loc5_ && _loc6_ == 0 || (_loc5_) && !(_loc6_ == 0) && (this.chShouldShow(_loc7_))?"""" + _loc7_ + """":_loc7_; _loc2_ = _loc2_ + (""["" + _loc8_ + ""] ""); _loc6_++; } if(param1) { _loc2_ = _loc2_ + ("""" + (_loc3_.length > _loc4_?""..."":"""") + ""^^ ""); } _loc2_ = _loc2_ + "" ""; return _loc2_; } private function doActive(param1:String, param2:Boolean) : String { if(param2) { return """" + param1 + """"; } return param1; } public function onMenuRollOver(param1:TextEvent, param2:ConsolePanel = null) : void { var _loc4_:Array = null; var _loc5_:Object = null; if(param2 == null) { param2 = this; } var _loc3_:String = param1.text?param1.text.replace(""event:"",""""):""""; if(_loc3_ == ""channel_"" + Console.GLOBAL_CHANNEL) { _loc3_ = ""View all channels""; } else if(_loc3_ == ""channel_"" + Console.DEFAULT_CHANNEL) { _loc3_ = ""Default channel::Logs with no channel""; } else if(_loc3_ == ""channel_"" + Console.CONSOLE_CHANNEL) { _loc3_ = ""Console\\'s channel::Logs generated from Console""; } else if(_loc3_ == ""channel_"" + Console.FILTER_CHANNEL) { _loc3_ = this._filterRegExp?String(this._filterRegExp):this._filterText; _loc3_ = ""Filtering channel"" + ""::*"" + _loc3_ + ""*""; } else if(_loc3_ == ""channel_"" + LogReferences.INSPECTING_CHANNEL) { _loc3_ = ""Inspecting channel""; } else if(_loc3_.indexOf(""channel_"") == 0) { _loc3_ = ""Change channel::shift: select multiple\\nctrl: ignore channel""; } else if(_loc3_ == ""pause"") { if(console.paused) { _loc3_ = ""Resume updates""; } else { _loc3_ = ""Pause updates""; } } else if(_loc3_ == ""close"" && param2 == this) { _loc3_ = ""Close::Type password to show again""; } else if(_loc3_.indexOf(""external_"") == 0) { _loc4_ = this._extraMenus[_loc3_.substring(9)]; if(_loc4_) { _loc3_ = _loc4_[2]; } } else { _loc5_ = { ""fps"":""Frames Per Second"", ""mm"":""Memory Monitor"", ""roller"":""Display Roller::Map the display list under your mouse"", ""ruler"":""Screen Ruler::Measure the distance and angle between two points on screen."", ""command"":""Command Line"", ""copy"":""Save to clipboard::shift: no channel name\\nctrl: use viewing filters\\nalt: save to file"", ""clear"":""Clear log"", ""priority"":""Priority filter::shift: previous priority\\n(skips unused priorites)"", ""channels"":""Expand channels"", ""close"":""Close"" }; _loc3_ = _loc5_[_loc3_]; } console.panels.tooltip(_loc3_,param2); } private function linkHandler(param1:TextEvent) : void { var str:String = null; var file:FileReference = null; var ind:int = 0; var menu:Array = null; var e:TextEvent = param1; txtField.setSelection(0,0); stopDrag(); var t:String = e.text; if(t == ""pause"") { if(console.paused) { console.paused = false; } else { console.paused = true; } console.panels.tooltip(null); } else if(t == ""hide"") { console.panels.tooltip(); this._mini = true; console.config.style.topMenu = false; this.height = height; this.updateMenu(); } else if(t == ""show"") { console.panels.tooltip(); this._mini = false; console.config.style.topMenu = true; this.height = height; this.updateMenu(); } else if(t == ""close"") { console.panels.tooltip(); visible = false; dispatchEvent(new Event(Event.CLOSE)); } else if(t == ""channels"") { console.panels.channelsPanel = !console.panels.channelsPanel; } else if(t == ""fps"") { console.fpsMonitor = !console.fpsMonitor; } else if(t == ""priority"") { this.incPriority(this._shift); } else if(t == ""mm"") { console.memoryMonitor = !console.memoryMonitor; } else if(t == ""roller"") { console.displayRoller = !console.displayRoller; } else if(t == ""ruler"") { console.panels.tooltip(); console.panels.startRuler(); } else if(t == ""command"") { this.commandLine = !this.commandLine; } else if(t == ""copy"") { str = console.logs.getLogsAsString(""\\r\\n"",!this._shift,this._ctrl?this.lineShouldShow:null); if(this._alt) { file = new FileReference(); try { file[""save""](str,""log.txt""); } catch(err:Error) { console.report(""Save to file is not supported in your flash player."",8); } } else { System.setClipboard(str); console.report(""Copied log to clipboard."",-1); } } else if(t == ""clear"") { console.clear(); } else if(t == ""settings"") { console.report(""A new window should open in browser. If not, try searching for \\'Flash Player Global Security Settings panel\\' online :)"",-1); Security.showSettings(SecurityPanel.SETTINGS_MANAGER); } else if(t == ""remote"") { console.remoter.remoting = Remoting.RECIEVER; } else if(t.indexOf(""ref"") == 0) { console.refs.handleRefEvent(t); } else if(t.indexOf(""channel_"") == 0) { this.onChannelPressed(t.substring(8)); } else if(t.indexOf(""cl_"") == 0) { ind = t.indexOf(""_"",3); console.cl.handleScopeEvent(uint(t.substring(3,ind < 0?t.length:ind))); if(ind >= 0) { this._cmdField.text = t.substring(ind + 1); } } else if(t.indexOf(""external_"") == 0) { menu = this._extraMenus[t.substring(9)]; if(menu) { menu[0].apply(null,menu[1]); } } txtField.setSelection(0,0); e.stopPropagation(); } public function onChannelPressed(param1:String) : void { var _loc2_:Array = null; if((this._ctrl) && !(param1 == Console.GLOBAL_CHANNEL)) { _loc2_ = this.toggleCHList(this._ignoredChannels,param1); this.setIgnoredChannels.apply(this,_loc2_); } else if((this._shift) && !(param1 == Console.GLOBAL_CHANNEL) && !(this._viewingChannels[0] == LogReferences.INSPECTING_CHANNEL)) { _loc2_ = this.toggleCHList(this._viewingChannels,param1); this.setViewingChannels.apply(this,_loc2_); } else { console.setViewingChannels(param1); } } private function toggleCHList(param1:Array, param2:String) : Array { var param1:Array = param1.concat(); var _loc3_:int = param1.indexOf(param2); if(_loc3_ >= 0) { param1.splice(_loc3_,1); if(param1.length == 0) { param1.push(Console.GLOBAL_CHANNEL); } } else { param1.push(param2); } return param1; } public function set priority(param1:uint) : void { this._priority = param1; console.so[PRIORITY_HISTORY] = this._priority; this.updateToBottom(); this.updateMenu(); } public function get priority() : uint { return this._priority; } private function incPriority(param1:Boolean) : void { var _loc3_:uint = 0; var _loc2_:uint = 10; var _loc4_:Log = console.logs.last; var _loc5_:int = this._priority; this._priority = 0; var _loc6_:uint = 32000; while((_loc4_) && _loc6_ > 0) { _loc6_--; if(this.lineShouldShow(_loc4_)) { if(_loc4_.priority > _loc5_ && _loc2_ > _loc4_.priority) { _loc2_ = _loc4_.priority; } if(_loc4_.priority < _loc5_ && _loc3_ < _loc4_.priority) { _loc3_ = _loc4_.priority; } } _loc4_ = _loc4_.prev; } if(param1) { if(_loc3_ == _loc5_) { _loc5_ = 10; } else { _loc5_ = _loc3_; } } else if(_loc2_ == _loc5_) { _loc5_ = 0; } else { _loc5_ = _loc2_; } this.priority = _loc5_; } private function clearCommandLineHistory(... rest) : void { this._cmdsInd = -1; console.updateSO(); this._cmdsHistory = new Array(); } private function commandKeyDown(param1:KeyboardEvent) : void { if(param1.keyCode == Keyboard.TAB) { if(this._hint) { this._cmdField.text = this._hint; this.setCLSelectionAtEnd(); this.setHints(); } } } private function commandKeyUp(param1:KeyboardEvent) : void { var _loc2_:String = null; var _loc3_:* = 0; if(param1.keyCode == Keyboard.ENTER) { this.updateToBottom(); this.setHints(); if(this._enteringLogin) { console.remoter.login(this._cmdField.text); this._cmdField.text = """"; this.requestLogin(false); } else { _loc2_ = this._cmdField.text; if(_loc2_.length > 2) { _loc3_ = this._cmdsHistory.indexOf(_loc2_); while(_loc3_ >= 0) { this._cmdsHistory.splice(_loc3_,1); _loc3_ = this._cmdsHistory.indexOf(_loc2_); } this._cmdsHistory.unshift(_loc2_); this._cmdsInd = -1; if(this._cmdsHistory.length > 20) { this._cmdsHistory.splice(20); } console.updateSO(CL_HISTORY); } this._cmdField.text = """"; if(config.commandLineInputPassThrough != null) { _loc2_ = config.commandLineInputPassThrough(_loc2_); } if(_loc2_) { console.cl.run(_loc2_); } } } else if(param1.keyCode == Keyboard.ESCAPE) { if(stage) { stage.focus = null; } } else if(param1.keyCode == Keyboard.UP) { this.setHints(); if((this._cmdField.text) && this._cmdsInd < 0) { this._cmdsHistory.unshift(this._cmdField.text); this._cmdsInd++; } if(this._cmdsInd < this._cmdsHistory.length - 1) { this._cmdsInd++; this._cmdField.text = this._cmdsHistory[this._cmdsInd]; this.setCLSelectionAtEnd(); } else { this._cmdsInd = this._cmdsHistory.length; this._cmdField.text = """"; } } else if(param1.keyCode == Keyboard.DOWN) { this.setHints(); if(this._cmdsInd > 0) { this._cmdsInd--; this._cmdField.text = this._cmdsHistory[this._cmdsInd]; this.setCLSelectionAtEnd(); } else { this._cmdsInd = -1; this._cmdField.text = """"; } } else if(param1.keyCode == Keyboard.TAB) { this.setCLSelectionAtEnd(); } else if(!this._enteringLogin) { this.updateCmdHint(); } } private function setCLSelectionAtEnd() : void { this._cmdField.setSelection(this._cmdField.text.length,this._cmdField.text.length); } private function updateCmdHint(param1:Event = null) : void { var e:Event = param1; var str:String = this._cmdField.text; if((str) && (config.commandLineAutoCompleteEnabled) && !(console.remoter.remoting == Remoting.RECIEVER)) { try { this.setHints(console.cl.getHintsFor(str,5)); return; } catch(err:Error) { } } this.setHints(); } private function onCmdFocusOut(param1:Event) : void { this.setHints(); } private function setHints(param1:Array = null) : void { var _loc2_:Array = null; var _loc3_:Array = null; var _loc4_:Rectangle = null; var _loc5_:String = null; var _loc6_:* = false; var _loc7_:* = 0; if((param1) && (param1.length)) { this._hint = param1[0][0]; if(param1.length > 1) { _loc5_ = param1[1][0]; _loc6_ = false; _loc7_ = 0; while(_loc7_ < _loc5_.length) { if(_loc5_.charAt(_loc7_) == this._hint.charAt(_loc7_)) { _loc6_ = true; _loc7_++; continue; } if((_loc6_) && this._cmdField.text.length < _loc7_) { this._hint = this._hint.substring(0,_loc7_); } break; } } _loc2_ = new Array(); for each(_loc3_ in param1) { _loc2_.push("""" + _loc3_[0] + "" "" + (_loc3_[1]?_loc3_[1]:"""") + """"); } this._hintField.htmlText = ""

"" + _loc2_.reverse().join(""\\n"") + ""

""; this._hintField.visible = true; _loc4_ = this._cmdField.getCharBoundaries(this._cmdField.text.length - 1); if(!_loc4_) { _loc4_ = new Rectangle(); } this._hintField.x = this._cmdField.x + _loc4_.x + _loc4_.width + 30; this._hintField.y = height - this._hintField.height; } else { this._hintField.visible = false; this._hint = null; } } public function updateCLScope(param1:String) : void { if(this._enteringLogin) { this._enteringLogin = false; this.requestLogin(false); } this._cmdPrefx.autoSize = TextFieldAutoSize.LEFT; this._cmdPrefx.text = param1; this.updateCLSize(); } private function updateCLSize() : void { var _loc1_:Number = width - 48; if(this._cmdPrefx.width > 120 || this._cmdPrefx.width > _loc1_) { this._cmdPrefx.autoSize = TextFieldAutoSize.NONE; this._cmdPrefx.width = _loc1_ > 120?120:_loc1_; this._cmdPrefx.scrollH = this._cmdPrefx.maxScrollH; } this._cmdField.x = this._cmdPrefx.width + 2; this._cmdField.width = width - 15 - this._cmdField.x; this._hintField.x = this._cmdField.x; } public function set commandLine(param1:Boolean) : void { if(param1) { this._cmdField.visible = true; this._cmdPrefx.visible = true; this._cmdBG.visible = true; } else { this._cmdField.visible = false; this._cmdPrefx.visible = false; this._cmdBG.visible = false; } this._needUpdateMenu = true; this.height = height; } public function get commandLine() : Boolean { return this._cmdField.visible; } } } ",12409,True,2573.783467675159,median "/* Open Sound Control for Audio Library for Teensy 3.x, 4.x * Copyright (c) 2021, Jonathan Oakley, teensy-osc@0akley.co.uk * * Development of this library was enabled by PJRC.COM, LLC by sales of * Teensy and Audio Adaptor boards, implementing libraries, and maintaining * the forum at https://forum.pjrc.com/ * * Please support PJRC's efforts to develop open source software by * purchasing Teensy or other PJRC products. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice, development funding notice, and this permission * notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ // Demo code fragment to illustrate using OSC messages in conjunction with MIDI #include #include #include ""OSCAudioUseMIDI.h"" #define USE_GROUPS /* * JSON to use in GUI++ for test purposes * {""version"":1,""settings"":{""arduino"":{""ProjectName"":""SimpleMIDIpoly"",""Board"":{""Platform"":"""",""Board"":"""",""Options"":""""}},""BiDirDataWebSocketBridge"":{},""workspaces"":{},""sidebar"":{""autoSwitchTabToInfoTab"":false},""palette"":{},""editor"":{},""devTest"":{},""IndexedDBfiles"":{""testFileNames"":""testFile.txt""},""NodeDefGenerator"":{},""NodeDefManager"":{},""NodeHelpManager"":{},""OSC"":{""UseDebugLinkName"":true}},""workspaces"":[{""type"":""tab"",""id"":""3629fcd9.ccc604"",""label"":""Main"",""inputs"":0,""outputs"":0,""export"":true,""isMain"":false,""mainNameType"":""tabName"",""mainNameExt"":"".ino"",""generateCppDestructor"":false,""extraClassDeclarations"":"""",""settings"":{""guiEditMode"":false,""workspaceBgColor"":""#EDFFDF"",""scaleFactor"":0.8,""showGridHminor"":false,""showGridHmajor"":false,""showGridVminor"":false,""showGridVmajor"":false,""useCenterBasedPositions"":false},""nodes"":[{""id"":""Main_waveform1"",""type"":""AudioSynthWaveform"",""name"":""wavA1"",""comment"":"""",""x"":60,""y"":95,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_2:0""]]},{""id"":""Main_waveform5"",""type"":""AudioSynthWaveform"",""name"":""wavA2"",""comment"":"""",""x"":60,""y"":140,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_2:1""]]},{""id"":""Main_waveform2"",""type"":""AudioSynthWaveform"",""name"":""wavB1"",""comment"":"""",""x"":60,""y"":200,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_3:0""]]},{""id"":""Main_waveform3"",""type"":""AudioSynthWaveform"",""name"":""wavB2"",""comment"":"""",""x"":60,""y"":245,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_3:1""]]},{""id"":""Main_waveform4"",""type"":""AudioSynthWaveform"",""name"":""wavC1"",""comment"":"""",""x"":65,""y"":305,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_4:0""]]},{""id"":""Main_waveform6"",""type"":""AudioSynthWaveform"",""name"":""wavC2"",""comment"":"""",""x"":65,""y"":350,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_4:1""]]},{""id"":""Main_waveform7"",""type"":""AudioSynthWaveform"",""name"":""wavD1"",""comment"":"""",""x"":65,""y"":410,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_5:0""]]},{""id"":""Main_waveform8"",""type"":""AudioSynthWaveform"",""name"":""wavD2"",""comment"":"""",""x"":65,""y"":455,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_5:1""]]},{""id"":""Main_mixer4_2"",""type"":""AudioMixer4"",""name"":""mixA"",""comment"":"""",""inputs"":""4"",""x"":260,""y"":115,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_envelope1:0""]]},{""id"":""Main_mixer4_3"",""type"":""AudioMixer4"",""name"":""mixB"",""comment"":"""",""inputs"":""4"",""x"":260,""y"":220,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_envelope2:0""]]},{""id"":""Main_mixer4_4"",""type"":""AudioMixer4"",""name"":""mixC"",""comment"":"""",""inputs"":""4"",""x"":265,""y"":325,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_envelope3:0""]]},{""id"":""Main_mixer4_5"",""type"":""AudioMixer4"",""name"":""mixD"",""comment"":"""",""inputs"":""4"",""x"":265,""y"":430,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_envelope4:0""]]},{""id"":""Main_envelope1"",""type"":""AudioEffectEnvelope"",""name"":""envA"",""comment"":"""",""x"":380,""y"":125,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_1:0""]]},{""id"":""Main_envelope2"",""type"":""AudioEffectEnvelope"",""name"":""envB"",""comment"":"""",""x"":380,""y"":230,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_1:1""]]},{""id"":""Main_envelope3"",""type"":""AudioEffectEnvelope"",""name"":""envC"",""comment"":"""",""x"":385,""y"":335,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_1:2""]]},{""id"":""Main_envelope4"",""type"":""AudioEffectEnvelope"",""name"":""envD"",""comment"":"""",""x"":385,""y"":440,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_mixer4_1:3""]]},{""id"":""Main_mixer4_1"",""type"":""AudioMixer4"",""name"":""mixer"",""comment"":"""",""inputs"":""4"",""x"":560,""y"":230,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[[""Main_pt8211_2_1:0"",""Main_pt8211_2_1:1"",""Main_i2s1:0"",""Main_i2s1:1""]]},{""id"":""Main_pt8211_2_1"",""type"":""AudioOutputPT8211_2"",""name"":""pt8211_2"",""comment"":"""",""x"":720,""y"":210,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[]},{""id"":""Main_i2s1"",""type"":""AudioOutputI2S"",""name"":""i2s"",""comment"":"""",""x"":740,""y"":270,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[]},{""id"":""Main_sgtl5000_1"",""type"":""AudioControlSGTL5000"",""name"":""sgtl5000"",""comment"":"""",""x"":1560,""y"":445,""z"":""3629fcd9.ccc604"",""bgColor"":""#E6E0F8"",""wires"":[]},{""id"":""Main_Button1"",""type"":""UI_Button"",""name"":""use connection to connect wafo to mixer1 input 1"",""comment"":"""",""w"":360,""h"":34,""textSize"":14,""midiCh"":""0"",""midiId"":""0"",""pressAction"":"""",""repeatPressAction"":false,""releaseAction"":"""",""repeatReleaseAction"":false,""local"":""true"",""sendCommand"":""var addr = \\""/teensy1/audio/wafo2mixer1/connect*\\""\\nvar data = OSC.GetSimpleOSCdata(addr,\\""sisi\\"", \\""wafo\\"", 0, \\""mixer1\\"", 1);\\nOSC.SendAsSlipToSerial(data);"",""x"":2200,""y"":170,""z"":""3629fcd9.ccc604"",""bgColor"":""#F6F8BC"",""wires"":[]},{""id"":""Main_Slider1"",""type"":""UI_Slider"",""name"":""ch1"",""tag"":""g 0"",""comment"":"""",""w"":32,""h"":281,""textSize"":16,""midiCh"":"""",""midiId"":""29"",""orientation"":""v"",""label"":""d.val/d.maxVal"",""minVal"":0,""maxVal"":100,""val"":10,""divVal"":1,""fval"":10,""sendMode"":""m"",""autoReturn"":false,""returnValue"":""mid"",""barFGcolor"":""#F87A00"",""sendFormat"":""\\""midisend(0xB0,\\""+d.midiId+\\"",\\"" + d.val + \\"");\\"""",""sendCommand"":""var tags = d.tag.split(' ');\\nvar addr = RED.OSC.settings.RootAddress + \\""/audio/\\""+d.parentGroup.name+\\""/\\""+tags[0]+\\""*\\"";\\nOSC.SendData(OSC.CreateMessageData(addr,\\""if\\"", tags[1], d.val/d.maxVal));"",""parentGroup"":""Main_group1"",""x"":1320,""y"":84.28572082519531,""z"":""3629fcd9.ccc604"",""bgColor"":""#808080"",""wires"":[]},{""id"":""Main_Slider2"",""type"":""UI_Slider"",""name"":""ch2"",""tag"":""g 1"",""comment"":"""",""w"":30,""h"":280,""textSize"":16,""midiCh"":"""",""midiId"":""29"",""orientation"":""v"",""label"":""d.val/d.maxVal"",""minVal"":0,""maxVal"":100,""val"":10,""divVal"":1,""fval"":10,""sendMode"":""m"",""autoReturn"":false,""returnValue"":""mid"",""barFGcolor"":""#F87A00"",""sendFormat"":""\\""midisend(0xB0,\\""+d.midiId+\\"",\\"" + d.val + \\"");\\"""",""sendCommand"":""var tags = d.tag.split(' ');\\nvar addr = RED.OSC.settings.RootAddress + \\""/audio/\\""+d.parentGroup.name+\\""/\\""+tags[0]+\\""*\\"";\\nOSC.SendData(OSC.CreateMessageData(addr,\\""if\\"", tags[1], d.val/d.maxVal));"",""parentGroup"":""Main_group1"",""x"":1370,""y"":85,""z"":""3629fcd9.ccc604"",""bgColor"":""#808080"",""wires"":[]},{""id"":""Main_Slider3"",""type"":""UI_Slider"",""name"":""ch3"",""tag"":""g 2"",""comment"":"""",""w"":30,""h"":280,""textSize"":16,""midiCh"":"""",""midiId"":""29"",""orientation"":""v"",""label"":""d.val/d.maxVal"",""minVal"":0,""maxVal"":100,""val"":0,""divVal"":1,""fval"":0,""sendMode"":""m"",""autoReturn"":false,""returnValue"":""mid"",""barFGcolor"":""#F87A00"",""sendFormat"":""\\""midisend(0xB0,\\""+d.midiId+\\"",\\"" + d.val + \\"");\\"""",""sendCommand"":""var tags = d.tag.split(' ');\\nvar addr = RED.OSC.settings.RootAddress + \\""/audio/\\""+d.parentGroup.name+\\""/\\""+tags[0]+\\""*\\"";\\nOSC.SendData(OSC.CreateMessageData(addr,\\""if\\"", tags[1], d.val/d.maxVal));"",""parentGroup"":""Main_group1"",""x"":1420,""y"":84.28572082519531,""z"":""3629fcd9.ccc604"",""bgColor"":""#808080"",""wires"":[]},{""id"":""Main_Slider4"",""type"":""UI_Slider"",""name"":""ch4"",""tag"":""g 3"",""comment"":"""",""w"":30,""h"":280,""textSize"":16,""midiCh"":"""",""midiId"":""29"",""orientation"":""v"",""label"":""d.val/d.maxVal"",""minVal"":0,""maxVal"":100,""val"":10,""divVal"":1,""fval"":10,""sendMode"":""m"",""autoReturn"":false,""returnValue"":""mid"",""barFGcolor"":""#F87A00"",""sendFormat"":""\\""midisend(0xB0,\\""+d.midiId+\\"",\\"" + d.val + \\"");\\"""",""sendCommand"":""var tags = d.tag.split(' ');\\nvar addr = RED.OSC.settings.RootAddress + \\""/audio/\\""+d.parentGroup.name+\\""/\\""+tags[0]+\\""*\\"";\\nOSC.SendData(OSC.CreateMessageData(addr,\\""if\\"", tags[1], d.val/d.maxVal));"",""parentGroup"":""Main_group1"",""x"":1470,""y"":84.28572082519531,""z"":""3629fcd9.ccc604"",""bgColor"":""#808080"",""wires"":[]},{""id"":""Main_Button2"",""type"":""UI_Button"",""name"":""create new AudioSynthWaveForm wafo"",""comment"":"""",""w"":275,""h"":34,""textSize"":14,""midiCh"":""0"",""midiId"":""0"",""pressAction"":"""",""repeatPressAction"":false,""releaseAction"":"""",""repeatReleaseAction"":false,""local"":""true"",""sendCommand"":""var addr = \\""/teensy1/dynamic/createObject*\\""\\nvar data = OSC.GetSimpleOSCdata(addr,\\""ss\\"", \\""AudioSynthWaveform\\"", \\""wafo\\"");\\nOSC.SendAsSlipToSerial(data);"",""x"":2260,""y"":90,""z"":""3629fcd9.ccc604"",""bgColor"":""#F6F8BC"",""wires"":[]},{""id"":""Main_Button3"",""type"":""UI_Button"",""name"":""create connection wafo2mixer1"",""comment"":"""",""w"":223,""h"":30,""textSize"":14,""midiCh"":""0"",""midiId"":""0"",""pressAction"":"""",""repeatPressAction"":false,""releaseAction"":"""",""repeatReleaseAction"":false,""local"":""true"",""sendCommand"":""var addr = \\""/teensy1/dynamic/createConn*\\""\\nvar data = OSC.GetSimpleOSCdata(addr,\\""s\\"", \\""wafo2mixer1\\"");\\nOSC.SendAsSlipToSerial(data);"",""x"":2260,""y"":130,""z"":""3629fcd9.ccc604"",""bgColor"":""#F6F8BC"",""wires"":[]},{""id"":""Main_Button4"",""type"":""UI_Button"",""name"":""do all above in one go"",""comment"":"""",""w"":157,""h"":34,""textSize"":14,""midiCh"":""0"",""midiId"":""0"",""pressAction"":"""",""repeatPressAction"":false,""releaseAction"":"""",""repeatReleaseAction"":false,""local"":""true"",""sendCommand"":""var data = osc.writeBundle({\\r\\n timeTag: osc.timeTag(0),\\r\\n packets: [\\r\\n {\\r\\n address: \\""/teensy1/dynamic/createObject*\\"",\\r\\n args: [\\r\\n\\t\\t\\t\\t\\t{type: \\""s\\"", value: \\""AudioSynthWaveform\\""},\\r\\n\\t\\t\\t\\t\\t{type: \\""s\\"", value: \\""wafo\\""}\\r\\n ]\\r\\n },\\r\\n {\\r\\n address: \\""/teensy1/dynamic/createConn*\\"",\\r\\n args: [\\r\\n {type: \\""s\\"", value: \\""wafo2mixer1\\""}\\r\\n ]\\r\\n },\\r\\n {\\r\\n address: \\""/teensy1/audio/wafo2mixer1/connect*\\"",\\r\\n args: [\\r\\n {type: \\""s\\"", value: \\""wafo\\""},\\r\\n\\t\\t\\t\\t\\t{type: \\""i\\"", value: 0},\\r\\n\\t\\t\\t\\t\\t{type: \\""s\\"", value: \\""mixer1\\""},\\r\\n\\t\\t\\t\\t\\t{type: \\""i\\"", value: 1}\\r\\n ]\\r\\n }\\r\\n\\t\\t\\t\\r\\n ]\\r\\n });\\r\\nOSC.SendAsSlipToSerial(data);"",""x"":2280,""y"":210,""z"":""3629fcd9.ccc604"",""bgColor"":""#F6F8BC"",""wires"":[]},{""id"":""Main_group1"",""type"":""group"",""name"":""mixer"",""comment"":"""",""w"":228,""h"":472,""textSize"":14,""nodes"":[""Main_Slider1"",""Main_Slider2"",""Main_Slider3"",""Main_Slider4"",""Main_Button6"",""Main_Button13""],""border_color"":""rgba(153,153,153,1)"",""individualListBoxMode"":true,""exportAsClass"":true,""x"":1300,""y"":30,""z"":""3629fcd9.ccc604"",""bgColor"":""rgba(221,255,187,1)"",""wires"":[]},{""id"":""Main_Button6"",""type"":""UI_Button"",""name"":""set all mixer gains to 0.10"",""tag"":""g"",""comment"":"""",""w"":176,""h"":34,""textSize"":14,""midiCh"":""0"",""midiId"":""0"",""pressAction"":"""",""repeatPressAction"":false,""releaseAction"":"""",""repeatReleaseAction"":false,""local"":""true"",""sendCommand"":""var parentName = d.parentGroup.name;\\r\\nvar gain = 0.10;\\r\\nvar addr = RED.OSC.settings.RootAddress + \\""/audio/\\""+d.parentGroup.name+\\""/\\""+d.tag+\\""*\\"";\\r\\n\\r\\nvar bundle = OSC.CreateBundle(0);\\r\\nbundle.packets.push(OSC.CreatePacket(addr,\\""if\\"",0,gain));\\r\\nbundle.packets.push(OSC.CreatePacket(addr,\\""if\\"",1,gain));\\r\\nbundle.packets.push(OSC.CreatePacket(addr,\\""if\\"",2,gain));\\r\\nbundle.packets.push(OSC.CreatePacket(addr,\\""if\\"",3,gain));\\r\\nOSC.SendData(OSC.CreateBundleData(bundle));\\r\\n\\r\\n// update sliders in ui\\r\\nfor (var i=0; i 0) freq *= (float)(1<=0;i--) if (AVAIL == allocate[i] || note == allocate[i]) { allocate[i] = note; break; } return i; } // return index of allocation array where note // was allocated, and mark as available int deallocateMIDI(byte note) { int i; for (i=COUNT_OF(allocate)-1;i>=0;i--) if (note == allocate[i]) { allocate[i] = AVAIL; pending[i] = note; break; } return i; } //----------------------------------------------------- int waveform1,waveform2; float detune2 = 1.0f,pw=0.5f; //----------------------------------------------------- void OSCnoteOn(byte channel, byte note, byte velocity) { float freq; OSCBundle bndl; OSCBundle reply; int slot = allocateMIDI(note); if (slot >= 0) { char buf[50]; //Serial.print(""\\nNote on: ""); freq = note2freq(note,wellTempered); //Serial.println(freq); dbgMIDI(channel,0x80,note,velocity); uint32_t st = micros(); #if !defined(USE_GROUPS) sprintf(buf,""/teensy1/audio/wav%c1/be"",slot+'A'); #else sprintf(buf,""/teensy1/audio/voice1/i%c/wav/be"",slot+'0'); #endif // !defined(USE_GROUPS) bndl.add(buf).add(velocity/127.0f).add(freq).add(waveform1); #if !defined(USE_GROUPS) sprintf(buf,""/teensy1/audio/wav%c2/be"",slot+'A'); #else sprintf(buf,""/teensy1/audio/voice1/i%c/wav2/be"",slot+'0'); #endif // !defined(USE_GROUPS) bndl.add(buf).add(velocity/127.0f).add(freq*detune2).add(waveform2); #if !defined(USE_GROUPS) sprintf(buf,""/teensy1/audio/env%c/noteOn"",slot+'A'); #else sprintf(buf,""/teensy1/audio/voice1/i%c/env/noteOn"",slot+'0'); #endif // !defined(USE_GROUPS) bndl.add(buf); //bndl.send(Serial); // for debug! reply.add(""/noteOn""); processBundle(&bndl,reply); st = micros() - st; //Serial.printf(""OSC processing took %d us\\n"",st); } } // poll all releasing envelopes to see // if we can stop the associated waveforms // to save some CPU load uint32_t nextPoll; void pollMIDIstopWav() { if (millis() > nextPoll) { nextPoll = millis() + 10; // only poll every 10ms or so for (size_t i=0;igetBoolean(2); if (!envActive) { pending[i] = AVAIL; bndl.empty(); reply.empty(); #if !defined(USE_GROUPS) sprintf(buf,""/teensy1/audio/wav%c1/amp"",slot+'A'); bndl.add(buf).add(0.0f); sprintf(buf,""/teensy1/audio/wav%c2/amp"",slot+'A'); bndl.add(buf).add(0.0f); #else sprintf(buf,""/teensy1/audio/voice1/i%c/wa*/amp"",slot+'0'); bndl.add(buf).add(0.0f); #endif // !defined(USE_GROUPS) reply.add(""/wavStop""); processBundle(&bndl,reply); } } } } } void OSCnoteOff(byte channel, byte note, byte velocity) { OSCBundle bndl; OSCBundle reply; int slot = deallocateMIDI(note); //Serial.print(""\\nNote off: ""); dbgMIDI(channel,0x90,note,velocity); if (slot >= 0) { char buf[50]; #if !defined(USE_GROUPS) sprintf(buf,""/teensy1/audio/env%c/noteOff"",slot+'A'); bndl.add(buf); #else sprintf(buf,""/teensy1/audio/voice1/i%c/env/noteOff"",slot+'0'); bndl.add(buf); #endif // !defined(USE_GROUPS) reply.add(""/noteOff""); processBundle(&bndl,reply); pending[slot] = note; // signal to poll that envelope is releasing } } //----------------------------------------------------- void handleCC(byte channel, byte control, byte value) { switch(control) { // V-Mini knobs case 14: waveform1 = value / 10; Serial.printf(""wav1 = %d\\n"",waveform1); break; case 15: waveform2 = value / 10; Serial.printf(""wav2 = %d\\n"",waveform2); break; case 16: { int off = value - 64; detune2 = pow(2.0,off / 16.0); Serial.print(""detune = ""); Serial.println(detune2); } break; case 17: { OSCBundle bndl; OSCBundle reply; pw = (value+1) / 256.0; // go from 0.39% to 50% //Serial.print(""pulse width = ""); //Serial.println(pw); #if !defined(USE_GROUPS) bndl.add(""/teensy1/audio/wav*/pul"").add(pw); #else bndl.add(""/teensy1/audio/voice1/i*/wa*/pul"").add(pw); #endif // !defined(USE_GROUPS) //bndl.send(Serial); // for debug! reply.add(""/pw""); processBundle(&bndl,reply); //reply.send(Serial); } break; } } void initMIDI(void) { pinMode(LED_BUILTIN,OUTPUT); // use as MIDI monitor usbMIDI.setHandleNoteOff(OSCnoteOff); usbMIDI.setHandleNoteOn(OSCnoteOn); usbMIDI.setHandleControlChange(handleCC); for (size_t i=0;iThe font is based on ""uni05_53.ttf"" from Craig Kroeger (http://www.miniml.com) and was * converted to a Bitmap Font with ""GlyphDesigner"" from 71squared (http://www.71squared.com). *

*/ internal class MiniBitmapFont2D { private static const BITMAP_WIDTH:int = 128; private static const BITMAP_HEIGHT:int = 64; private static const BITMAP_DATA:Array = [2027613533, 3413039936, 202148514, 2266925598, 4206886452, 4286853117, 2034947, 3202703399, 352977282, 2957757964, 3113652880, 2158068882, 1468709156, 2268063717, 2779310143, 2101025806, 3416509055, 4215794539, 3602168838, 1038056207, 1932393374, 3182285627, 3086802234, 1741291262, 2017257123, 3395280843, 984074419, 3049693147, 3986077023, 1055013549, 1806563255, 1754714962, 1577746187, 1124058786, 3888759258, 2482229043, 2916583666, 3743065328, 866060213, 1695195001, 2401582068, 3113347901, 2616521596, 1053798161, 2093370968, 4229025683, 560451479, 854767518, 2610241322, 4279041348, 4181572480, 4031244973, 587139110, 1081376765, 962217926, 783603325, 3605526425, 4102001916, 289204733, 2635140255, 3453981695, 3487854373, 2132197241, 3164775074, 4257640328, 770238970, 144664537, 707141570, 2934433071, 871272893, 512964596, 808491899, 481894297, 3095982481, 3598364156, 1710636358, 2904016319, 1751040139, 596966466, 1363963692, 465815609, 315567311, 4290666159, 4086022551, 179721458, 2221734970, 3942224988, 1519355876, 3292323782, 3933427230, 3314199893, 3736227348, 3846038425, 603088884, 2677349227, 3207069327, 3555275967, 3063054283, 3064577213, 3412044179, 693642210, 4280513949, 762928717, 1802215333, 3774849674, 4221155330, 970959395, 557220237, 2107226136, 3509822982, 3403284788, 4265820019, 898597576, 991077243, 2091615904, 3334716888, 633599866, 4218780109, 2216000376, 834870947, 2118009742, 1362731961, 236280636, 1274945142, 1458729366, 797960805, 3289369720, 2103717340, 3946406003, 2676522889, 1624104606, 1156993903, 3186170404, 2254499071, 1204911924, 1314218830, 3307086392, 2824275959, 3839865679, 2073394964, 1873329433, 1754205930, 1528429545, 1631106062, 2263272465, 4220497047, 3522893765, 3641376303, 707451487, 3452496787, 1390653868, 2620555793, 1027328684, 3419683476, 3662193703, 765701986, 3808279132, 786403271, 3824435837, 713234896, 4261856399, 3471930731, 3993492879, 1447960461, 1398434593, 1914230187, 2398643285, 4156374464, 3859339207, 3220700061, 3373248762, 3186030434, 1315917060, 2809852481, 4008553903, 4105611953, 1599499652, 3513857591, 877854499, 4198259455, 3648560077, 2838035419, 3255594190, 2465578457, 4263505201, 534904657, 2889261598, 1358214576, 1069250354, 3870010557, 2628896583, 3448610878, 442343309, 1024736866, 4015119133, 3250867279, 1513359261, 2442089596, 1944476762, 735490552, 426990058, 4234106111, 1204305707, 3330995265, 2398649368, 4221048123, 1724669255, 3801115709, 3489328790, 3896402933, 3696936939, 2836983295, 3656750393, 3349724512, 3810416287, 3654997608, 4284455103, 2294939563, 4207697932, 642748805, 2476981639, 2319419898, 572956615, 3833238940, 964924880, 2081600351, 3572458416, 2056247513, 1951368808, 2133449703, 2783728628, 512866577, 913279200, 1678129016, 3488578991, 3373952929, 2562996951, 3666058925, 1664169178, 1943591935, 750675303, 154399903, 2571590890, 852654952, 4117307766, 1971649621, 4180195820, 1222535348, 4283953215, 2880662236, 2717410980, 1175907705, 1157322027, 505963121, 2631540616, 3661227656, 3591803353, 2624126821, 1948662907, 3596065103, 1147387734, 256773959, 1173572460, 2361957471, 4210876076, 3080180620, 3464801210, 3821654259, 1465302035, 2851185457, 3143266144, 3793180414, 3368833103, 4274670712, 3473819108, 3487569332, 773123355, 1618635668, 2570176190, 2075248691, 1740805534, 288646743, 1837597401, 603556968, 3182536872, 673184603, 3088757053, 2897054404, 3192651316, 2885335802, 1057233368, 1118437241, 4182126463, 3110464775, 3313191614, 2360987274, 735505357, 2992631425, 2360928811, 4187834527, 279183208, 1586420003, 1174008423, 4062987589, 1162167621, 1162167621, 1162167621, 1162167621, 1174119799, 787274608]; private static const XML_DATA:XML = ; public static function get texture():Texture2D { var bmpData:BitmapData = new BitmapData(BITMAP_WIDTH, BITMAP_HEIGHT); var bmpBytes:ByteArray = new ByteArray(); var numBytes:int = BITMAP_DATA.length; for (var i:int = 0; i < numBytes; ++i) bmpBytes.writeUnsignedInt(BITMAP_DATA[i]); bmpBytes.uncompress(); bmpData.setPixels(new Rectangle(0, 0, BITMAP_WIDTH, BITMAP_HEIGHT), bmpBytes); return Texture2D.fromBitmapData(bmpData, false); } public static function get xml():XML { return XML_DATA; } } }",12411,True,3278.594292781665,median "/*********************************************************** File name: Adeept6LegSpiderRobot.ino Description: In the example code provided, the robot supports 2 working modes: remote control and automatic obstacle avoidance. Under the remote control mode, you can make the bot stand, squat, go forward and backward, and turn left and right with the remotxe control. Under the mode of automatic obstacle avoidance, it will go forward automatically, and bypass obstacles in front if any and continue to walk ahead then. Website: www.adeept.com E-mail: support@adeept.com Author: Tom Date: 2017/08/23 ***********************************************************/ // //PWM31 // head // (PWM2)(PWM1)(PWM0)// //(PWM16)(PWM17)(PWM18) // Left forefoot right forefoot // (PWM5)(PWM4)(PWM3)// //(PWM19)(PWM20)(PWM21) // Left foot right foot // (PWM8)(PWM7)(PWM6)// //(PWM22)(PWM23)(PWM24) // Left hind foot right hind foot #include #include #include ""RF24.h"" char pwm00Calibration = 0; char pwm01Calibration = 0; char pwm02Calibration = 0; char pwm03Calibration = 0; char pwm04Calibration = 0; char pwm05Calibration = 0; char pwm06Calibration = 0; char pwm07Calibration = 0; char pwm08Calibration = 0; char pwm16Calibration = 0; char pwm17Calibration = 0; char pwm18Calibration = 0; char pwm19Calibration = 0; char pwm20Calibration = 0; char pwm21Calibration = 0; char pwm22Calibration = 0; char pwm23Calibration = 0; char pwm24Calibration = 0; char pwm31Calibration = 0;//Ultrasonic steering gear offset int movementSpeed = 100; //The speed of movement of the robot Adeept_PWMPCA9685 pwm0 = Adeept_PWMPCA9685(0x40); //1+A5 A4 A3 A2 A1 A0+RW, RW is Read and Write Adeept_PWMPCA9685 pwm1 = Adeept_PWMPCA9685(0x41); //1+A5 A4 A3 A2 A1 A0+RW, RW is Read and Write uint8_t servonum = 0; RF24 radio(9, 10); // define the object to control NRF24L01 byte addresses[5] = ""00005""; // define communication address which should correspond to remote control int data[9]={512, 512, 1, 0, 1, 1, 512, 512, 512}; // define array used to save the communication data int mode[1]; int trigPin = 3; // define Trig pin for ultrasonic ranging module int echoPin = 2; // define Echo pin for ultrasonic ranging module float maxDistance = 200; // define the range(cm) for ultrasonic ranging module, Maximum sensor distance is rated at 400-500cm. float soundVelocity = 340; // Sound velocity = 340 m/s float rangingTimeOut = 2 * maxDistance / 100 / soundVelocity * 1000000; // define the timeout(ms) for ultrasonic ranging module const int buzzerPin = 8; // define pin for buzzer int automatic = 0; int upOrDown = 0; int oneTime = 0; char oneForward = 0; //Avoid repeating the 'start***()' 'stop***()' program several times before proceeding char oneBackward = 0;//Avoid repeating the 'start***()' 'stop***()' program multiple times in the back char oneRight = 0; //Avoid repeating the 'start***()' 'stop***()' program repeatedly on the right turn char oneLeft = 0; //Avoid repeating the 'start***()' 'stop***()' program multiple times on the left char detectCommunication = 0; //Check whether the communication is connected. Reboot the communication if it is not char standingWay = 0; //The setting can only be run when the robot is standing(standingWay=1) char automaticTime = 0; //Set the robot's operating mode(automaticTime=1:Automatic mode of operation. automaticTime=0:Manual mode of operation) void setup() { radio.begin(); // initialize RF24 radio.setRetries(0, 15); // set retries times radio.setPALevel(RF24_PA_LOW); // set power radio.openReadingPipe(1, addresses);// open delivery channel radio.startListening(); // start monitoring delay(100); pwm0.begin(); pwm0.setPWMFreq(60); // Analog servos run at ~60 Hz updates pwm1.begin(); pwm1.setPWMFreq(60); // Analog servos run at ~60 Hz updates pinMode(trigPin, OUTPUT); // set trigPin to output mode pinMode(echoPin, INPUT); // set echoPin to input mode //Control the RGB light to display red pwm0.setPWM(13, 0, 4095); pwm0.setPWM(14, 0, 4095); pwm0.setPWM(15, 0, 0); calibration(); pwm1.setPWM(15, 0, angle(pwm31Calibration + 90));//Control the PWM31 to 90 degrees } void loop() { receiveData(); if(!data[2]){//Detect standing or squatting. upOrDown++ ;if(oneTime==0){down();oneTime=1;standingWay=1;} if(upOrDown>1){upOrDown=0;if(oneTime==1){up();oneTime=0;standingWay=0;}} } if(standingWay == 1){ if(automatic == 1){//Automatic obstacle avoidance mode //Control RGB lights show green pwm0.setPWM(13, 0, 4095); pwm0.setPWM(14, 0, 0); pwm0.setPWM(15, 0, 4095); byte barDistance = maxDistance; // save the minimum measured distance from obstacles byte barDegree; // save the minimum measured angel from obstacles byte distance; // save the current the measured distance from obstacles // define the initial scanning position servo of pan tilt pwm1.setPWM(15, 0, angle(pwm31Calibration + 90)); // start to scan distance. During this progress, we will get the distance and angle from the closest obstacle for (byte ultrasonicServoDegree = 40; ultrasonicServoDegree < 140; ultrasonicServoDegree += 10) { pwm1.setPWM(15, 0, angle(pwm31Calibration + ultrasonicServoDegree)); // steer pan tilt to corresponding position delay(50); // wait 50ms between pings (about 40 pingsc). 29ms should be the shortest delay between pings. receiveData(); distance = getDistance(); // detect the current distance from obstacle with angle of pan tilt stable if (distance < barDistance) { // if the current measured distance is smaller than the previous one, save the data of current measured distance barDegree = ultrasonicServoDegree; // save the measured angle barDistance = distance; // save the measured distance } } // servo of pan tilt turns to default position pwm1.setPWM(15, 0, angle(pwm31Calibration + 90)); // According to the result of scanning control action of intelligent vehicles if(barDistance >= 30) { // if the obstacle distance is not close, move on if(automaticTime==0){startForward();automaticTime=1;} turnForward(); }else { // if the obstacle distance is too close, reverse the travelling direction stopForward();startBackward();turnBackward();turnBackward();stopBackward(); if(barDegree < 90){ // choose to reverse direction according to the angle with obstacle startLeftTow();turnLeftTow();turnLeftTow();stopLeftTow();automaticTime=0; }else{ startRightTow();turnRightTow();turnRightTow();stopRightTow();automaticTime=0; } } } if(automatic == 0){//Remote control mode if(automaticTime!=0){ stopForward(); automaticTime=0; } //Control the RGB light to display blue pwm0.setPWM(13, 0, 0); pwm0.setPWM(14, 0, 4095); pwm0.setPWM(15, 0, 4095); if(data[1]>600&&oneBackward==0&&oneRight==0&&oneLeft==0){ //Go ahead if(oneForward==0){startForward();oneForward=1;} turnForward(); }else if(oneForward==1){oneForward=0;stopForward();} if(data[1]<400&&oneForward==0&&oneRight==0&&oneLeft==0){//Backwards if(oneBackward==0){startBackward();oneBackward=1;} turnBackward(); }else if(oneBackward==1){oneBackward=0; stopBackward();} if(data[8]<400&&oneForward==0&&oneBackward==0&&oneLeft==0){//Turn right if(oneRight==0){startRightTow();oneRight=1;} turnRightTow(); }else if(oneRight==1){oneRight=0; stopRightTow();} if(data[8]>600&&oneForward==0&&oneBackward==0&&oneRight==0){//Turn left if(oneLeft==0){startLeftTow();oneLeft=1;} turnLeftTow(); }else if(oneLeft==1){oneLeft=0;stopLeftTow();} } }else{ //Control the RGB light to display red pwm0.setPWM(13, 0, 4095); pwm0.setPWM(14, 0, 4095); pwm0.setPWM(15, 0, 0); } delay(100); // upDown(); // standUp(); // calibration(); } int angle(int angle){//Angle conversion if(angle>=180){angle=180;} if(angle<=0){angle=0;} return map(angle,0,180,130,600);//130-600 } int oppAngle(int oppAngle){// The opposite direction angle conversion if(oppAngle>=180){oppAngle=180;} if(oppAngle<=0){oppAngle=0;} return map(oppAngle,0,180,600,130);//600-130 } //Control robot back void startBackward(void){ int i; int j=90; pwm0.setPWM(2, 0, angle(pwm02Calibration + 170)); pwm0.setPWM(5, 0, angle(pwm05Calibration + 170)); pwm0.setPWM(8, 0, angle(pwm08Calibration + 170)); pwm1.setPWM(2, 0, oppAngle(pwm18Calibration + 170)); pwm1.setPWM(5, 0, oppAngle(pwm21Calibration + 170)); pwm1.setPWM(8, 0, oppAngle(pwm24Calibration + 170)); for(i=90;i>50;i--){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); if(i>70){j--;if(j<=55){j=55;}} if(i<=70){j++;if(j>=90){j=90;}} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=90;i>50;i--){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); if(i>70){j--;if(j<=55){j=55;}} if(i<=70){j++;if(j>=90){j=90;}} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=90;i>50;i--){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); if(i>70){j--;if(j<=55){j=55;}} if(i<=70){j++;if(j>=90){j=90;}} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } j=90; for(i=50;i<120;i++){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } } void turnBackward(void){ int i; int j=90; for(i=120;i>85;i--){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j--;if(j<=55){j=55;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=85;i>50;i--){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } j=90; for(i=120;i>85;i--){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j--;if(j<=55){j=55;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=85;i>50;i--){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } j=90; for(i=120;i>85;i--){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j--;if(j<=55){j=55;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=85;i>50;i--){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } j=90; for(i=50;i<120;i++){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } } void stopBackward(void){ int i; int j=90; for(i=120;i>90;i--){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); if(i>105){j--;if(j<=75){j=75;}} if(i<=105){j++;if(j>=90){j=90;}} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=120;i>90;i--){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); if(i>105){j--;if(j<=75){j=75;}} if(i<=105){j++;if(j>=90){j=90;}} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } for(i=120;i>90;i--){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); if(i>105){j--;if(j<=75){j=75;}} if(i<=105){j++;if(j>=90){j=90;}} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[1],0,400,10,100); } } } //Control the robot forward void startForward(void){ int i; int j=90; pwm0.setPWM(2, 0, angle(pwm02Calibration + 170)); pwm0.setPWM(5, 0, angle(pwm05Calibration + 170)); pwm0.setPWM(8, 0, angle(pwm08Calibration + 170)); pwm1.setPWM(2, 0, oppAngle(pwm16Calibration + 170)); pwm1.setPWM(5, 0, oppAngle(pwm21Calibration + 170)); pwm1.setPWM(8, 0, oppAngle(pwm24Calibration + 170)); for(i=90;i<130;i++){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); if(i<=110){j--;if(j<=55){j=55;}} if(i>110){j++;if(j>=90){j=90;}} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=90;i<130;i++){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); if(i<=110){j--;if(j<=55){j=55;}} if(i>110){j++;if(j>=90){j=90;}} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=90;i<130;i++){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); if(i<=110){j--;if(j<=55){j=55;}} if(i>110){j++;if(j>=90){j=90;}} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } j=90; for(i=130;i>60;i--){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } } void turnForward(void){ int i; int j=90; for(i=60;i<95;i++){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j--;if(j<=55){j=55;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=95;i<130;i++){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } j=90; for(i=60;i<95;i++){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j--;if(j<=55){j=55;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=95;i<=130;i++){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } j=90; for(i=60;i<95;i++){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j--;if(j<=55){j=55;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=95;i<=130;i++){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } j=90; for(i=130;i>60;i--){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } } void stopForward(void){ int i; int j=90; for(i=60;i<90;i++){ pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); if(i<=75){j--;if(j<=75){j=75;}} if(i>75){j++;if(j>=90){j=90;}} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=60;i<90;i++){ pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); if(i<=75){j--;if(j<=75){j=75;}} if(i>75){j++;if(j>=90){j=90;}} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } for(i=60;i<90;i++){ pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); if(i<=75){j--;if(j<=75){j=75;}} if(i>75){j++;if(j>=90){j=90;}} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[1]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[1],600,1023,100,10); } } } //Control the robot to the left, two legs with the rotation void startLeftTow(void){ int i; int j=90; pwm0.setPWM(2, 0, angle(pwm02Calibration + 170)); pwm0.setPWM(5, 0, angle(pwm05Calibration + 170)); pwm0.setPWM(8, 0, angle(pwm08Calibration + 170)); pwm1.setPWM(2, 0, oppAngle(pwm18Calibration + 170)); pwm1.setPWM(5, 0, oppAngle(pwm21Calibration + 170)); pwm1.setPWM(8, 0, oppAngle(pwm24Calibration + 170)); for(i=90;i<115;i++){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j--;if(j<=65){j=65;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=115;i<140;i++){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } j=90; for(i=90;i<115;i++){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j--;if(j<=65){j=65;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j));pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=115;i<140;i++){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } j=90; for(i=90;i<115;i++){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j--;if(j<=65){j=65;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=115;i<140;i++){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=140;i>=40;i--){ pwm0.setPWM(0, 0, angle( pwm00Calibration + i)); pwm0.setPWM(3, 0, angle( pwm03Calibration + i)); pwm0.setPWM(6, 0, angle( pwm06Calibration + i)); pwm1.setPWM(0, 0, angle( pwm16Calibration + i)); pwm1.setPWM(3, 0, angle( pwm19Calibration + i)); pwm1.setPWM(6, 0, angle( pwm20Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } } void turnLeftTow(void){ int i; int j=90; for(i=40;i<90;i++){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j--;if(j<=0){j=40;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=90;i<140;i++){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } j=90; for(i=40;i<90;i++){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j--;if(j<=0){j=40;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=90;i<140;i++){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } j=90; for(i=40;i<90;i++){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j--;if(j<=0){j=40;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=90;i<140;i++){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } for(i=140;i>=40;i--){ pwm0.setPWM(0, 0, angle( pwm00Calibration + i)); pwm0.setPWM(3, 0, angle( pwm03Calibration + i)); pwm0.setPWM(6, 0, angle( pwm06Calibration + i)); pwm1.setPWM(0, 0, angle( pwm16Calibration + i)); pwm1.setPWM(3, 0, angle( pwm19Calibration + i)); pwm1.setPWM(6, 0, angle( pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } } void stopLeftTow(void){ int i; for(i=40;i<90;i++){ pwm0.setPWM(0, 0, angle( pwm00Calibration + i)); pwm0.setPWM(3, 0, angle( pwm03Calibration + i)); pwm0.setPWM(6, 0, angle( pwm06Calibration + i)); pwm1.setPWM(0, 0, angle( pwm16Calibration + i)); pwm1.setPWM(3, 0, angle( pwm19Calibration + i)); pwm1.setPWM(6, 0, angle( pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]<=600){ movementSpeed = 10; }else{ movementSpeed = map(data[8],600,1023,100,10); } } } //Control the robot to the left, two legs with the rotation void startRightTow(void){ int i; int j=90; pwm0.setPWM(2, 0, angle(pwm02Calibration + 170)); pwm0.setPWM(5, 0, angle(pwm05Calibration + 170)); pwm0.setPWM(8, 0, angle(pwm08Calibration + 170)); pwm1.setPWM(2, 0, oppAngle(pwm18Calibration + 170)); pwm1.setPWM(5, 0, oppAngle(pwm21Calibration + 170)); pwm1.setPWM(8, 0, oppAngle(pwm24Calibration + 170)); for(i=90;i>65;i--){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); pwm1.setPWM(7, 0, angle(pwm23Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } j=65; for(i=65;i>40;i--){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle( pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=90;i>65;i--){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i));pwm1.setPWM(4, 0, angle(pwm20Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } j=65; for(i=65;i>40;i--){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=90;i>65;i--){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); pwm1.setPWM(1, 0, angle(pwm17Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } j=65; for(i=65;i>40;i--){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=40;i<=140;i++){ pwm0.setPWM(0, 0, angle( pwm00Calibration + i)); pwm0.setPWM(3, 0, angle( pwm03Calibration + i)); pwm0.setPWM(6, 0, angle( pwm06Calibration + i)); pwm1.setPWM(0, 0, angle( pwm16Calibration + i)); pwm1.setPWM(3, 0, angle( pwm19Calibration + i)); pwm1.setPWM(6, 0, angle( pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } } void turnRightTow(void){ int i; int j=90; for(i=140;i>90;i--){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j--;if(j<=0){j=40;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle(pwm23Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=90;i>40;i--){ pwm0.setPWM(0, 0, angle(pwm00Calibration + i)); pwm1.setPWM(6, 0, angle(pwm22Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + j)); pwm1.setPWM(7, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } j=90; for(i=140;i>90;i--){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j--;if(j<=0){j=40;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=90;i>40;i--){ pwm0.setPWM(3, 0, angle(pwm03Calibration + i)); pwm1.setPWM(3, 0, angle(pwm19Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + j)); pwm1.setPWM(4, 0, angle(pwm20Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } j=90; for(i=140;i>90;i--){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j--;if(j<=0){j=40;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=90;i>40;i--){ pwm0.setPWM(6, 0, angle(pwm06Calibration + i)); pwm1.setPWM(0, 0, angle(pwm16Calibration + i)); j++;if(j>=90){j=90;} pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + j)); pwm1.setPWM(1, 0, angle(pwm17Calibration + j)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } for(i=40;i<=140;i++){ pwm0.setPWM(0, 0, angle( pwm00Calibration + i)); pwm0.setPWM(3, 0, angle( pwm03Calibration + i)); pwm0.setPWM(6, 0, angle( pwm06Calibration + i)); pwm1.setPWM(0, 0, angle( pwm16Calibration + i)); pwm1.setPWM(3, 0, angle( pwm19Calibration + i)); pwm1.setPWM(6, 0, angle( pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } } void stopRightTow(void){ int i; for(i=140;i>=90;i--){ pwm0.setPWM(0, 0, angle( pwm00Calibration + i)); pwm0.setPWM(3, 0, angle( pwm03Calibration + i)); pwm0.setPWM(6, 0, angle( pwm06Calibration + i)); pwm1.setPWM(0, 0, angle( pwm16Calibration + i)); pwm1.setPWM(3, 0, angle( pwm19Calibration + i)); pwm1.setPWM(6, 0, angle( pwm22Calibration + i)); delay(movementSpeed); receiveData(); if(data[8]>=400){ movementSpeed = 10; }else{ movementSpeed = map(data[8],0,400,10,100); } } } void down(void){ int m=0; int n=0; //Each leg interval of about 60 degrees. pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + 90)); pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + 90)); pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + 90)); pwm1.setPWM(0, 0, angle(pwm16Calibration + 90)); pwm1.setPWM(3, 0, angle(pwm19Calibration + 90)); pwm1.setPWM(6, 0, angle(pwm22Calibration + 90)); m=10;n=30; receiveData(); for(int i=0;i<20;i++){ pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + m)); pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + m)); pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + m)); pwm1.setPWM(1, 0, angle(pwm17Calibration + m)); pwm1.setPWM(4, 0, angle(pwm20Calibration + m)); pwm1.setPWM(7, 0, angle(pwm23Calibration + m)); pwm0.setPWM(2, 0, oppAngle(pwm02Calibration + n)); pwm0.setPWM(5, 0, oppAngle(pwm05Calibration + n)); pwm0.setPWM(8, 0, oppAngle(pwm08Calibration + n)); pwm1.setPWM(2, 0, angle(pwm18Calibration + n)); pwm1.setPWM(5, 0, angle(pwm21Calibration + n)); pwm1.setPWM(8, 0, angle(pwm24Calibration + n)); delay(25);receiveData();delay(25);m++;n--; } receiveData(); for(m=30;m<=90;m++){ pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + m)); pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + m)); pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + m)); pwm1.setPWM(1, 0, angle(pwm17Calibration + m)); pwm1.setPWM(4, 0, angle(pwm20Calibration + m)); pwm1.setPWM(7, 0, angle(pwm23Calibration + m)); delay(25);receiveData();delay(25); } } void up(void){ int m=0; int n=0; m=90;n=10; receiveData(); for(m=90;m>=30;m--){ pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + m)); pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + m)); pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + m)); pwm1.setPWM(1, 0, angle(pwm17Calibration + m)); pwm1.setPWM(4, 0, angle(pwm20Calibration + m)); pwm1.setPWM(7, 0, angle(pwm23Calibration + m)); delay(25);receiveData();delay(25); } receiveData(); for(int i=0;i<20;i++){ pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + m)); pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + m)); pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + m)); pwm1.setPWM(1, 0, angle(pwm17Calibration + m)); pwm1.setPWM(4, 0, angle(pwm20Calibration + m)); pwm1.setPWM(7, 0, angle(pwm23Calibration + m)); pwm0.setPWM(2, 0, oppAngle(pwm02Calibration + n)); pwm0.setPWM(5, 0, oppAngle(pwm05Calibration + n)); pwm0.setPWM(8, 0, oppAngle(pwm08Calibration + n)); pwm1.setPWM(2, 0, angle(pwm18Calibration + n)); pwm1.setPWM(5, 0, angle(pwm21Calibration + n)); pwm1.setPWM(8, 0, angle(pwm24Calibration + n)); delay(25);receiveData();delay(25);m--;n++; } } void calibration(void){//6 feet position calibration //Six feet straight pwm0.setPWM(0, 0, oppAngle(pwm00Calibration + 90)); pwm0.setPWM(3, 0, oppAngle(pwm03Calibration + 90)); receiveData();delay(100); pwm0.setPWM(6, 0, oppAngle(pwm06Calibration + 90)); pwm0.setPWM(1, 0, oppAngle(pwm01Calibration + 90)); receiveData();delay(100); pwm0.setPWM(4, 0, oppAngle(pwm04Calibration + 90)); pwm0.setPWM(7, 0, oppAngle(pwm07Calibration + 90)); receiveData();delay(100); pwm0.setPWM(2, 0, oppAngle(pwm02Calibration + 90)); pwm0.setPWM(5, 0, oppAngle(pwm05Calibration + 90)); receiveData();delay(100); pwm0.setPWM(8, 0, oppAngle(pwm08Calibration + 90)); pwm1.setPWM(0, 0, angle(pwm16Calibration + 90)); receiveData();delay(100); pwm1.setPWM(3, 0, angle(pwm19Calibration + 90)); pwm1.setPWM(6, 0, angle(pwm22Calibration + 90)); receiveData();delay(100); pwm1.setPWM(1, 0, angle(pwm17Calibration + 90)); pwm1.setPWM(4, 0, angle(pwm20Calibration + 90)); receiveData();delay(100); pwm1.setPWM(7, 0, angle(pwm23Calibration + 90)); pwm1.setPWM(2, 0, angle(pwm18Calibration + 90)); receiveData();delay(100); pwm1.setPWM(5, 0, angle(pwm21Calibration + 90)); pwm1.setPWM(8, 0, angle(pwm24Calibration + 90)); } float getDistance() { unsigned long pingTime; // save the high level time returned by ultrasonic ranging module float distance; // save the distance away from obstacle // set the trigPin output 10us high level to make the ultrasonic ranging module start to measure digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // get the high level time returned by ultrasonic ranging module pingTime = pulseIn(echoPin, HIGH, rangingTimeOut); if (pingTime != 0) { // if the measure is not overtime distance = pingTime * soundVelocity / 2 / 10000; // calculate the obstacle distance(cm) according to the time of high level returned return distance; // return distance(cm) } else // if the measure is overtime return maxDistance; // returns the maximum distance(cm) } void receiveData(){ detectCommunication++; if ( radio.available()) { // if receive the data while (radio.available()) { // read all the data radio.read( data, sizeof(data) ); // read data } detectCommunication = 0; if(!data[3]){ automatic = 0; } if(!data[4]){ automatic = 1; } if (!data[5])// control the buzzer tone(buzzerPin, 2000); else noTone(buzzerPin); } if(detectCommunication>=100){ detectCommunication = 0; radio.begin(); // initialize RF24 radio.setRetries(0, 15); // set retries times radio.setPALevel(RF24_PA_LOW); // set power radio.openReadingPipe(1, addresses);// open delivery channel radio.startListening(); // start monitoring } //movementSpeed = map(data[6],0,1023,0,100); } ",16249,True,4533.614434924567,median """!

Favorites tree controller

CLASS zcl_dbbr_favorites_tree DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. INTERFACES zif_uitb_content_searcher . INTERFACES zif_uitb_gui_view. INTERFACES zif_uitb_gui_control . ALIASES focus FOR zif_uitb_gui_control~focus . ALIASES has_focus FOR zif_uitb_gui_control~has_focus . ALIASES free FOR zif_uitb_gui_control~free. CONSTANTS: BEGIN OF c_context_codes, personal_favorites TYPE sy-ucomm VALUE 'PRIV_FAV', global_favorites TYPE sy-ucomm VALUE 'GLOBAL_FAV', collapse_node TYPE sy-ucomm VALUE 'COLLAPSE', collapse_node_all TYPE sy-ucomm VALUE 'COLLAPSE_ALL', expand_node TYPE sy-ucomm VALUE 'EXPAND', expand_node_all TYPE sy-ucomm VALUE 'EXPAND_ALL', insert_folder TYPE sy-ucomm VALUE 'INS_FOLDER', show_in_object_browser TYPE sy-ucomm VALUE 'SHOWINOBJBROWSER', edit_favorite TYPE sy-ucomm VALUE 'EDIT_FAV', delete_favorite TYPE sy-ucomm VALUE 'DELETE_FAV', insert_favorite TYPE sy-ucomm VALUE 'INS_FAV', insert_current TYPE sy-ucomm VALUE 'INS_CURRENT', move_up TYPE sy-ucomm VALUE 'MOVE_UP', move_down TYPE sy-ucomm VALUE 'MOVE_DOWN', search TYPE sy-ucomm VALUE 'SEARCH', search_more TYPE sy-ucomm VALUE 'SEARCH_MORE', clear_list TYPE sy-ucomm VALUE 'CLEAR_LIST', delete_most_used_entry TYPE sy-ucomm VALUE 'CLEAR_ENTRY', start_with_default_variant TYPE sy-ucomm VALUE 'RUNDEFAULTVAR', load_full_history TYPE sy-ucomm VALUE 'LOADFULLHIST', import_from_clipboard TYPE sy-ucomm VALUE 'IMPFROMCLIP', END OF c_context_codes . ""!

Build/Re Build the favorite tree

METHODS build_tree IMPORTING !if_global TYPE boolean RAISING zcx_uitb_tree_error. ""!

Collapse the current node

METHODS collapse_node IMPORTING !if_collapse_all TYPE boolean OPTIONAL . ""!

CONSTRUCTOR

METHODS constructor IMPORTING !io_parent TYPE REF TO cl_gui_container OPTIONAL io_parent_view TYPE REF TO zif_uitb_gui_composite_view. ""!

Create new favorite

METHODS create_new_favorite IMPORTING !iv_fav_type TYPE zsat_favmenu_type OPTIONAL !iv_favorite TYPE tabname OPTIONAL iv_favorite_raw TYPE zsat_entity_id_raw OPTIONAL !iv_description TYPE ddtext OPTIONAL . ""!

Create new folder

METHODS create_new_fav_folder . ""!

Creates the tree

METHODS create_tree . ""!

Edits the current selected favorite

METHODS edit_favorite . ""!

Expands the current node

METHODS expand_node IMPORTING !if_expand_all TYPE boolean OPTIONAL . ""!

Retrieves the currently selected node

METHODS get_selected_favorite RETURNING VALUE(rr_node) TYPE REF TO zcl_uitb_ctm_node . ""!

Moves the current entry one position down

METHODS move_favorite_down . ""!

Moves the current entry one position up

METHODS move_favorite_up . ""!

Shows the tree

METHODS show IMPORTING !if_global TYPE abap_bool OPTIONAL RAISING zcx_uitb_tree_error . PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_fav_info, type TYPE zsat_favmenu_type, favorite TYPE tabname, favorite_raw TYPE zsat_entity_id_raw, description TYPE ddtext, END OF ty_fav_info. TYPES: tt_fav_info TYPE STANDARD TABLE OF ty_fav_info WITH EMPTY KEY. TYPES: BEGIN OF ty_node_map, node_key TYPE tm_nodekey, entity_id TYPE zsat_entity_id, entity_type TYPE zsat_entity_type, END OF ty_node_map . TYPES: BEGIN OF mty_node_data. INCLUDE TYPE treemsnod. TYPES: items TYPE treemcitab. TYPES: END OF mty_node_data . TYPES: BEGIN OF ty_s_variant_data, variant_id TYPE zdbbr_variant_id, entity_id TYPE zsat_entity_id, entity_type TYPE zsat_entity_type, END OF ty_s_variant_data. CONSTANTS c_hierarchy_node2 TYPE tv_itmname VALUE 'HIER2' ##no_text. CONSTANTS c_descr_column TYPE tv_itmname VALUE 'DESCR' ##NO_TEXT. CONSTANTS c_top_node TYPE tm_nodekey VALUE '00001' ##NO_TEXT. DATA mt_node_map TYPE SORTED TABLE OF ty_node_map WITH UNIQUE KEY node_key . DATA mv_last_var_node_key TYPE tm_nodekey VALUE '50000' ##NO_TEXT. DATA mo_tree_model TYPE REF TO zcl_uitb_column_tree_model . DATA mf_global_fav_mode TYPE boolean . DATA mo_favmenu_f TYPE REF TO zcl_dbbr_favmenu_factory . DATA mo_tree_dnd_behaviour TYPE REF TO cl_dragdrop . DATA mo_query_f TYPE REF TO zcl_dbbr_query_factory . DATA mo_parent_container TYPE REF TO cl_gui_container . DATA mo_parent_view TYPE REF TO zif_uitb_gui_composite_view. ""!

Creates multiple favorite entries from table entries

METHODS create_multiple_faventries IMPORTING it_favinfo TYPE tt_fav_info !io_selected_node TYPE REF TO zcl_uitb_ctm_node !is_parent_favmenu TYPE zdbbr_favmenu !iv_parent_relationship TYPE i RETURNING VALUE(rv_first_new_node) TYPE tm_nodekey . ""!

Deletes the current favorite

METHODS delete_favorite_node IMPORTING !io_selected_node TYPE REF TO zcl_uitb_ctm_node RETURNING VALUE(rf_deletion_success) TYPE boolean . ""!

Deletes several selected favorite entries

METHODS delete_selected_nodes . ""!

Checks if the favorite exists in the node

METHODS favorite_exists_in_node IMPORTING !io_node TYPE REF TO zcl_uitb_ctm_node RETURNING VALUE(rf_fav_exists) TYPE abap_bool . ""!

Fill the toolbar with functions

METHODS fill_toolbar . ""!

Gets favorite menu data for node

METHODS get_node_favmenu_data IMPORTING !io_node TYPE REF TO zcl_uitb_ctm_node RETURNING VALUE(rs_favmenu) TYPE zdbbr_favmenu . ""!

Get the selection mode

METHODS get_selection_mode RETURNING VALUE(result) TYPE i . ""!

Checks if the node is holds a db browser variant

""! METHODS is_variant_node IMPORTING io_node TYPE REF TO zcl_uitb_ctm_node RETURNING VALUE(rf_variant_node) TYPE abap_bool. ""!

handles a ui function code

""! METHODS handle_gui_function IMPORTING iv_code TYPE sy-ucomm iv_node_key TYPE tm_nodekey OPTIONAL. ""!

Loads all favorite nodes into the tree

METHODS load_favorite_nodes RAISING zcx_uitb_tree_error. ""!

Handler for when drop completed

METHODS on_drop_complete FOR EVENT drop_complete OF zif_uitb_tree_model_events IMPORTING !er_drag_drop_object !ev_item_name !ev_node_key . ""!

Handler for deleted entity -> remove invalid nodes

METHODS on_entity_deleted FOR EVENT entity_deleted OF zcl_dbbr_selscreen_util IMPORTING !ev_entity_id !ev_entity_type . ""!

Handler for when children are to be loaded lazily

METHODS on_expand_no_children FOR EVENT expand_no_children OF zif_uitb_tree_model_events IMPORTING !ev_node_key . ""!

Handler for requesting a context menu for a node

METHODS on_node_context_menu_request FOR EVENT node_context_menu_request OF zif_uitb_tree_model_events IMPORTING !er_menu !ev_node_key . ""!

Handler for when the context menu entry was chosen

METHODS on_node_context_menu_select FOR EVENT node_context_menu_select OF zif_uitb_tree_model_events IMPORTING !ev_fcode !ev_node_key . ""!

Handler for double click on node

METHODS on_node_double_click FOR EVENT node_double_click OF zif_uitb_tree_model_events IMPORTING !ev_node_key . ""!

Handler for ENTER key press on node

METHODS on_node_enter_key FOR EVENT node_keypress OF zif_uitb_tree_model_events IMPORTING !ev_key !ev_node_key . ""!

Handler for pressed toolbar button

METHODS on_toolbar_button FOR EVENT function_selected OF zif_uitb_toolbar_events IMPORTING !ev_fcode . ""!

Handler for Tree drag was started

METHODS on_tree_drag FOR EVENT drag OF zif_uitb_tree_model_events IMPORTING !er_drag_drop_object !ev_item_name !ev_node_key . ""!

Handler fro Multiple Tree drag was started

METHODS on_tree_drag_multiple FOR EVENT drag_multiple OF zif_uitb_tree_model_events IMPORTING !er_drag_drop_object !et_node_key_table !ev_item_name . ""!

Handler for a single drop

METHODS on_tree_drop FOR EVENT drop OF zif_uitb_tree_model_events IMPORTING !er_drag_drop_object !ev_node_key . ""!

Handler for multiple drops completed

METHODS on_tree_drop_complete_multiple FOR EVENT drop_complete_multiple OF zif_uitb_tree_model_events IMPORTING !er_drag_drop_object !et_node_key_table !ev_item_name . ""!

Checks if node should be displayed as folder

METHODS should_display_as_folder IMPORTING !iv_fav_type TYPE zsat_favmenu_type !if_has_variants TYPE abap_bool RETURNING VALUE(result) TYPE abap_bool . ""!

Delete favorite

""! ""! @parameter io_node |

""! @parameter if_update_selection |

METHODS delete_favorite IMPORTING io_node TYPE REF TO zcl_uitb_ctm_node OPTIONAL if_update_selection TYPE abap_bool DEFAULT abap_true. ""!

Start entity behind favorite with default variant

METHODS start_with_default_variant . ""!

Updates the menulevel of the child nodes of a node

METHODS update_menulevel_of_children IMPORTING !iv_node_key TYPE tm_nodekey . ""!

Updates the sort order of the child nodes of a node

METHODS update_sortorder_of_children IMPORTING iv_node_key TYPE tm_nodekey . ""!

Import favorites from Clipboard

""! ""!

Import favorites from Clipboard

METHODS import_from_clipboard IMPORTING iv_node_key TYPE tm_nodekey OPTIONAL. METHODS show_in_object_list IMPORTING iv_node_key TYPE tm_nodekey. ENDCLASS. CLASS zcl_dbbr_favorites_tree IMPLEMENTATION. METHOD build_tree. mf_global_fav_mode = if_global. DATA(lo_nodes) = mo_tree_model->get_nodes( ). lo_nodes->delete_all_nodes( ). DATA(lv_node_text) = COND string( WHEN if_global = abap_true THEN 'Favorites (Global)' ELSE |Favorites for { sy-uname }| ). *.. create dummy favmenu entry data for top node DATA(lr_favmenu_data) = NEW zdbbr_favmenu( uname = COND #( WHEN mf_global_fav_mode = abap_false THEN sy-uname ) favtype = zif_dbbr_c_favmenu_type=>folder object_id = 1 menu_level = 0 ). DATA(lo_root_dnd_behavior) = NEW cl_dragdrop( ). lo_root_dnd_behavior->add( flavor = 'Node' dragsrc = abap_false droptarget = abap_true effect = cl_dragdrop=>move ). lo_root_dnd_behavior->get_handle( IMPORTING handle = DATA(lv_dnd_handle) ). *.. create top node for fields lo_nodes->add_node( iv_node_key = c_top_node if_folder = abap_true ir_user_data = lr_favmenu_data iv_drag_drop_id = lv_dnd_handle it_item_table = VALUE #( ( item_name = zcl_uitb_column_tree_model=>c_hierarchy_column class = cl_list_tree_model=>item_class_text font = cl_list_tree_model=>item_font_prop text = lv_node_text ) ) ). CLEAR mt_node_map. *.. fill tree with saved nodes load_favorite_nodes( ). lo_nodes->expand_node( c_top_node ). mo_tree_model->get_selections( )->select_nodes( VALUE #( ( c_top_node ) ) ). focus( ). ENDMETHOD. METHOD collapse_node. DATA(lt_selected_node) = mo_tree_model->get_selections( )->get_selected_nodes( ). CHECK: lt_selected_node IS NOT INITIAL, lines( lt_selected_node ) = 1. DATA(lo_selected_node) = lt_selected_node[ 1 ]. IF lo_selected_node IS INITIAL OR NOT lo_selected_node->is_folder( ). RETURN. ENDIF. "" expand the node mo_tree_model->get_nodes( )->collapse_node( iv_node_key = lo_selected_node->mv_node_key if_collapse_subtree = if_collapse_all ). ENDMETHOD. METHOD constructor. mo_parent_view = io_parent_view. mo_favmenu_f = NEW zcl_dbbr_favmenu_factory( ). mo_query_f = NEW #( ). mo_parent_container = io_parent. SET HANDLER: on_entity_deleted. ENDMETHOD. METHOD create_multiple_faventries. DATA: lt_favmenu_new TYPE zdbbr_favmenu_itab. mo_tree_dnd_behaviour->get_handle( IMPORTING handle = DATA(lv_dnd_handle) ). DATA(lv_user) = COND #( WHEN mf_global_fav_mode = abap_false THEN sy-uname ). DATA(lv_relationship) = iv_parent_relationship. DATA(lv_relative_key) = io_selected_node->mv_node_key. DATA(lv_new_fav_id) = mo_favmenu_f->get_next_object_id( if_global = mf_global_fav_mode ). DATA(lv_parent_id) = is_parent_favmenu-object_id. DATA(lv_menu_level) = is_parent_favmenu-menu_level + 1. LOOP AT it_favinfo ASSIGNING FIELD-SYMBOL(). DATA(lr_favmenu_entry) = NEW zdbbr_favmenu( uname = lv_user favtype = -type fav_entry = -favorite fav_entry_raw = -favorite_raw parent_id = is_parent_favmenu-object_id object_id = lv_new_fav_id menu_level = lv_menu_level text = -description ). lt_favmenu_new = VALUE #( BASE lt_favmenu_new ( lr_favmenu_entry->* ) ). *.... add node to node table DATA(lv_node_id) = |{ lv_new_fav_id ALPHA = IN }|. IF rv_first_new_node IS INITIAL. rv_first_new_node = lv_node_id. ENDIF. DATA(lv_node_image) = COND #( WHEN -type = zif_dbbr_c_favmenu_type=>cds_view THEN zif_dbbr_c_icon=>cds_view WHEN -type = zif_dbbr_c_favmenu_type=>table THEN zif_dbbr_c_icon=>database_table WHEN -type = zif_dbbr_c_favmenu_type=>query THEN zif_dbbr_c_icon=>query ). mo_tree_model->get_nodes( )->add_node( iv_node_key = lv_node_id iv_relative_node_key = lv_relative_key iv_relationship = lv_relationship iv_drag_drop_id = lv_dnd_handle iv_image = lv_node_image iv_expanded_image = lv_node_image ir_user_data = lr_favmenu_entry it_item_table = VALUE #( ( item_name = mo_tree_model->c_hierarchy_column class = cl_item_tree_model=>item_class_text font = cl_item_tree_model=>item_font_prop text = lr_favmenu_entry->fav_entry_raw ) ( item_name = c_hierarchy_node2 style = zif_uitb_c_ctm_style=>inverted_gray font = cl_item_tree_model=>item_font_prop class = cl_item_tree_model=>item_class_text text = lr_favmenu_entry->text ) ) ). *.... fill new id values lv_relationship = cl_list_tree_model=>relat_next_sibling. lv_relative_key = lv_new_fav_id. lv_parent_id = lv_new_fav_id. lv_new_fav_id = lv_new_fav_id + 1. ENDLOOP. mo_favmenu_f->update_favorites( lt_favmenu_new ). ENDMETHOD. METHOD create_new_favorite. DATA: lv_node_description TYPE ddtext, lv_favorite_name TYPE tabname, lv_favorite_name_raw TYPE zsat_entity_id_raw, lv_favorite_type TYPE zsat_favmenu_type. DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). IF lo_selected_node IS INITIAL OR is_variant_node( lo_selected_node ). RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_selected_node ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. IF iv_favorite IS NOT INITIAL. lv_node_description = iv_description. lv_favorite_name = iv_favorite. lv_favorite_name_raw = iv_favorite_raw. lv_favorite_type = iv_fav_type. ELSE. DATA(lo_choose_tab_query_ctrl) = NEW zcl_dbbr_choose_object_ctrl( if_global_fav_mode = mf_global_fav_mode if_for_fav_menu = abap_true ). lo_choose_tab_query_ctrl->zif_uitb_screen_controller~call_screen( ). IF NOT lo_choose_tab_query_ctrl->zif_uitb_screen_controller~was_not_cancelled( ). RETURN. ENDIF. lo_choose_tab_query_ctrl->get_chosen_entry( IMPORTING ev_entry = lv_favorite_name ev_type = lv_favorite_type ). ENDIF. """""" determine new relationship information for new favorite IF lo_selected_node->is_folder( ). DATA(lv_relationship) = cl_list_tree_model=>relat_first_child. DATA(lo_parent_favnode) = lo_selected_node. ELSE. lv_relationship = cl_list_tree_model=>relat_next_sibling. lo_parent_favnode = lo_selected_node->get_parent( ). ENDIF. DATA(ls_parent_favnode_data) = get_node_favmenu_data( lo_parent_favnode ). """""" 1) get description for new node IF lv_node_description IS INITIAL OR iv_favorite_raw IS INITIAL. CASE lv_favorite_type. WHEN zif_dbbr_c_favmenu_type=>table OR zif_dbbr_c_favmenu_type=>view. lv_node_description = zcl_sat_ddic_repo_access=>get_table_info( lv_favorite_name )-ddtext. lv_favorite_name_raw = lv_favorite_name. WHEN zif_dbbr_c_favmenu_type=>cds_view. DATA(ls_cds_header) = zcl_sat_cds_view_factory=>read_cds_view_header( lv_favorite_name ). lv_node_description = ls_cds_header-description. lv_favorite_name_raw = ls_cds_header-entityname_raw. WHEN zif_dbbr_c_favmenu_type=>query. DATA(lo_query_f) = NEW zcl_dbbr_query_factory( ). DATA(ls_query) = lo_query_f->get_query( iv_query_name = lv_favorite_name ). lv_node_description = ls_query-description. lv_favorite_name_raw = lv_favorite_name. ENDCASE. ENDIF. "" get the current new max object id for the new favorite entry DATA(lv_new_fav_id) = mo_favmenu_f->get_next_object_id( if_global = mf_global_fav_mode ). DATA(lr_favmenu_entry_new) = NEW zdbbr_favmenu( uname = COND sy-uname( WHEN mf_global_fav_mode = abap_false THEN sy-uname ) favtype = lv_favorite_type fav_entry = lv_favorite_name fav_entry_raw = lv_favorite_name_raw object_id = lv_new_fav_id parent_id = ls_parent_favnode_data-object_id menu_level = ls_parent_favnode_data-menu_level + 1 text = lv_node_description ). mo_favmenu_f->update_favorite( lr_favmenu_entry_new->* ). DATA(lv_new_node_key) = |{ lv_new_fav_id ALPHA = IN }|. "" 3) add node as next child mo_tree_dnd_behaviour->get_handle( IMPORTING handle = DATA(lv_dnd_handle) ). mo_tree_model->get_nodes( )->add_node( iv_node_key = lv_new_node_key iv_relative_node_key = lo_selected_node->mv_node_key iv_relationship = lv_relationship if_folder = abap_false iv_image = zcl_dbbr_tree_helper=>get_tree_node_icon( lv_favorite_type ) iv_drag_drop_id = lv_dnd_handle ir_user_data = lr_favmenu_entry_new it_item_table = VALUE #( ( item_name = mo_tree_model->c_hierarchy_column class = cl_item_tree_model=>item_class_text font = cl_item_tree_model=>item_font_prop text = lv_favorite_name_raw ) ( item_name = c_hierarchy_node2 style = zif_uitb_c_ctm_style=>inverted_gray font = cl_item_tree_model=>item_font_prop class = cl_item_tree_model=>item_class_text text = lv_node_description ) ) "" Items des Knotens ). mt_node_map = VALUE #( BASE mt_node_map ( node_key = lv_new_node_key entity_id = lr_favmenu_entry_new->fav_entry entity_type = lr_favmenu_entry_new->favtype ) ). "" expand select the newly created folder mo_tree_model->get_selections( )->select_nodes( VALUE #( ( lv_new_node_key ) ) ). "" update sort order of all childs update_sortorder_of_children( lo_parent_favnode->mv_node_key ). focus( ). ENDMETHOD. METHOD create_new_fav_folder. DATA: lv_rcode(1), lt_fields TYPE TABLE OF sval. DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). IF lo_selected_node IS INITIAL OR is_variant_node( lo_selected_node ). RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_selected_node ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. DATA(lv_folder_name) = zcl_uitb_pgv_factory=>create_single_field_popup( iv_title = 'Enter name of folder' is_field = VALUE #( tabname = 'dd03t' fieldname = 'ddtext' fieldtext = 'Folder name' field_obl = abap_true ) )->show( )->get_first_field_value( ). IF lv_folder_name IS INITIAL. RETURN. ENDIF. """""" determine new relationship information for new favorite IF lo_selected_node->is_folder( ). DATA(lv_relationship) = cl_list_tree_model=>relat_first_child. DATA(lo_parent_favnode) = lo_selected_node. ELSE. lv_relationship = cl_list_tree_model=>relat_next_sibling. lo_parent_favnode = lo_selected_node->get_parent( ). ENDIF. DATA(ls_parent_favnode_data) = get_node_favmenu_data( lo_parent_favnode ). "" 2) create new fav entry for folder "" get the current new max object id for the new favorite entry DATA(lv_new_fav_id) = mo_favmenu_f->get_next_object_id( if_global = mf_global_fav_mode ). DATA(lr_favmenu_entry_new) = NEW zdbbr_favmenu( uname = COND sy-uname( WHEN mf_global_fav_mode = abap_false THEN sy-uname ) favtype = zif_dbbr_c_favmenu_type=>folder object_id = lv_new_fav_id parent_id = ls_parent_favnode_data-object_id menu_level = ls_parent_favnode_data-menu_level + 1 text = lv_folder_name ). mo_favmenu_f->update_favorite( lr_favmenu_entry_new->* ). DATA(lv_new_node_key) = |{ lv_new_fav_id ALPHA = IN }|. "" 3) add node as next child mo_tree_dnd_behaviour->get_handle( IMPORTING handle = DATA(lv_dnd_handle) ). mo_tree_model->get_nodes( )->add_node( iv_node_key = lv_new_node_key iv_relative_node_key = lo_selected_node->mv_node_key iv_relationship = lv_relationship if_folder = abap_true iv_drag_drop_id = lv_dnd_handle ir_user_data = lr_favmenu_entry_new it_item_table = VALUE #( ( item_name = mo_tree_model->c_hierarchy_column class = cl_item_tree_model=>item_class_text font = cl_item_tree_model=>item_font_prop text = lv_folder_name ) ) ). *.. create new node map entry mt_node_map = VALUE #( BASE mt_node_map ( node_key = lv_new_node_key entity_id = lr_favmenu_entry_new->fav_entry entity_type = lr_favmenu_entry_new->favtype ) ). "" expand select the newly created folder mo_tree_model->get_selections( )->select_nodes( VALUE #( ( lv_new_node_key ) ) ). update_sortorder_of_children( lo_parent_favnode->mv_node_key ). focus( ). ENDMETHOD. METHOD create_tree. *&---------------------------------------------------------------------* *& Description: Creates the favorite tree *&---------------------------------------------------------------------* DATA: lt_events TYPE cntl_simple_events. CHECK mo_tree_model IS INITIAL. mo_tree_model = NEW zcl_uitb_column_tree_model( ir_parent = mo_parent_container is_hierarchy_header = VALUE #( heading = 'Object Name' ) if_with_toolbar = abap_true iv_selection_mode = get_selection_mode( ) ). mo_tree_model->get_columns( )->add_hierarchy_column( c_hierarchy_node2 ). *.. create drag-n-drop behaviour object mo_tree_dnd_behaviour = NEW #( ). mo_tree_dnd_behaviour->add( flavor = 'Node' dragsrc = abap_true droptarget = abap_true effect = cl_dragdrop=>move ). fill_toolbar( ). mo_tree_model->create_tree_control( ). DATA(lo_events) = mo_tree_model->get_events( ). lo_events->add_key_for_keypress( cl_tree_model=>key_delete ). lo_events->add_key_for_keypress( cl_tree_model=>key_insert ). *.. set event handler methods to tree control SET HANDLER: on_tree_drag FOR lo_events, on_tree_drag_multiple FOR lo_events, on_tree_drop_complete_multiple FOR lo_events, on_tree_drop FOR lo_events, on_drop_complete FOR lo_events, on_node_context_menu_request FOR lo_events, on_node_context_menu_select FOR lo_events, on_node_double_click FOR lo_events, on_node_enter_key FOR lo_events, on_expand_no_children FOR lo_events. ENDMETHOD. METHOD delete_favorite. DATA: lv_answer TYPE char1, lo_selected_node TYPE REF TO zcl_uitb_ctm_node, lv_new_node_after_deletion TYPE tm_nodekey. IF io_node IS BOUND. lo_selected_node = io_node. ELSE. DATA(lt_selected_nodes) = mo_tree_model->get_selections( )->get_selected_nodes( ). IF lines( lt_selected_nodes ) > 1. delete_selected_nodes( ). RETURN. ELSEIF lines( lt_selected_nodes ) = 1. lo_selected_node = lt_selected_nodes[ 1 ]. ENDIF. ENDIF. IF lo_selected_node IS INITIAL OR lo_selected_node->mv_node_key = c_top_node OR is_variant_node( lo_selected_node ). RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_selected_node ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. IF lo_selected_node->has_children( ). *.... Only show query for folder deletion if it really is a folder DATA(lr_user_data) = lo_selected_node->get_user_data( ). TRY. DATA(lr_fav_data) = CAST zdbbr_favmenu( lr_user_data ). IF lr_fav_data->favtype = zif_dbbr_c_favmenu_type=>folder. IF zcl_dbbr_appl_util=>popup_to_confirm( iv_title = 'Delete favorite folder' iv_query = 'Should the folder and all its child nodes really be deleted?' iv_icon_type = 'ICON_QUESTION' ) <> '1'. RETURN. ENDIF. ENDIF. CATCH cx_sy_move_cast_error. ENDTRY. ENDIF. *.. 1) delete favorites from ZDBBR_favmenu delete_favorite_node( lo_selected_node ). *.. 2) determine new selection node DATA(lo_previous_node) = lo_selected_node->get_previous_sibling( ). IF lo_previous_node IS NOT INITIAL. lv_new_node_after_deletion = lo_previous_node->mv_node_key. ELSE. *.... get the parent node lv_new_node_after_deletion = lo_selected_node->get_parent( )->mv_node_key. ENDIF. *.. 3) delete the node and all subnodes mo_tree_model->get_nodes( )->delete_node( lo_selected_node->mv_node_key ). IF if_update_selection = abap_true. *.... 4) select new node mo_tree_model->get_selections( )->select_nodes( VALUE #( ( lv_new_node_after_deletion ) ) ). ENDIF. ENDMETHOD. METHOD delete_favorite_node. *.. 1) delete all sub nodes (recursively first IF io_selected_node->has_children( ). LOOP AT io_selected_node->get_children( ) ASSIGNING FIELD-SYMBOL(). delete_favorite_node( ). ENDLOOP. ENDIF. *.. delete entry from node map DELETE mt_node_map WHERE node_key = io_selected_node->mv_node_key. *.. 2) delete the node itself mo_favmenu_f->delete_favorite( get_node_favmenu_data( io_selected_node ) ). ENDMETHOD. METHOD delete_selected_nodes. DATA(lt_nodes) = mo_tree_model->get_selections( )->get_selected_nodes( ). DATA(lv_node_count) = lines( lt_nodes ). LOOP AT lt_nodes ASSIGNING FIELD-SYMBOL(). delete_favorite( io_node = if_update_selection = xsdbool( sy-tabix = lv_node_count ) ). ENDLOOP. MESSAGE |{ lv_node_count } Favorites have been deleted.| TYPE 'S'. ENDMETHOD. METHOD edit_favorite. DATA: lv_rcode(1). DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). IF lo_selected_node IS INITIAL OR lo_selected_node->mv_node_key = c_top_node. RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_selected_node ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. DATA(ls_favmenu_data) = get_node_favmenu_data( lo_selected_node ). DATA(lo_popup) = zcl_uitb_pgv_factory=>create_single_field_popup( iv_title = 'Edit Text' is_field = VALUE #( tabname = 'dd03t' fieldname = 'ddtext' fieldtext = 'Text' field_obl = abap_true value = ls_favmenu_data-text ) )->show( ). IF NOT lo_popup->cancelled( ). DATA(lv_new_favorite_text) = lo_popup->get_first_field_value( ). IF lv_new_favorite_text = ls_favmenu_data-text. RETURN. "" no changes needed ENDIF. ls_favmenu_data-text = lv_new_favorite_text. ELSE. RETURN. ENDIF. IF lo_selected_node->is_folder( ). lo_selected_node->get_item( mo_tree_model->c_hierarchy_column )->set_text( |{ lv_new_favorite_text }| ). ELSE. lo_selected_node->get_item( c_hierarchy_node2 )->set_text( |{ lv_new_favorite_text }| ). ENDIF. mo_favmenu_f->update_favorite( ls_favmenu_data ). lo_selected_node->set_user_data( NEW zdbbr_favmenu( ls_favmenu_data ) ). mo_tree_model->zif_uitb_gui_control~focus( ). ENDMETHOD. METHOD expand_node. DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). IF lo_selected_node IS INITIAL OR NOT lo_selected_node->is_folder( ). RETURN. ENDIF. *.. expand the node mo_tree_model->get_nodes( )->expand_node( iv_node_key = lo_selected_node->mv_node_key if_expand_subtree = if_expand_all ). ENDMETHOD. METHOD favorite_exists_in_node. IF io_node->mv_node_key = c_top_node. rf_fav_exists = abap_true. RETURN. ENDIF. rf_fav_exists = mo_favmenu_f->favorite_exists( get_node_favmenu_data( io_node ) ). ENDMETHOD. METHOD fill_toolbar. DATA(lo_toolbar) = mo_tree_model->get_toolbar( ). DATA(lt_buttons) = VALUE ttb_button( ( function = c_context_codes-personal_favorites icon = icon_system_user_menu quickinfo = 'Show User Favorites' butn_type = cntb_btype_button text = space ) ( function = c_context_codes-global_favorites icon = icon_system_sap_menu quickinfo = 'Show global Favorites' butn_type = cntb_btype_button text = space ) ( butn_type = cntb_btype_sep ) ( function = c_context_codes-expand_node_all icon = icon_expand_all butn_type = cntb_btype_button quickinfo = 'Expand node completely' ) ( function = c_context_codes-collapse_node_all icon = icon_collapse_all butn_type = cntb_btype_button quickinfo = 'Collapse node completely' ) ( butn_type = cntb_btype_sep ) ( function = c_context_codes-search icon = icon_search butn_type = cntb_btype_button quickinfo = 'Find' ) ( function = c_context_codes-search_more icon = icon_search_next butn_type = cntb_btype_button quickinfo = 'Find next' ) ( butn_type = cntb_btype_sep ) ( function = c_context_codes-insert_folder icon = icon_open_folder quickinfo = 'Insert new Folder' butn_type = cntb_btype_button ) ( function = c_context_codes-insert_favorite icon = icon_insert_favorites quickinfo = 'Insert Table/query' butn_type = cntb_btype_button ) ( function = c_context_codes-delete_favorite icon = icon_delete_favorites quickinfo = 'Delete Favorite' butn_type = cntb_btype_button ) ( butn_type = cntb_btype_sep ) ( function = c_context_codes-move_up icon = icon_next_value quickinfo = 'Move up' butn_type = cntb_btype_button ) ( function = c_context_codes-move_down icon = icon_previous_value quickinfo = 'Move down' butn_type = cntb_btype_button ) ). lo_toolbar->add_buttons( lt_buttons ). *.. register event handler SET HANDLER on_toolbar_button FOR lo_toolbar. ENDMETHOD. METHOD zif_uitb_gui_control~free. *... clear all nodes IF mo_tree_model IS BOUND. mo_tree_model->get_nodes( )->delete_all_nodes( ). ENDIF. CLEAR mt_node_map. ENDMETHOD. METHOD get_node_favmenu_data. DATA(lr_user_data) = io_node->get_user_data( ). CHECK lr_user_data IS BOUND. TRY. rs_favmenu = CAST zdbbr_favmenu( lr_user_data )->*. CATCH cx_sy_move_cast_error. ENDTRY. ENDMETHOD. METHOD get_selected_favorite. rr_node = mo_tree_model->get_selections( )->get_selected_node( ). ENDMETHOD. METHOD get_selection_mode. result = cl_tree_model=>node_sel_mode_multiple. ENDMETHOD. METHOD handle_gui_function. CASE iv_code. WHEN c_context_codes-search. zif_uitb_content_searcher~search( ). WHEN c_context_codes-search_more. zif_uitb_content_searcher~search_next( ). WHEN c_context_codes-personal_favorites. build_tree( abap_false ). WHEN c_context_codes-global_favorites. build_tree( abap_true ). WHEN c_context_codes-move_up. move_favorite_up( ). WHEN c_context_codes-move_down. move_favorite_down( ). WHEN c_context_codes-collapse_node. collapse_node( ). WHEN c_context_codes-collapse_node_all. collapse_node( abap_true ). WHEN c_context_codes-expand_node. expand_node( ). WHEN c_context_codes-expand_node_all. expand_node( abap_true ). WHEN c_context_codes-insert_folder. create_new_fav_folder( ). WHEN c_context_codes-edit_favorite. edit_favorite( ). WHEN c_context_codes-delete_favorite. delete_favorite( ). WHEN c_context_codes-insert_favorite. create_new_favorite( ). WHEN c_context_codes-insert_current. zcl_dbbr_selscr_nav_events=>raise_favtree_event( NEW zcl_dbbr_favmenu_evt_handler( me ) ). WHEN c_context_codes-import_from_clipboard. import_from_clipboard( ). WHEN c_context_codes-start_with_default_variant. start_with_default_variant( ). WHEN c_context_codes-show_in_object_browser. show_in_object_list( iv_node_key ). ENDCASE. ENDMETHOD. METHOD is_variant_node. CHECK io_node IS BOUND. DATA(lr_user_data) = io_node->get_user_data( ). CHECK lr_user_data IS BOUND. TRY. CAST ty_s_variant_data( lr_user_data ). rf_variant_node = abap_true. CATCH cx_sy_move_cast_error. ENDTRY. ENDMETHOD. METHOD import_from_clipboard. DATA: lv_clipboard_count TYPE sy-tabix. *.. 1) validate of import is possible on current node DATA(lo_node_for_import) = COND #( WHEN iv_node_key IS NOT INITIAL THEN mo_tree_model->get_nodes( )->get_node( iv_node_key ) ELSE mo_tree_model->get_selections( )->get_selected_node( ) ). IF lo_node_for_import IS INITIAL OR is_variant_node( lo_node_for_import ). RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_node_for_import ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. *.. Try to retrieve data from clipboard DATA(lt_entities) = zcl_dbbr_ddic_util=>get_entities_from_clipboard( IMPORTING ev_clipboard_count = lv_clipboard_count ). IF lt_entities IS INITIAL. MESSAGE s082(zdbbr_info). RETURN. ENDIF. *.. 6) evaluate current parent node *.. determine relationship information for new favorite IF lo_node_for_import->is_folder( ). DATA(lv_relationship) = cl_list_tree_model=>relat_first_child. DATA(lo_parent_favnode) = lo_node_for_import. ELSE. lv_relationship = cl_list_tree_model=>relat_next_sibling. lo_parent_favnode = lo_node_for_import->get_parent( ). ENDIF. DATA(ls_parent_favnode_data) = get_node_favmenu_data( lo_parent_favnode ). *.. 7) create node/favmenu entries for all db tables in package DATA(lv_first_new_node) = create_multiple_faventries( it_favinfo = VALUE #( FOR entity IN lt_entities ( favorite = entity-entity_id favorite_raw = entity-entity_id_raw type = entity-entity_type description = entity-description ) ) io_selected_node = lo_node_for_import is_parent_favmenu = ls_parent_favnode_data iv_parent_relationship = lv_relationship ). *.. expand select the newly created folder mo_tree_model->get_selections( )->select_nodes( VALUE #( ( lv_first_new_node ) ) ). *.. update sort order of all children update_sortorder_of_children( lo_parent_favnode->mv_node_key ). mo_tree_model->zif_uitb_gui_control~focus( ). MESSAGE s083(zdbbr_info) WITH |{ lines( lt_entities ) NUMBER = USER }| |{ lv_clipboard_count NUMBER = USER }|. ENDMETHOD. METHOD load_favorite_nodes. DATA: lt_items TYPE treemcitab, lv_icon TYPE tv_image. mo_tree_dnd_behaviour->get_handle( IMPORTING handle = DATA(lv_dnd_handle) ). mo_favmenu_f->get_favorites( EXPORTING if_global_favorites = mf_global_fav_mode IMPORTING et_favmenu_entries = DATA(lt_favmenu_entries) ). LOOP AT lt_favmenu_entries ASSIGNING FIELD-SYMBOL() GROUP BY ( menu_level = -menu_level ) ASCENDING ASSIGNING FIELD-SYMBOL(). DATA(lt_menu_entries) = VALUE zdbbr_favorite_menu_itab( FOR entry IN GROUP ( entry ) ). SORT lt_menu_entries BY sort_order ASCENDING. LOOP AT lt_menu_entries ASSIGNING FIELD-SYMBOL(). CHECK: -object_id IS NOT INITIAL, -parent_id IS NOT INITIAL. DATA(lf_is_folder) = should_display_as_folder( iv_fav_type = -favtype if_has_variants = -has_variants ). lv_icon = zcl_dbbr_tree_helper=>get_tree_node_icon( -favtype ). lt_items = VALUE #( ( item_name = zcl_uitb_column_tree_model=>c_hierarchy_column class = cl_item_tree_model=>item_class_text font = cl_item_tree_model=>item_font_prop text = COND #( WHEN -favtype = zif_dbbr_c_favmenu_type=>folder THEN -text ELSE -fav_entry_raw ) ) ). IF -favtype <> zif_dbbr_c_favmenu_type=>folder. lt_items = VALUE #( BASE lt_items ( item_name = c_hierarchy_node2 style = zif_uitb_c_ctm_style=>inverted_gray font = cl_item_tree_model=>item_font_prop class = cl_item_tree_model=>item_class_text text = -text ) ). ENDIF. mo_tree_model->get_nodes( )->add_node( iv_node_key = |{ -object_id }| iv_relative_node_key = |{ -parent_id }| iv_drag_drop_id = lv_dnd_handle if_folder = lf_is_folder if_expander = lf_is_folder iv_image = lv_icon iv_expanded_image = lv_icon "" add reference of favorite to node ir_user_data = NEW zdbbr_favmenu( ) it_item_table = lt_items ). ENDLOOP. ENDLOOP. ENDMETHOD. METHOD move_favorite_down. DATA: lv_relatkey TYPE tm_nodekey, lv_relationship TYPE i. *.. 1) get the selected node DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). IF lo_selected_node IS INITIAL OR lo_selected_node->mv_node_key = c_top_node OR is_variant_node( lo_selected_node ). RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_selected_node ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. DATA(lo_next_sibling) = lo_selected_node->get_next_sibling( ). IF lo_next_sibling IS INITIAL. RETURN. ENDIF. lv_relationship = cl_list_tree_model=>relat_next_sibling. lv_relatkey = lo_next_sibling->mv_node_key. lo_selected_node->move_node_to( iv_relative_node = lv_relatkey iv_relationship = lv_relationship ). *.. update sort order of sub nodes of parent update_sortorder_of_children( lo_selected_node->get_parent( )->mv_node_key ). mo_tree_model->get_selections( )->select_nodes( VALUE #( ( lo_selected_node->mv_node_key ) ) ). ENDMETHOD. METHOD move_favorite_up. *.. 1) get the selected node DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). IF lo_selected_node IS INITIAL OR lo_selected_node->mv_node_key = c_top_node OR is_variant_node( lo_selected_node ). RETURN. ENDIF. IF NOT favorite_exists_in_node( lo_selected_node ). build_tree( mf_global_fav_mode ). MESSAGE TEXT-001 TYPE 'S'. RETURN. ENDIF. DATA(lo_previous_sibling) = lo_selected_node->get_previous_sibling( ). IF lo_previous_sibling IS INITIAL. RETURN. ENDIF. lo_selected_node->move_node_to( iv_relationship = cl_tree_model=>relat_prev_sibling iv_relative_node = lo_previous_sibling->mv_node_key ). *.. update sort order of sub nodes of parent update_sortorder_of_children( lo_selected_node->get_parent( )->mv_node_key ). mo_tree_model->get_selections( )->select_nodes( VALUE #( ( lo_selected_node->mv_node_key ) ) ). ENDMETHOD. METHOD on_drop_complete. IF er_drag_drop_object->state = cl_dragdropobject=>state_aborted. build_tree( mf_global_fav_mode ). ENDIF. ENDMETHOD. METHOD on_entity_deleted. DATA: lt_nodes TYPE treemnotab. LOOP AT mt_node_map ASSIGNING FIELD-SYMBOL() WHERE entity_id = ev_entity_id AND entity_type = ev_entity_type. lt_nodes = VALUE #( BASE lt_nodes ( -node_key ) ). ENDLOOP. CHECK lt_nodes IS NOT INITIAL. mo_tree_model->get_nodes( )->delete_nodes( lt_nodes ). ENDMETHOD. METHOD on_expand_no_children. DATA(lo_node) = mo_tree_model->get_nodes( )->get_node( ev_node_key ). DATA(lr_user_data) = lo_node->get_user_data( ). DATA(ls_favmenu_data) = CAST zdbbr_favmenu( lr_user_data )->*. DATA(lt_variants) = zcl_dbbr_variant_factory=>find_variant_infos_for_type( iv_entity_id = ls_favmenu_data-fav_entry iv_entity_type = ls_favmenu_data-favtype ). LOOP AT lt_variants ASSIGNING FIELD-SYMBOL(). -entity_type = ls_favmenu_data-favtype. IF -description IS NOT INITIAL. DATA(lt_items_for_description) = VALUE treemcitab( ( item_name = c_hierarchy_node2 style = zif_uitb_c_ctm_style=>inverted_gray font = cl_item_tree_model=>item_font_prop class = cl_item_tree_model=>item_class_text text = -description ) ). ENDIF. mo_tree_model->get_nodes( )->add_node( iv_node_key = mv_last_var_node_key iv_relative_node_key = ev_node_key iv_relationship = cl_list_tree_model=>relat_last_child iv_image = CONV #( icon_alv_variants ) ir_user_data = NEW ty_s_variant_data( variant_id = -variant_id entity_id = ls_favmenu_data-fav_entry entity_type = ls_favmenu_data-favtype ) it_item_table = VALUE #( ( item_name = mo_tree_model->c_hierarchy_column class = cl_item_tree_model=>item_class_text font = cl_item_tree_model=>item_font_prop text = -variant_name ) ( LINES OF lt_items_for_description ) ) ). CLEAR lt_items_for_description. ADD 1 TO mv_last_var_node_key. ENDLOOP. mo_tree_model->get_nodes( )->expand_node( ev_node_key ). ENDMETHOD. METHOD on_node_context_menu_request. DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). CHECK NOT is_variant_node( lo_selected_node ). DATA(lo_parent_node) = lo_selected_node->get_parent( ). DATA(lv_parent_node) = COND #( WHEN lo_parent_node IS BOUND THEN lo_parent_node->mv_node_key ). DATA(lt_expanded_nodes) = mo_tree_model->get_nodes( )->get_expanded_nodes( ). IF lo_selected_node->is_folder( ). IF line_exists( lt_expanded_nodes[ table_line = ev_node_key ] ). er_menu->add_function( fcode = c_context_codes-collapse_node text = |{ 'Collapse folder'(002) }| ). ELSE. er_menu->add_function( fcode = c_context_codes-expand_node text = |{ 'Expand folder'(003) }| ). ENDIF. er_menu->add_separator( ). ENDIF. er_menu->add_function( fcode = c_context_codes-insert_current text = |{ 'Insert Current Entity'(008) }| ). er_menu->add_separator( ). er_menu->add_function( fcode = c_context_codes-insert_folder text = |{ 'Insert Folder'(009) }| ). er_menu->add_function( fcode = c_context_codes-insert_favorite text = |{ 'Insert Favorite'(010) }| ). IF ev_node_key <> c_top_node. er_menu->add_function( fcode = c_context_codes-edit_favorite text = |{ 'Change Favorite'(011) }| ). er_menu->add_function( fcode = c_context_codes-delete_favorite text = |{ 'Delete Favorite'(012) }| ). ENDIF. er_menu->add_separator( ). *... create new action for importing db tables from package er_menu->add_function( fcode = c_context_codes-import_from_clipboard text = |{ 'Import from Clipboard'(013) }| ). IF NOT lo_selected_node->is_folder( ). er_menu->add_separator( ). *... Shows the given favorite in the Object browser er_menu->add_function( fcode = c_context_codes-show_in_object_browser text = |{ 'Show in Object Browser'(014) }| ). *... create new function for running the selected table/script and build_tree the results er_menu->add_function( fcode = c_context_codes-start_with_default_variant text = |{ 'Execute with Default Settings'(007) }| ). ENDIF. ENDMETHOD. METHOD on_node_context_menu_select. handle_gui_function( iv_code = ev_fcode iv_node_key = ev_node_key ). ENDMETHOD. METHOD on_node_double_click. DATA: lf_is_favorite TYPE abap_bool. *.. Get the selected node from the tree DATA(lo_selected_node) = mo_tree_model->get_selections( )->get_selected_node( ). DATA(lr_user_data) = lo_selected_node->get_user_data( ). IF lo_selected_node->is_folder( ). *.... Check whether the node is truly a folder or just a favorite with variants IF lr_user_data IS BOUND. DATA(lv_fav_type) = CAST zdbbr_favmenu( lr_user_data )->favtype. IF lv_fav_type <> zif_dbbr_c_favmenu_type=>folder. lf_is_favorite = abap_true. ENDIF. ENDIF. ELSE. lf_is_favorite = abap_true. ENDIF. IF lf_is_favorite = abap_true. IF is_variant_node( lo_selected_node ). DATA(ls_variant_info) = CAST ty_s_variant_data( lr_user_data )->*. zcl_dbbr_selscr_nav_events=>raise_variant_entry_chosen( iv_entity_id = ls_variant_info-entity_id iv_entity_type = ls_variant_info-entity_type iv_variant_id = ls_variant_info-variant_id ). ELSE. DATA(lr_fav_entry) = CAST zdbbr_favmenu( lr_user_data ). zcl_dbbr_selscr_nav_events=>raise_entity_chosen( iv_entity_id = lr_fav_entry->fav_entry iv_entity_type = lr_fav_entry->favtype ). ENDIF. ELSE. *.... check if folder is expanded/collapsed IF lo_selected_node->is_expanded( ). collapse_node( ). ELSE. expand_node( ). ENDIF. ENDIF. ENDMETHOD. METHOD on_node_enter_key. IF ev_key = cl_list_tree_model=>key_enter. on_node_double_click( ev_node_key = ev_node_key ). ELSEIF ev_key = cl_list_tree_model=>key_delete. on_node_context_menu_select( ev_fcode = c_context_codes-delete_favorite ev_node_key = ev_node_key ). ELSEIF ev_key = cl_list_tree_model=>key_insert. import_from_clipboard( ). ENDIF. ENDMETHOD. METHOD on_toolbar_button. handle_gui_function( ev_fcode ). ENDMETHOD. METHOD on_tree_drag. *.. first check if the node to be dragged still exists IF NOT favorite_exists_in_node( mo_tree_model->get_nodes( )->get_node( ev_node_key ) ). er_drag_drop_object->abort( ). RETURN. ENDIF. *.. create drag and drop object er_drag_drop_object->object = NEW zcl_dbbr_tree_dnd_object( VALUE #( ( ev_node_key ) ) ). ENDMETHOD. METHOD on_tree_drag_multiple. *.. create drag and drop object er_drag_drop_object->object = NEW zcl_dbbr_tree_dnd_object( et_node_key_table ). ENDMETHOD. METHOD on_tree_drop. DATA: lv_relationship TYPE i, lv_menulevel TYPE zdbbr_favmenu-menu_level. DATA(lo_nodes) = mo_tree_model->get_nodes( ). DATA(lo_target_node) = lo_nodes->get_node( ev_node_key ). *.. does the target still exist IF NOT favorite_exists_in_node( lo_target_node ). er_drag_drop_object->abort( ). RETURN. ENDIF. DATA(ls_favmenu_target) = get_node_favmenu_data( lo_target_node ). IF lo_target_node->is_folder( ). lv_relationship = cl_tree_model=>relat_first_child. lv_menulevel = ls_favmenu_target-menu_level + 1. ELSE. lv_relationship = cl_tree_model=>relat_next_sibling. lv_menulevel = ls_favmenu_target-menu_level. *.... also read the parent of the target node DATA(lo_target_parent_node) = lo_nodes->get_node( lo_target_node->get_parent( )->mv_node_key ). DATA(ls_favmenu_target_parent) = get_node_favmenu_data( lo_target_parent_node ). ENDIF. *.. get drag and drop object TRY. DATA(lo_dnd_object) = CAST zcl_dbbr_tree_dnd_object( er_drag_drop_object->object ). DATA(lv_source_node) = lo_dnd_object->get_next_node( ). DATA(lo_source_node) = lo_nodes->get_node( lv_source_node ). lo_source_node->move_node_to( iv_relative_node = lo_target_node->mv_node_key iv_relationship = lv_relationship ). CATCH cx_sy_move_cast_error. er_drag_drop_object->abort( ). RETURN. ENDTRY. *.. drop was successful DATA(ls_favmenu_source) = get_node_favmenu_data( lo_source_node ). *...-> check which attributes of the favmenu entry need to be adjusted *.. 1) has the parent changed of the source IF NOT lo_target_node->is_folder( ) AND lo_source_node->get_parent( )->mv_node_key = lo_target_node->mv_node_key. *.... only sort order must be changed update_sortorder_of_children( lo_target_node->mv_node_key ). ELSE. *.... source gets new parent -> delete current favmenu entry and create new one mo_favmenu_f->delete_favorite( ls_favmenu_source ). ls_favmenu_source-parent_id = COND #( WHEN lo_target_node->is_folder( ) THEN ls_favmenu_target-object_id ELSE ls_favmenu_target_parent-object_id ). ls_favmenu_source-menu_level = lv_menulevel. mo_favmenu_f->update_favorite( ls_favmenu_source ). lo_source_node->set_user_data( NEW zdbbr_favmenu( ls_favmenu_source ) ). *.... update menu levels of node update_menulevel_of_children( lv_source_node ). *.... check which node's children need an updated sort order IF lo_target_node->is_folder( ). update_sortorder_of_children( lo_target_node->mv_node_key ). ELSE. update_sortorder_of_children( lo_target_parent_node->mv_node_key ). ENDIF. ENDIF. ENDMETHOD. METHOD on_tree_drop_complete_multiple. ENDMETHOD. METHOD should_display_as_folder. CLEAR result. IF iv_fav_type = zif_dbbr_c_favmenu_type=>folder OR if_has_variants = abap_true. result = abap_true. ENDIF. ENDMETHOD. METHOD show. create_tree( ). build_tree( if_global ). ENDMETHOD. METHOD show_in_object_list. DATA: lv_fav_id TYPE string. DATA(lo_node) = mo_tree_model->get_nodes( )->get_node( iv_node_key ). DATA(lr_user_data) = lo_node->get_user_data( ). CHECK lr_user_data IS NOT INITIAL. DATA(ls_favmenu_data) = CAST zdbbr_favmenu( lr_user_data )->*. IF mo_parent_view IS BOUND. mo_parent_view->execute_command( NEW zcl_uitb_gui_simple_command( iv_function = zcl_dbbr_object_navigator=>c_command_id-show_object_list ir_params = NEW zsat_entity( entity_id = ls_favmenu_data-fav_entry entity_type = ls_favmenu_data-favtype ) ) ). ENDIF. ENDMETHOD. METHOD start_with_default_variant. DATA: lv_fav_id TYPE string. DATA(lo_selected_node) = get_selected_favorite( ). CHECK lo_selected_node IS NOT INITIAL. DATA(lr_user_data) = lo_selected_node->get_user_data( ). CHECK lr_user_data IS NOT INITIAL. DATA(ls_favmenu_data) = CAST zdbbr_favmenu( lr_user_data )->*. DATA(lf_query) = xsdbool( ls_favmenu_data-favtype = zif_dbbr_c_favmenu_type=>query ). lv_fav_id = ls_favmenu_data-fav_entry. zcl_dbbr_selscr_nav_events=>raise_variant_entry_chosen( iv_entity_id = CONV #( lv_fav_id ) iv_entity_type = ls_favmenu_data-favtype iv_variant_id = zif_dbbr_c_global=>c_dummy_variant if_go_to_result = abap_true ). ENDMETHOD. METHOD update_menulevel_of_children. DATA(lo_node) = mo_tree_model->get_nodes( )->get_node( iv_node_key ). CHECK lo_node->is_folder( ). *.. starting menulevel from node DATA(ls_favmenu_data) = get_node_favmenu_data( lo_node ). DATA(lv_menulevel) = ls_favmenu_data-menu_level + 1. LOOP AT lo_node->get_children( ) ASSIGNING FIELD-SYMBOL(). ls_favmenu_data = get_node_favmenu_data( ). ls_favmenu_data-menu_level = lv_menulevel. mo_favmenu_f->update_favorite( ls_favmenu_data ). ->set_user_data( NEW zdbbr_favmenu( ls_favmenu_data ) ). *.... also update child nodes IF ->is_folder( ). update_menulevel_of_children( ->mv_node_key ). ENDIF. ENDLOOP. ENDMETHOD. METHOD update_sortorder_of_children. DATA(lo_node) = mo_tree_model->get_nodes( )->get_node( iv_node_key = iv_node_key ). DATA(lv_sortorder) = 10. DATA(lo_favmenu_f) = NEW zcl_dbbr_favmenu_factory( ). LOOP AT lo_node->get_children( ) ASSIGNING FIELD-SYMBOL(). DATA(ls_favmenu_data) = get_node_favmenu_data( ). ls_favmenu_data-sort_order = lv_sortorder. lo_favmenu_f->update_favorite( ls_favmenu_data ). ->set_user_data( NEW zdbbr_favmenu( ls_favmenu_data ) ). ADD 10 TO lv_sortorder. ENDLOOP. ENDMETHOD. METHOD zif_uitb_content_searcher~search. DATA(ls_find_result) = mo_tree_model->get_search( )->find( ). IF ls_find_result IS NOT INITIAL. mo_tree_model->get_selections( )->select_nodes( VALUE #( ( ls_find_result-node_key ) ) ). ENDIF. ENDMETHOD. METHOD zif_uitb_content_searcher~search_next. DATA(ls_find_result) = mo_tree_model->get_search( )->find_next( ). IF ls_find_result IS NOT INITIAL. mo_tree_model->get_selections( )->select_nodes( VALUE #( ( ls_find_result-node_key ) ) ). ENDIF. ENDMETHOD. METHOD zif_uitb_gui_control~focus. mo_tree_model->zif_uitb_gui_control~focus( ). ENDMETHOD. METHOD zif_uitb_gui_control~has_focus. rf_has_focus = mo_tree_model->zif_uitb_gui_control~has_focus( ). ENDMETHOD. ENDCLASS. ",15128,True,3076.189958185888,median "CLASS zcl_abapgit_gui_page_view_repo DEFINITION PUBLIC FINAL INHERITING FROM zcl_abapgit_gui_page CREATE PUBLIC. PUBLIC SECTION. CONSTANTS: BEGIN OF c_actions, repo_list TYPE string VALUE 'abapgit_home' ##NO_TEXT, change_dir TYPE string VALUE 'change_dir' ##NO_TEXT, toggle_hide_files TYPE string VALUE 'toggle_hide_files' ##NO_TEXT, toggle_folders TYPE string VALUE 'toggle_folders' ##NO_TEXT, toggle_changes TYPE string VALUE 'toggle_changes' ##NO_TEXT, toggle_diff_first TYPE string VALUE 'toggle_diff_first ' ##NO_TEXT, display_more TYPE string VALUE 'display_more' ##NO_TEXT, repo_switch_origin_to_pr TYPE string VALUE 'repo_switch_origin_to_pr', repo_reset_origin TYPE string VALUE 'repo_reset_origin', END OF c_actions. INTERFACES: zif_abapgit_gui_hotkeys. METHODS constructor IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception . METHODS zif_abapgit_gui_event_handler~on_event REDEFINITION. PROTECTED SECTION. METHODS render_content REDEFINITION. PRIVATE SECTION. DATA mo_repo TYPE REF TO zcl_abapgit_repo . DATA mv_cur_dir TYPE string . DATA mv_hide_files TYPE abap_bool . DATA mv_max_lines TYPE i . DATA mv_max_setting TYPE i . DATA mv_show_folders TYPE abap_bool . DATA mv_changes_only TYPE abap_bool . DATA mv_order_by TYPE string . DATA mv_order_descending TYPE abap_bool . DATA mv_diff_first TYPE abap_bool . DATA mv_key TYPE zif_abapgit_persistence=>ty_value . DATA mv_are_changes_recorded_in_tr TYPE abap_bool . METHODS render_head_line IMPORTING !iv_lstate TYPE char1 !iv_rstate TYPE char1 RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS build_head_menu IMPORTING !iv_lstate TYPE char1 !iv_rstate TYPE char1 RETURNING VALUE(ro_toolbar) TYPE REF TO zcl_abapgit_html_toolbar RAISING zcx_abapgit_exception . METHODS build_view_menu RETURNING VALUE(ro_toolbar) TYPE REF TO zcl_abapgit_html_toolbar RAISING zcx_abapgit_exception . METHODS render_item IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item !iv_render_transports TYPE abap_bool RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS render_item_files IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . METHODS render_item_command IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . METHODS get_item_class IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(rv_html) TYPE string . METHODS get_item_icon IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(rv_html) TYPE string . METHODS render_item_lock_column IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(rv_html) TYPE string . METHODS render_parent_dir RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS build_obj_jump_link IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(rv_html) TYPE string . METHODS build_dir_jump_link IMPORTING !iv_path TYPE string RETURNING VALUE(rv_html) TYPE string . METHODS build_inactive_object_code IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_repo_item RETURNING VALUE(rv_inactive_html_code) TYPE string . METHODS open_in_master_language RAISING zcx_abapgit_exception . METHODS render_order_by RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . METHODS apply_order_by CHANGING !ct_repo_items TYPE zif_abapgit_definitions=>tt_repo_items . METHODS build_branch_dropdown IMPORTING !iv_wp_opt LIKE zif_abapgit_html=>c_html_opt-crossout RETURNING VALUE(ro_branch_dropdown) TYPE REF TO zcl_abapgit_html_toolbar RAISING zcx_abapgit_exception . METHODS build_tag_dropdown IMPORTING !iv_wp_opt LIKE zif_abapgit_html=>c_html_opt-crossout RETURNING VALUE(ro_tag_dropdown) TYPE REF TO zcl_abapgit_html_toolbar RAISING zcx_abapgit_exception . METHODS build_advanced_dropdown IMPORTING !iv_wp_opt LIKE zif_abapgit_html=>c_html_opt-crossout !iv_lstate TYPE char1 !iv_rstate TYPE char1 RETURNING VALUE(ro_advanced_dropdown) TYPE REF TO zcl_abapgit_html_toolbar RAISING zcx_abapgit_exception . METHODS build_main_toolbar IMPORTING !iv_pull_opt LIKE zif_abapgit_html=>c_html_opt-crossout !iv_lstate TYPE char1 !iv_rstate TYPE char1 !io_tb_branch TYPE REF TO zcl_abapgit_html_toolbar !io_tb_tag TYPE REF TO zcl_abapgit_html_toolbar !io_tb_advanced TYPE REF TO zcl_abapgit_html_toolbar RETURNING VALUE(ro_toolbar) TYPE REF TO zcl_abapgit_html_toolbar RAISING zcx_abapgit_exception . METHODS switch_to_pr IMPORTING !it_fields TYPE tihttpnvp OPTIONAL !iv_revert TYPE abap_bool OPTIONAL RETURNING VALUE(rv_switched) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS build_main_menu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . METHODS render_scripts RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_GUI_PAGE_VIEW_REPO IMPLEMENTATION. METHOD apply_order_by. DATA: lt_sort TYPE abap_sortorder_tab, ls_sort LIKE LINE OF lt_sort, lt_non_code_and_metadata_items LIKE ct_repo_items, lt_code_items LIKE ct_repo_items, lt_diff_items LIKE ct_repo_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_repo_item. IF mv_order_by IS INITIAL. RETURN. ENDIF. "" we want to preserve non-code and metadata files at the top, "" so we isolate them and and sort only the code artifacts LOOP AT ct_repo_items ASSIGNING . IF -obj_type IS INITIAL AND -is_dir = abap_false. INSERT INTO TABLE lt_non_code_and_metadata_items. ELSE. INSERT INTO TABLE lt_code_items. ENDIF. ENDLOOP. IF mv_diff_first = abap_true. "" fix diffs on the top, right after non-code and metadata LOOP AT lt_code_items ASSIGNING WHERE changes > 0. INSERT INTO TABLE lt_diff_items. ENDLOOP. DELETE lt_code_items WHERE changes > 0. ENDIF. CLEAR: ct_repo_items. ls_sort-name = mv_order_by. ls_sort-descending = mv_order_descending. ls_sort-astext = abap_true. INSERT ls_sort INTO TABLE lt_sort. SORT lt_code_items BY (lt_sort). SORT lt_diff_items BY (lt_sort). INSERT LINES OF lt_non_code_and_metadata_items INTO TABLE ct_repo_items. INSERT LINES OF lt_diff_items INTO TABLE ct_repo_items. INSERT LINES OF lt_code_items INTO TABLE ct_repo_items. ENDMETHOD. METHOD build_advanced_dropdown. DATA: lv_crossout LIKE zif_abapgit_html=>c_html_opt-crossout. CREATE OBJECT ro_advanced_dropdown. IF iv_rstate IS NOT INITIAL OR iv_lstate IS NOT INITIAL. "" In case of asyncronicities ro_advanced_dropdown->add( iv_txt = 'Reset Local (Force Pull)' iv_act = |{ zif_abapgit_definitions=>c_action-git_reset }?key={ mv_key }| iv_opt = iv_wp_opt ). ENDIF. IF mo_repo->is_offline( ) = abap_false. "" Online ? ro_advanced_dropdown->add( iv_txt = 'Background Mode' iv_act = |{ zif_abapgit_definitions=>c_action-go_background }?key={ mv_key }| ). ro_advanced_dropdown->add( iv_txt = 'Change Remote' iv_act = |{ zif_abapgit_definitions=>c_action-repo_remote_change }?key={ mv_key }| ). ro_advanced_dropdown->add( iv_txt = 'Make Off-line' iv_act = |{ zif_abapgit_definitions=>c_action-repo_remote_detach }?key={ mv_key }| ). ro_advanced_dropdown->add( iv_txt = 'Force Stage' iv_act = |{ zif_abapgit_definitions=>c_action-go_stage }?key={ mv_key }| ). CLEAR lv_crossout. IF zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-transport_to_branch ) = abap_false. lv_crossout = zif_abapgit_html=>c_html_opt-crossout. ENDIF. ro_advanced_dropdown->add( iv_txt = 'Transport to Branch' iv_act = |{ zif_abapgit_definitions=>c_action-repo_transport_to_branch }?key={ mv_key }| iv_opt = lv_crossout ). ELSE. ro_advanced_dropdown->add( iv_txt = 'Make On-line' iv_act = |{ zif_abapgit_definitions=>c_action-repo_remote_attach }?key={ mv_key }| ). ENDIF. IF mv_are_changes_recorded_in_tr = abap_true. ro_advanced_dropdown->add( iv_txt = 'Add all objects to transport request' iv_act = |{ zif_abapgit_definitions=>c_action-repo_add_all_obj_to_trans_req }?key={ mv_key }| ). ENDIF. ro_advanced_dropdown->add( iv_txt = 'Syntax Check' iv_act = |{ zif_abapgit_definitions=>c_action-repo_syntax_check }?key={ mv_key }| ). ro_advanced_dropdown->add( iv_txt = 'Run Code Inspector' iv_act = |{ zif_abapgit_definitions=>c_action-repo_code_inspector }?key={ mv_key }| ). CLEAR lv_crossout. IF zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-update_local_checksum ) = abap_false. lv_crossout = zif_abapgit_html=>c_html_opt-crossout. ENDIF. ro_advanced_dropdown->add( iv_txt = 'Update Local Checksums' iv_act = |{ zif_abapgit_definitions=>c_action-repo_refresh_checksums }?key={ mv_key }| iv_opt = lv_crossout ). IF mo_repo->get_dot_abapgit( )->get_master_language( ) <> sy-langu. ro_advanced_dropdown->add( iv_txt = 'Open in Master Language' iv_act = |{ zif_abapgit_definitions=>c_action-repo_open_in_master_lang }?key={ mv_key }| ). ENDIF. ro_advanced_dropdown->add( iv_txt = 'Remove' iv_act = |{ zif_abapgit_definitions=>c_action-repo_remove }?key={ mv_key }| ). CLEAR lv_crossout. IF mo_repo->get_local_settings( )-write_protected = abap_true OR zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-uninstall ) = abap_false. lv_crossout = zif_abapgit_html=>c_html_opt-crossout. ENDIF. ro_advanced_dropdown->add( iv_txt = 'Uninstall' iv_act = |{ zif_abapgit_definitions=>c_action-repo_purge }?key={ mv_key }| iv_opt = lv_crossout ). ENDMETHOD. METHOD build_branch_dropdown. DATA lo_repo_online TYPE REF TO zcl_abapgit_repo_online. CREATE OBJECT ro_branch_dropdown. IF mo_repo->is_offline( ) = abap_true. RETURN. ENDIF. ro_branch_dropdown->add( iv_txt = 'Overview' iv_act = |{ zif_abapgit_definitions=>c_action-go_branch_overview }?key={ mv_key }| ). ro_branch_dropdown->add( iv_txt = 'Switch' iv_act = |{ zif_abapgit_definitions=>c_action-git_branch_switch }?key={ mv_key }| iv_opt = iv_wp_opt ). ro_branch_dropdown->add( iv_txt = 'Create' iv_act = |{ zif_abapgit_definitions=>c_action-git_branch_create }?key={ mv_key }| ). ro_branch_dropdown->add( iv_txt = 'Delete' iv_act = |{ zif_abapgit_definitions=>c_action-git_branch_delete }?key={ mv_key }| ). lo_repo_online ?= mo_repo. "" TODO refactor this disaster IF lo_repo_online->get_switched_origin( ) IS NOT INITIAL. ro_branch_dropdown->add( iv_txt = 'Switch Origin: Revert beta' iv_act = |{ c_actions-repo_reset_origin }| ). ELSE. ro_branch_dropdown->add( iv_txt = 'Switch Origin: to PR beta' iv_act = |{ c_actions-repo_switch_origin_to_pr }| ). ENDIF. ENDMETHOD. METHOD build_dir_jump_link. DATA lv_path TYPE string. DATA lv_encode TYPE string. DATA li_html TYPE REF TO zif_abapgit_html. CREATE OBJECT li_html TYPE zcl_abapgit_html. lv_path = iv_path. REPLACE FIRST OCCURRENCE OF mv_cur_dir IN lv_path WITH ''. lv_encode = zcl_abapgit_html_action_utils=>dir_encode( lv_path ). rv_html = li_html->a( iv_txt = lv_path iv_act = |{ c_actions-change_dir }?{ lv_encode }| ). ENDMETHOD. METHOD build_head_menu. DATA: lo_tb_advanced TYPE REF TO zcl_abapgit_html_toolbar, lo_tb_branch TYPE REF TO zcl_abapgit_html_toolbar, lo_tb_tag TYPE REF TO zcl_abapgit_html_toolbar, lv_wp_opt LIKE zif_abapgit_html=>c_html_opt-crossout, lv_pull_opt LIKE zif_abapgit_html=>c_html_opt-crossout. IF mo_repo->get_local_settings( )-write_protected = abap_true. lv_wp_opt = zif_abapgit_html=>c_html_opt-crossout. lv_pull_opt = zif_abapgit_html=>c_html_opt-crossout. ELSE. lv_pull_opt = zif_abapgit_html=>c_html_opt-strong. ENDIF. lo_tb_branch = build_branch_dropdown( lv_wp_opt ). lo_tb_tag = build_tag_dropdown( lv_wp_opt ). lo_tb_advanced = build_advanced_dropdown( iv_wp_opt = lv_wp_opt iv_rstate = iv_rstate iv_lstate = iv_lstate ). ro_toolbar = build_main_toolbar( iv_pull_opt = lv_pull_opt iv_rstate = iv_rstate iv_lstate = iv_lstate io_tb_branch = lo_tb_branch io_tb_tag = lo_tb_tag io_tb_advanced = lo_tb_advanced ). ENDMETHOD. METHOD build_inactive_object_code. IF is_item-inactive = abap_true. rv_inactive_html_code = zcl_abapgit_html=>icon( iv_name = 'bolt/orange' iv_hint = 'Object or object part is inactive' iv_class = 'inactive' ). ENDIF. ENDMETHOD. METHOD build_main_menu. CREATE OBJECT ro_menu EXPORTING iv_id = 'toolbar-main'. ro_menu->add( iv_txt = zcl_abapgit_gui_buttons=>repo_list( ) iv_act = zif_abapgit_definitions=>c_action-abapgit_home )->add( iv_txt = zcl_abapgit_gui_buttons=>settings( ) iv_act = zif_abapgit_definitions=>c_action-go_settings )->add( iv_txt = zcl_abapgit_gui_buttons=>advanced( ) io_sub = zcl_abapgit_gui_chunk_lib=>advanced_submenu( ) )->add( iv_txt = zcl_abapgit_gui_buttons=>help( ) io_sub = zcl_abapgit_gui_chunk_lib=>help_submenu( ) ). ENDMETHOD. METHOD build_main_toolbar. DATA: li_log TYPE REF TO zif_abapgit_log. CREATE OBJECT ro_toolbar EXPORTING iv_id = 'toolbar-repo'. IF mo_repo->is_offline( ) = abap_false. IF iv_rstate IS NOT INITIAL. "" Something new at remote ro_toolbar->add( iv_txt = 'Pull' iv_act = |{ zif_abapgit_definitions=>c_action-git_pull }?key={ mv_key }| iv_opt = iv_pull_opt ). ENDIF. IF iv_lstate IS NOT INITIAL. "" Something new at local ro_toolbar->add( iv_txt = 'Stage' iv_act = |{ zif_abapgit_definitions=>c_action-go_stage }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). ENDIF. IF iv_rstate IS NOT INITIAL OR iv_lstate IS NOT INITIAL. "" Any changes ro_toolbar->add( iv_txt = 'Diff' iv_act = |{ zif_abapgit_definitions=>c_action-go_diff }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). ENDIF. li_log = mo_repo->get_log( ). IF li_log IS BOUND AND li_log->count( ) > 0. ro_toolbar->add( iv_txt = 'Log' iv_act = |{ zif_abapgit_definitions=>c_action-repo_log }?key={ mv_key }| ). ENDIF. ro_toolbar->add( iv_txt = 'Branch' io_sub = io_tb_branch ). ro_toolbar->add( iv_txt = 'Tag' io_sub = io_tb_tag ). ELSE. IF mo_repo->has_remote_source( ) = abap_true AND iv_rstate IS NOT INITIAL. ro_toolbar->add( iv_txt = 'Pull zip' iv_act = |{ zif_abapgit_definitions=>c_action-git_pull }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). ro_toolbar->add( iv_txt = 'Diff' iv_act = |{ zif_abapgit_definitions=>c_action-go_diff }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). ENDIF. ro_toolbar->add( iv_txt = 'Import zip' iv_act = |{ zif_abapgit_definitions=>c_action-zip_import }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). ro_toolbar->add( iv_txt = 'Export zip' iv_act = |{ zif_abapgit_definitions=>c_action-zip_export }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). li_log = mo_repo->get_log( ). IF li_log IS BOUND AND li_log->count( ) > 0. ro_toolbar->add( iv_txt = 'Log' iv_act = |{ zif_abapgit_definitions=>c_action-repo_log }?key={ mv_key }| ). ENDIF. ENDIF. ro_toolbar->add( iv_txt = 'Advanced' io_sub = io_tb_advanced ). ro_toolbar->add( iv_txt = 'View' io_sub = build_view_menu( ) ). ro_toolbar->add( iv_txt = 'Refresh' iv_act = |{ zif_abapgit_definitions=>c_action-repo_refresh }?key={ mv_key }| iv_opt = zif_abapgit_html=>c_html_opt-strong ). ro_toolbar->add( iv_txt = zcl_abapgit_html=>icon( iv_name = 'cog' ) iv_act = |{ zif_abapgit_definitions=>c_action-repo_settings }?key={ mv_key }| iv_title = `Repository Settings` ). ENDMETHOD. METHOD build_obj_jump_link. DATA lv_encode TYPE string. DATA li_html TYPE REF TO zif_abapgit_html. CREATE OBJECT li_html TYPE zcl_abapgit_html. lv_encode = zcl_abapgit_html_action_utils=>jump_encode( iv_obj_type = is_item-obj_type iv_obj_name = is_item-obj_name ). rv_html = li_html->a( iv_txt = |{ is_item-obj_name }| iv_act = |{ zif_abapgit_definitions=>c_action-jump }?{ lv_encode }| ). ENDMETHOD. METHOD build_tag_dropdown. CREATE OBJECT ro_tag_dropdown. IF mo_repo->is_offline( ) = abap_true. RETURN. ENDIF. ro_tag_dropdown->add( iv_txt = 'Overview' iv_act = |{ zif_abapgit_definitions=>c_action-go_tag_overview }?key={ mv_key }| ). ro_tag_dropdown->add( iv_txt = 'Switch' iv_act = |{ zif_abapgit_definitions=>c_action-git_tag_switch }?key={ mv_key }| iv_opt = iv_wp_opt ). ro_tag_dropdown->add( iv_txt = 'Create' iv_act = |{ zif_abapgit_definitions=>c_action-git_tag_create }?key={ mv_key }| ). ro_tag_dropdown->add( iv_txt = 'Delete' iv_act = |{ zif_abapgit_definitions=>c_action-git_tag_delete }?key={ mv_key }| ). ENDMETHOD. METHOD build_view_menu. CREATE OBJECT ro_toolbar. ro_toolbar->add( iv_txt = 'Changes First' iv_chk = mv_diff_first iv_act = c_actions-toggle_diff_first ). IF mo_repo->has_remote_source( ) = abap_true. ro_toolbar->add( iv_txt = 'Changes Only' iv_chk = mv_changes_only iv_act = c_actions-toggle_changes ). ro_toolbar->add( iv_txt = 'File Paths' iv_chk = boolc( NOT mv_hide_files = abap_true ) iv_act = c_actions-toggle_hide_files ). ENDIF. ro_toolbar->add( iv_txt = 'Folders' iv_chk = mv_show_folders iv_act = c_actions-toggle_folders ). ENDMETHOD. METHOD constructor. DATA: lo_settings TYPE REF TO zcl_abapgit_settings, lx_error TYPE REF TO zcx_abapgit_exception, lv_package TYPE devclass. super->constructor( ). TRY. mv_key = iv_key. mo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). mv_cur_dir = '/'. "" Root mv_hide_files = zcl_abapgit_persistence_user=>get_instance( )->get_hide_files( ). mv_changes_only = zcl_abapgit_persistence_user=>get_instance( )->get_changes_only( ). mv_diff_first = abap_true. ms_control-page_title = 'Repository'. ms_control-page_menu = build_main_menu( ). "" Read global settings to get max # of objects to be listed lo_settings = zcl_abapgit_persist_settings=>get_instance( )->read( ). mv_max_lines = lo_settings->get_max_lines( ). mv_max_setting = mv_max_lines. lv_package = mo_repo->get_package( ). mv_are_changes_recorded_in_tr = zcl_abapgit_factory=>get_sap_package( lv_package )->are_changes_recorded_in_tr_req( ). CATCH zcx_abapgit_exception INTO lx_error. "" Reset 'last shown repo' so next start will go to repo overview "" and allow troubleshooting of issue zcl_abapgit_persistence_user=>get_instance( )->set_repo_show( || ). RAISE EXCEPTION lx_error. ENDTRY. ENDMETHOD. METHOD get_item_class. DATA lt_class TYPE TABLE OF string. IF is_item-is_dir = abap_true. APPEND 'folder' TO lt_class. ELSEIF is_item-changes > 0. APPEND 'modified' TO lt_class. ELSEIF is_item-obj_name IS INITIAL. APPEND 'unsupported' TO lt_class. ENDIF. IF lines( lt_class ) > 0. rv_html = | class=""{ concat_lines_of( table = lt_class sep = ` ` ) }""|. ENDIF. ENDMETHOD. METHOD get_item_icon. CASE is_item-obj_type. WHEN 'PROG' OR 'CLAS' OR 'FUGR' OR 'INTF' OR 'TYPE'. rv_html = zcl_abapgit_html=>icon( 'file-code/darkgrey' ). WHEN 'W3MI' OR 'W3HT' OR 'SFPF'. rv_html = zcl_abapgit_html=>icon( 'file-image/darkgrey' ). WHEN 'DEVC'. rv_html = zcl_abapgit_html=>icon( 'box/darkgrey' ). WHEN ''. rv_html = space. "" no icon WHEN OTHERS. rv_html = zcl_abapgit_html=>icon( 'file-alt/darkgrey' ). ENDCASE. IF is_item-is_dir = abap_true. rv_html = zcl_abapgit_html=>icon( 'folder/darkgrey' ). ENDIF. ENDMETHOD. METHOD open_in_master_language. CONSTANTS: lc_abapgit_tcode TYPE tcode VALUE `ZABAPGIT`. DATA: lv_master_language TYPE spras, lt_spagpa TYPE STANDARD TABLE OF rfc_spagpa, ls_spagpa LIKE LINE OF lt_spagpa, ls_item TYPE zif_abapgit_definitions=>ty_item, lv_subrc TYPE syst-subrc, lv_save_sy_langu TYPE sy-langu. "" https://blogs.sap.com/2017/01/13/logon-language-sy-langu-and-rfc/ lv_master_language = mo_repo->get_dot_abapgit( )->get_master_language( ). IF lv_master_language = sy-langu. zcx_abapgit_exception=>raise( |Repo already opened in master language| ). ENDIF. ls_item-obj_name = lc_abapgit_tcode. ls_item-obj_type = |TRAN|. IF zcl_abapgit_objects=>exists( ls_item ) = abap_false. zcx_abapgit_exception=>raise( |Please install the abapGit repository| ). ENDIF. lv_save_sy_langu = sy-langu. SET LOCALE LANGUAGE lv_master_language. ls_spagpa-parid = zif_abapgit_definitions=>c_spagpa_param_repo_key. ls_spagpa-parval = mo_repo->get_key( ). INSERT ls_spagpa INTO TABLE lt_spagpa. CALL FUNCTION 'ABAP4_CALL_TRANSACTION' DESTINATION 'NONE' STARTING NEW TASK 'ABAPGIT' EXPORTING tcode = lc_abapgit_tcode TABLES spagpa_tab = lt_spagpa EXCEPTIONS call_transaction_denied = 1 tcode_invalid = 2 communication_failure = 3 system_failure = 4 OTHERS = 5. lv_subrc = sy-subrc. SET LOCALE LANGUAGE lv_save_sy_langu. IF lv_subrc <> 0. zcx_abapgit_exception=>raise( |Error from ABAP4_CALL_TRANSACTION. Subrc = { lv_subrc }| ). ENDIF. MESSAGE 'Repository opened in a new window' TYPE 'S'. ENDMETHOD. METHOD render_content. DATA: lt_repo_items TYPE zif_abapgit_definitions=>tt_repo_items, lo_browser TYPE REF TO zcl_abapgit_repo_content_list, lx_error TYPE REF TO zcx_abapgit_exception, lv_lstate TYPE char1, lv_rstate TYPE char1, lv_max TYPE abap_bool, lv_max_str TYPE string, lv_add_str TYPE string, li_log TYPE REF TO zif_abapgit_log, lv_render_transports TYPE abap_bool, lv_msg TYPE string, lo_news TYPE REF TO zcl_abapgit_news. FIELD-SYMBOLS LIKE LINE OF lt_repo_items. gui_services( )->get_hotkeys_ctl( )->register_hotkeys( me ). gui_services( )->register_event_handler( me ). "" Reinit, for the case of type change mo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( mo_repo->get_key( ) ). lo_news = zcl_abapgit_news=>create( mo_repo ). TRY. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( |
| ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_repo_top( io_repo = mo_repo io_news = lo_news iv_interactive_branch = abap_true ) ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_news( io_news = lo_news ) ). lv_render_transports = zcl_abapgit_factory=>get_cts_api( )->is_chrec_possible_for_package( mo_repo->get_package( ) ). CREATE OBJECT lo_browser EXPORTING io_repo = mo_repo. lt_repo_items = lo_browser->list( iv_path = mv_cur_dir iv_by_folders = mv_show_folders iv_changes_only = mv_changes_only ). apply_order_by( CHANGING ct_repo_items = lt_repo_items ). LOOP AT lt_repo_items ASSIGNING . zcl_abapgit_state=>reduce( EXPORTING iv_cur = -lstate CHANGING cv_prev = lv_lstate ). zcl_abapgit_state=>reduce( EXPORTING iv_cur = -rstate CHANGING cv_prev = lv_rstate ). ENDLOOP. ri_html->add( render_head_line( iv_lstate = lv_lstate iv_rstate = lv_rstate ) ). li_log = lo_browser->get_log( ). IF mo_repo->is_offline( ) = abap_false AND li_log->count( ) > 0. ri_html->add( '
' ). ri_html->add( zcl_abapgit_log_viewer=>to_html( li_log ) ). "" shows eg. list of unsupported objects ri_html->add( '
' ). ENDIF. ri_html->add( '
' ). CLEAR lv_msg. IF mo_repo->is_offline( ) = abap_true AND mo_repo->has_remote_source( ) = abap_true AND lv_lstate IS INITIAL AND lv_rstate IS INITIAL. "" Offline match banner lv_msg = 'ZIP source is attached and completely matches the local state'. ELSEIF lines( lt_repo_items ) = 0. "" Online match banner IF mv_changes_only = abap_true. lv_msg = 'Local state completely matches the remote repository'. ELSE. lv_msg = |Package is empty. Show { build_dir_jump_link( 'parent' ) } package|. ENDIF. ELSE. "" Repo content table ri_html->add( '' ). IF zcl_abapgit_path=>is_root( mv_cur_dir ) = abap_false. ri_html->add( render_parent_dir( ) ). ENDIF. ri_html->add( render_order_by( ) ). LOOP AT lt_repo_items ASSIGNING . IF mv_max_lines > 0 AND sy-tabix > mv_max_lines. lv_max = abap_true. EXIT. "" current loop ENDIF. ri_html->add( render_item( is_item = iv_render_transports = lv_render_transports ) ). ENDLOOP. ri_html->add( '
' ). ENDIF. IF NOT lv_msg IS INITIAL. ri_html->add( |
{ lv_msg }
| ). ENDIF. IF lv_max = abap_true. ri_html->add( '
' ). IF mv_max_lines = 1. lv_max_str = '1 object'. ELSE. lv_max_str = |first { mv_max_lines } objects|. ENDIF. lv_add_str = |+{ mv_max_setting }|. ri_html->add( |Only { lv_max_str } shown in list. Display { ri_html->a( iv_txt = lv_add_str iv_act = c_actions-display_more ) } more. (Set in Advanced > { ri_html->a( iv_txt = 'Settings' iv_act = zif_abapgit_definitions=>c_action-go_settings ) } )| ). ri_html->add( '
' ). ENDIF. ri_html->add( '
' ). ri_html->add( '
' ). CATCH zcx_abapgit_exception INTO lx_error. "" Reset 'last shown repo' so next start will go to repo overview "" and allow troubleshooting of issue zcl_abapgit_persistence_user=>get_instance( )->set_repo_show( || ). ri_html->add( render_head_line( iv_lstate = lv_lstate iv_rstate = lv_rstate ) ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_error( iv_extra_style = 'repo_banner' ix_error = lx_error ) ). ENDTRY. register_deferred_script( render_scripts( ) ). ENDMETHOD. METHOD render_head_line. DATA lo_toolbar TYPE REF TO zcl_abapgit_html_toolbar. CREATE OBJECT ri_html TYPE zcl_abapgit_html. lo_toolbar = build_head_menu( iv_lstate = iv_lstate iv_rstate = iv_rstate ). ri_html->add( '
' ). ri_html->add( '' ). IF mv_show_folders = abap_true. ri_html->add( || ). ENDIF. ri_html->add( '' ). ri_html->add( '
{ mv_cur_dir }' ). ri_html->add( lo_toolbar->render( iv_right = abap_true ) ). ri_html->add( '
' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_item. DATA: lv_link TYPE string, lv_colspan TYPE i. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_render_transports = abap_false. lv_colspan = 2. ELSE. lv_colspan = 3. ENDIF. ri_html->add( || ). IF is_item-obj_name IS INITIAL AND is_item-is_dir = abap_false. ri_html->add( || && '' && 'non-code and meta files' && '' ). ELSE. ri_html->add( |{ get_item_icon( is_item ) }| ). IF iv_render_transports = abap_true. ri_html->add( render_item_lock_column( is_item ) ). ENDIF. IF is_item-is_dir = abap_true. "" Subdir lv_link = build_dir_jump_link( is_item-path ). ri_html->add( |{ lv_link }| ). ELSE. lv_link = build_obj_jump_link( is_item ). ri_html->add( |{ is_item-obj_type }| ). ri_html->add( |{ lv_link } { build_inactive_object_code( is_item ) }| ). ENDIF. ENDIF. "" Files ri_html->add( '' ). ri_html->add( render_item_files( is_item ) ). ri_html->add( '' ). "" Command IF mo_repo->has_remote_source( ) = abap_true. ri_html->add( '' ). ri_html->add( render_item_command( is_item ) ). ri_html->add( '' ). ENDIF. ri_html->add( '' ). ENDMETHOD. METHOD render_item_command. DATA: lv_difflink TYPE string, ls_file LIKE LINE OF is_item-files. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF is_item-is_dir = abap_true. "" Directory ri_html->add( '
' ). ri_html->add( |{ is_item-changes } changes| ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_item_state( iv_lstate = is_item-lstate iv_rstate = is_item-rstate ) ). ri_html->add( '
' ). ELSEIF is_item-changes > 0. IF mv_hide_files = abap_true AND is_item-obj_name IS NOT INITIAL. lv_difflink = zcl_abapgit_html_action_utils=>obj_encode( iv_key = mo_repo->get_key( ) ig_object = is_item ). ri_html->add( '
' ). ri_html->add_a( iv_txt = |diff ({ is_item-changes })| iv_act = |{ zif_abapgit_definitions=>c_action-go_diff }?{ lv_difflink }| ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_item_state( iv_lstate = is_item-lstate iv_rstate = is_item-rstate ) ). ri_html->add( '
' ). ELSE. LOOP AT is_item-files INTO ls_file. ri_html->add( '
' ). IF ls_file-is_changed = abap_true. lv_difflink = zcl_abapgit_html_action_utils=>file_encode( iv_key = mo_repo->get_key( ) ig_file = ls_file ). ri_html->add_a( iv_txt = 'diff' iv_act = |{ zif_abapgit_definitions=>c_action-go_diff }?{ lv_difflink }| ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_item_state( iv_lstate = ls_file-lstate iv_rstate = ls_file-rstate ) ). ELSE. ri_html->add( ' ' ). ENDIF. ri_html->add( '
' ). ENDLOOP. ENDIF. ENDIF. ENDMETHOD. METHOD render_item_files. DATA: ls_file LIKE LINE OF is_item-files. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF mv_hide_files = abap_true AND is_item-obj_type IS NOT INITIAL. RETURN. ENDIF. LOOP AT is_item-files INTO ls_file. ri_html->add( |
{ ls_file-path && ls_file-filename }
| ). ENDLOOP. ENDMETHOD. METHOD render_item_lock_column. DATA li_cts_api TYPE REF TO zif_abapgit_cts_api. DATA lv_transport TYPE trkorr. DATA lv_transport_string TYPE string. DATA lv_icon_html TYPE string. DATA li_html TYPE REF TO zif_abapgit_html. CREATE OBJECT li_html TYPE zcl_abapgit_html. li_cts_api = zcl_abapgit_factory=>get_cts_api( ). TRY. IF is_item-obj_type IS INITIAL OR is_item-obj_name IS INITIAL OR li_cts_api->is_object_type_lockable( is_item-obj_type ) = abap_false OR li_cts_api->is_object_locked_in_transport( iv_object_type = is_item-obj_type iv_object_name = is_item-obj_name ) = abap_false. rv_html = ||. ELSE. lv_transport = li_cts_api->get_current_transport_for_obj( iv_object_type = is_item-obj_type iv_object_name = is_item-obj_name iv_resolve_task_to_request = abap_false ). lv_transport_string = lv_transport. lv_icon_html = li_html->a( iv_txt = li_html->icon( iv_name = 'briefcase/darkgrey' iv_hint = lv_transport_string ) iv_act = |{ zif_abapgit_definitions=>c_action-jump_transport }?transport={ lv_transport }| ). rv_html = || && |{ lv_icon_html }| && ||. ENDIF. CATCH zcx_abapgit_exception. ASSERT 1 = 2. ENDTRY. ENDMETHOD. METHOD render_order_by. DATA: lv_icon TYPE string, lt_col_spec TYPE zif_abapgit_definitions=>tty_col_spec, ls_col_spec TYPE zif_abapgit_definitions=>ty_col_spec. CREATE OBJECT ri_html TYPE zcl_abapgit_html. APPEND INITIAL LINE TO lt_col_spec. IF mv_are_changes_recorded_in_tr = abap_true. APPEND INITIAL LINE TO lt_col_spec. ENDIF. ls_col_spec-tech_name = 'OBJ_TYPE'. ls_col_spec-display_name = 'Type'. APPEND ls_col_spec TO lt_col_spec. ls_col_spec-tech_name = 'OBJ_NAME'. ls_col_spec-display_name = 'Name'. APPEND ls_col_spec TO lt_col_spec. ls_col_spec-tech_name = 'PATH'. ls_col_spec-display_name = 'Path'. APPEND ls_col_spec TO lt_col_spec. APPEND INITIAL LINE TO lt_col_spec. ri_html->add( || ). ri_html->add( || ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_order_by_header_cells( it_col_spec = lt_col_spec iv_order_by = mv_order_by iv_order_descending = mv_order_descending ) ). IF mv_diff_first = abap_true. lv_icon = 'check/blue'. ELSE. lv_icon = 'check/grey'. ENDIF. ri_html->add( '' ). ri_html->add( '' ). ENDMETHOD. METHOD render_parent_dir. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '' ). ri_html->add( |{ ri_html->icon( 'folder' ) }| ). ri_html->add( |{ build_dir_jump_link( '..' ) }| ). IF mo_repo->has_remote_source( ) = abap_true. ri_html->add( || ). "" Dummy for online ENDIF. ri_html->add( '' ). ENDMETHOD. METHOD render_scripts. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->set_title( cl_abap_typedescr=>describe_by_object_ref( me )->get_relative_name( ) ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_repo_palette( zif_abapgit_definitions=>c_action-go_repo ) ). ENDMETHOD. METHOD switch_to_pr. DATA lo_repo_online TYPE REF TO zcl_abapgit_repo_online. DATA lt_pulls TYPE zif_abapgit_pr_enum_provider=>tty_pulls. DATA ls_pull LIKE LINE OF lt_pulls. IF mo_repo->is_offline( ) = abap_true. zcx_abapgit_exception=>raise( 'Unexpected PR switch for offline repo' ). ENDIF. IF mo_repo->get_local_settings( )-write_protected = abap_true. zcx_abapgit_exception=>raise( 'Cannot switch branch. Local code is write-protected by repo config' ). ENDIF. lo_repo_online ?= mo_repo. IF iv_revert = abap_true. lo_repo_online->switch_origin( '' ). ELSE. lt_pulls = zcl_abapgit_pr_enumerator=>new( lo_repo_online )->get_pulls( ). IF lines( lt_pulls ) = 0. RETURN. "" false ENDIF. ls_pull = zcl_abapgit_ui_factory=>get_popups( )->choose_pr_popup( lt_pulls ). IF ls_pull IS INITIAL. RETURN. "" false ENDIF. lo_repo_online->switch_origin( ls_pull-head_url ). lo_repo_online->set_branch_name( |refs/heads/{ ls_pull-head_branch }| ). "" TODO refactor rv_switched = abap_true. ENDIF. ENDMETHOD. METHOD zif_abapgit_gui_event_handler~on_event. DATA lv_path TYPE string. DATA lv_switched TYPE abap_bool. CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-go_repo. "" Switch to another repo CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_view_repo EXPORTING iv_key = |{ ii_event->query( iv_upper_cased = abap_true )->get( 'KEY' ) }|. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page_replacing. WHEN c_actions-toggle_hide_files. "" Toggle file diplay mv_hide_files = zcl_abapgit_persistence_user=>get_instance( )->toggle_hide_files( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-change_dir. "" Change dir lv_path = ii_event->query( )->get( 'PATH' ). mv_cur_dir = zcl_abapgit_path=>change_dir( iv_cur_dir = mv_cur_dir iv_cd = lv_path ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-toggle_folders. "" Toggle folder view mv_show_folders = boolc( mv_show_folders <> abap_true ). mv_cur_dir = '/'. "" Root rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-toggle_changes. "" Toggle changes only view mv_changes_only = zcl_abapgit_persistence_user=>get_instance( )->toggle_changes_only( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-toggle_diff_first. mv_diff_first = boolc( mv_diff_first = abap_false ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-display_more. "" Increase MAX lines limit mv_max_lines = mv_max_lines + mv_max_setting. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-change_order_by. mv_order_by = ii_event->query( )->get( 'ORDERBY' ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-direction. mv_order_descending = boolc( ii_event->query( )->get( 'DIRECTION' ) = 'DESCENDING' ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-repo_open_in_master_lang. open_in_master_language( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-repo_switch_origin_to_pr. lv_switched = switch_to_pr( ). IF lv_switched = abap_true. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ELSE. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ENDIF. WHEN c_actions-repo_reset_origin. switch_to_pr( iv_revert = abap_true ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN OTHERS. rs_handled = super->zif_abapgit_gui_event_handler~on_event( ii_event ). "" TODO refactor, move to HOC components ENDCASE. ENDMETHOD. METHOD zif_abapgit_gui_hotkeys~get_hotkey_actions. DATA: ls_hotkey_action LIKE LINE OF rt_hotkey_actions. ls_hotkey_action-ui_component = 'Repo'. ls_hotkey_action-description = |Stage changes|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-go_stage. ls_hotkey_action-hotkey = |s|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Switch branch|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-git_branch_switch. ls_hotkey_action-hotkey = |b|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Installed repo list|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-abapgit_home. ls_hotkey_action-hotkey = |o|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Refresh repository|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-repo_refresh. ls_hotkey_action-hotkey = |r|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Pull|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-git_pull. ls_hotkey_action-hotkey = |p|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Diff|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-go_diff. ls_hotkey_action-hotkey = |d|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Uninstall repository|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-repo_purge. ls_hotkey_action-hotkey = |u|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Run code inspector|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-repo_code_inspector. ls_hotkey_action-hotkey = |i|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Show log|. ls_hotkey_action-action = zif_abapgit_definitions=>c_action-repo_log. ls_hotkey_action-hotkey = |l|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ENDMETHOD. ENDCLASS. ",11752,False,2459.6838831271452,median "class ZSAPLINK_SOTR definition public inheriting from ZSAPLINK final create public . *""* public components of class ZSAPLINK_SOTR *""* do not include other source files here!!! public section. methods CHECKEXISTS redefinition . methods CREATEIXMLDOCFROMOBJECT redefinition . methods CREATEOBJECTFROMIXMLDOC redefinition . protected section. *""* protected components of class ZSAPLINK_TABLES *""* do not include other source files here!!! methods DELETEOBJECT redefinition . methods GETOBJECTTYPE redefinition . private section. *""* private components of class ZSAPLINK_TABLES *""* do not include other source files here!!! ENDCLASS. CLASS ZSAPLINK_SOTR IMPLEMENTATION. METHOD checkexists. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ * Plugin created by: * Berthe Joseph * joseph.berthe@gmail.com * No implementation exists = abap_true. ENDMETHOD. method CREATEIXMLDOCFROMOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ * Plugin created by: * Berthe Joseph * joseph.berthe@gmail.com TYPES: BEGIN OF totrhead, packet TYPE sotr_head-paket, END OF totrhead. DATA rc(4) TYPE n. DATA root_node TYPE REF TO if_ixml_element. DATA sub_node TYPE REF TO if_ixml_element. DATA datarow_node TYPE REF TO if_ixml_element. DATA _concept TYPE sotr_head-concept. DATA _objtype TYPE string. DATA _header TYPE sotr_head. DATA _entry_keys TYPE TABLE OF sotr_text. DATA _entry TYPE TABLE OF sotr_text. DATA _otr_keys TYPE TABLE OF sotr_key. DATA _paket TYPE totrhead. FIELD-SYMBOLS: TYPE STANDARD TABLE. FIELD-SYMBOLS: TYPE ANY. FIELD-SYMBOLS: TYPE sotr_key. * Check that table exits. REFRESH _otr_keys. CLEAR _header. _paket-packet = objname. CALL FUNCTION 'SOTR_GET_KEYS_FOR_PACKAGE' EXPORTING paket = _paket-packet IMPORTING sotr_keys = _otr_keys EXCEPTIONS no_entry_found = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = `OTR : Package not found`. ENDIF. _objtype = getobjecttype( ). root_node = xmldoc->create_element( _objtype ). me->setattributesfromstructure( node = root_node structure = _paket ). LOOP AT _otr_keys ASSIGNING . CLEAR: _header. REFRESH: _entry. CALL FUNCTION 'SOTR_GET_CONCEPT' EXPORTING concept = -concept IMPORTING header = _header TABLES entries = _entry EXCEPTIONS no_entry_found = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = `OTR not found`. ENDIF. * Create sub node sub_node = xmldoc->create_element( 'SOTR_HEAD' ). me->setattributesfromstructure( node = sub_node structure = _header ). * Create dynamic internal table and work area ASSIGN ('_ENTRY[]') TO . * Write records to XML node LOOP AT ASSIGNING . datarow_node = xmldoc->create_element( `SOTR_TEXT` ). me->setattributesfromstructure( node = datarow_node structure = ). rc = sub_node->append_child( datarow_node ). ENDLOOP. rc = root_node->append_child( sub_node ). ENDLOOP. * Add node rc = xmldoc->append_child( root_node ). ixmldocument = xmldoc. endmethod. METHOD createobjectfromixmldoc. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ * Plugin created by: * Berthe Joseph * joseph.berthe@gmail.com TYPES: BEGIN OF totrhead, packet TYPE sotr_head-paket, END OF totrhead. DATA root_node TYPE REF TO if_ixml_element. DATA sub_node TYPE REF TO if_ixml_element. DATA sub_node_node TYPE REF TO if_ixml_element. DATA sub_node_filter TYPE REF TO if_ixml_node_filter. DATA sub_node_iterator TYPE REF TO if_ixml_node_iterator. DATA datarow_node TYPE REF TO if_ixml_element. DATA datarow_filter TYPE REF TO if_ixml_node_filter. DATA datarow_iterator TYPE REF TO if_ixml_node_iterator. DATA _objtype TYPE string. DATA _header TYPE sotr_head. DATA _text_tab TYPE sotr_text_tt. DATA _packet TYPE sotr_pack. DATA _object_type TYPE trobjtype. DATA _msg_err TYPE string. DATA _paket TYPE totrhead. DATA checkexists TYPE flag. DATA dref_tab_head TYPE REF TO data. DATA dref_head TYPE REF TO data. DATA dref_tab_text TYPE REF TO data. DATA dref_text TYPE REF TO data. FIELD-SYMBOLS: TYPE STANDARD TABLE. FIELD-SYMBOLS: TYPE STANDARD TABLE. FIELD-SYMBOLS: TYPE sotr_head . FIELD-SYMBOLS: TYPE sotr_text . "" --> "" This bloc is useless for this version. checkexists = checkexists( ). IF checkexists IS NOT INITIAL. IF overwrite IS INITIAL. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>existing. ELSE. * delete object for new install deleteobject( ). ENDIF. ENDIF. "" <-- _objtype = getobjecttype( ). _object_type = _objtype. xmldoc = ixmldocument. root_node ?= xmldoc->find_from_name( _objtype ). * Get table name from XML. me->getstructurefromattributes( EXPORTING node = root_node CHANGING structure = _paket ). _packet = _paket-packet. "" Check if Package exist. SELECT COUNT(*) FROM tdevc WHERE devclass EQ _packet. IF sy-subrc EQ 0. * Create dynamic internal table and work area CREATE DATA dref_tab_head TYPE TABLE OF ('SOTR_HEAD'). ASSIGN dref_tab_head->* TO . CREATE DATA dref_head LIKE LINE OF . ASSIGN dref_head->* TO . * Build dynamic internal table from XML FREE: sub_node_filter, sub_node_iterator, sub_node_node. "" Find all sub_node. sub_node_filter = xmldoc->create_filter_name( `SOTR_HEAD` ). sub_node_iterator = xmldoc->create_iterator_filtered( sub_node_filter ). sub_node_node ?= sub_node_iterator->get_next( ). WHILE sub_node_node IS NOT INITIAL. APPEND INITIAL LINE TO ASSIGNING . me->getstructurefromattributes( EXPORTING node = sub_node_node CHANGING structure = ). * Create dynamic internal table and work area CREATE DATA dref_tab_text TYPE TABLE OF ('SOTR_TEXT'). ASSIGN dref_tab_text->* TO . CREATE DATA dref_text LIKE LINE OF . ASSIGN dref_text->* TO . FREE: datarow_filter, datarow_iterator, datarow_node. datarow_filter = sub_node_node->create_filter_name( `SOTR_TEXT` ). datarow_iterator = sub_node_node->create_iterator_filtered( datarow_filter ). datarow_node ?= datarow_iterator->get_next( ). WHILE datarow_node IS NOT INITIAL. APPEND INITIAL LINE TO ASSIGNING . me->getstructurefromattributes( EXPORTING node = datarow_node CHANGING structure = ). APPEND TO _text_tab. datarow_node ?= datarow_iterator->get_next( ). ENDWHILE. * Create the OTR CALL FUNCTION 'SOTR_CREATE_CONCEPT' EXPORTING paket = _packet crea_lan = -crea_lan alias_name = -alias_name object = 'WDCC' entries = _text_tab EXCEPTIONS package_missing = 1 crea_lan_missing = 2 object_missing = 3 paket_does_not_exist = 4 alias_already_exist = 5 object_type_not_found = 6 langu_missing = 7 identical_context_not_allowed = 8 text_too_long = 9 error_in_update = 10 no_master_langu = 11 error_in_concept_id = 12 alias_not_allowed = 13 tadir_entry_creation_failed = 14 internal_error = 15 error_in_correction = 16 user_cancelled = 17 no_entry_found = 18 OTHERS = 19. IF sy-subrc <> 0. DATA: lv_msg TYPE string. CASE sy-subrc. WHEN 1. lv_msg = 'OTR : Package missing.'. WHEN 2. lv_msg = 'OTR : Language missing.'. WHEN 3. lv_msg = 'OTR : Object missing.'. WHEN 4. lv_msg = 'OTR : Packet doesn''t exist.'. WHEN 5. lv_msg = 'OTR : Alias already exist.'. WHEN 6. lv_msg = 'OTR : Object type not found.'. WHEN 7. lv_msg = 'OTR : Language missing.'. WHEN 8. lv_msg = 'OTR : Identical context not allowed.'. WHEN 9. lv_msg = 'OTR : Text too long.'. WHEN 10. lv_msg = 'OTR : Error in update.'. WHEN 11. lv_msg = 'OTR : No master language.'. WHEN 12. lv_msg = 'OTR : Error in concept ID (GUID).'. WHEN 13. lv_msg = 'OTR : Alias not allowed.'. WHEN 14. lv_msg = 'OTR : TADIR entry creation failed.'. WHEN 15. lv_msg = 'OTR : Internal Error.'. WHEN 16. lv_msg = 'OTR : Error in correction.'. WHEN 17. lv_msg = 'OTR : User cancelled.'. WHEN 18. lv_msg = 'OTR : No entry found.'. WHEN OTHERS. lv_msg = 'OTR : Global error.'. ENDCASE. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = lv_msg. ENDIF. sub_node_node ?= sub_node_iterator->get_next( ). ENDWHILE. ELSE. CONCATENATE 'Package ' _packet ' doesn''t exist.' INTO _msg_err RESPECTING BLANKS. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = _msg_err. ENDIF. name = _packet. ENDMETHOD. METHOD deleteobject. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ * Plugin created by: * Berthe Joseph * joseph.berthe@gmail.com TYPES: BEGIN OF totrhead, packet TYPE sotr_head-paket, END OF totrhead. DATA _concept TYPE sotr_head-concept. DATA _objtype TYPE string. DATA _header TYPE sotr_head. DATA _entry_keys TYPE TABLE OF sotr_text. DATA _entry TYPE TABLE OF sotr_text. DATA _otr_keys TYPE TABLE OF sotr_key. DATA _paket TYPE totrhead. FIELD-SYMBOLS: TYPE sotr_key. _paket-packet = objname. CALL FUNCTION 'SOTR_GET_KEYS_FOR_PACKAGE' EXPORTING paket = _paket-packet IMPORTING sotr_keys = _otr_keys EXCEPTIONS no_entry_found = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = `OTR : Package not found`. ENDIF. _objtype = getobjecttype( ). LOOP AT _otr_keys ASSIGNING . CLEAR: _header. REFRESH: _entry. CALL FUNCTION 'SOTR_DELETE_CONCEPT' EXPORTING concept = -concept EXCEPTIONS no_authorization = 1 no_entry_found = 2 concept_used = 3 no_master_language = 4 no_source_system = 5 no_tadir_entry = 6 error_in_correction = 7 user_cancelled = 8 text_not_found = 9 invalid_package = 10 text_not_changeable = 11 text_enqueued = 12 no_correction = 13 parameter_error = 14. DATA _msg_err TYPE string. CLEAR _msg_err. CASE sy-subrc. WHEN 14. _msg_err = 'OTR (Del) : No TADIR found.'. WHEN 7. _msg_err = 'OTR (Del) : Error in correction.'. WHEN 8. _msg_err = 'OTR (Del) : ser Cancelled.'. WHEN 10. _msg_err = 'OTR (Del) : Invalid package.'. WHEN 14. _msg_err = 'OTR (Del) : ext no t changeable.'. WHEN 12. _msg_err = 'OTR (Del) : Txt Enqueued.'. WHEN 13. _msg_err = 'OTR (Del) : No Correction'. WHEN 14. _msg_err = 'OTR (Del) : Parameter error.'. WHEN 9. WHEN OTHERS. ENDCASE. IF _msg_err IS NOT INITIAL. CONCATENATE _msg_err -concept INTO _msg_err SEPARATED BY space. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = _msg_err. ENDIF. ENDLOOP. ENDMETHOD. method GETOBJECTTYPE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ * Plugin created by: * Berthe Joseph * joseph.berthe@gmail.com objecttype = 'SOTR'. ""Table Contents endmethod. ENDCLASS. ",4768,False,1119.1895163128452,median "#define FW_VERSION ""Ventilation_2020-05-06"" /* EEPROM MAP : addr 0...99 - для проверки состояния eeprom : == ap_ssid, иначе произвольные значения addr 110 - память состояния битовых переменных bit 0 : man_cmd bit 1 : rem_cmd bit 2 : auto_cmd bit 3 : bit 4 : bit 5 : bit 6 : bit 7 : addr 114...117 - mode_ctrl (int) addr 120...123 - set_temp (float) addr 124...127 - set_hum (float) addr 128...131 - set_moist (float) addr 132...135 - air_val (int) - показания датчика влажности почвы, соответствующие 0% addr 136...139 - water_val (int) - показания датчика влажности почвы, соответствующие 100% */ // === Library === #include #include #include #include #include #include #include #include #include #include #include #include // === Index === byte n = 0; // === WiFi AP Mode === IPAddress ap_ip(192,168,123,(20+n)); IPAddress ap_gateway(192,168,123,(20+n)); IPAddress ap_subnet(255,255,255,0); String ap_ssid = ""BGH_ventilation""; String ap_pass = ""12345678""; // === WiFi STA Mode === IPAddress ip, gw, mask; String ssid, pass; byte wifi_sta; // 0 = уже подключен к роутеру, 1 = подключаться к сети 1, 2 = подключаться к сети 2, ... // === MQTT broker === char* mqtt_server; int mqtt_port; String topic; String mqtt_client; String mqtt_user = """"; String mqtt_pass = """"; byte step_mqtt_send = 0; // переменная для поочередной (по одному сообщению за цикл loop) публикации сообщений на MQTT брокере boolean mqtt_send = false; WiFiClient espClient; PubSubClient client(espClient); // === WEB SERVER === ESP8266WebServer server(80); const char* root_str = ""\\n\\r""; const char* ctrl_str = ""\\n\\r""; // === BME280 === BME280I2C bme; float t, p, h, temp, hum; int pres, lcd_step; float set_temp = 24.0; // не ниже 20*С, оптимально 20...25*С float set_hum = 50.0; // оптимальная влажность воздуха 45...60% boolean bme_sensor_ok; long bme_n; // для усреднения выходных значений // === LCD Display === U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // === GPIO === const byte fan = 15; const byte ESP_BUILTIN_LED = 2; // === CTRL - управление === byte mode_ctrl; // режим: 0 = auto, 1 = remote, 2 = manual boolean set_ctrl; // для коррекции команд дистанционного управления boolean eeprom_ok; // true == EEPROM содержит актуальные данные boolean ventilation_run; boolean man_cmd; boolean rem_cmd; // дистанционная команда для реле вентилятора: false == выключить, true == включить boolean auto_cmd; // команда для реле вентилятора в автономном режиме: false == выключить, true == включить // === ТАЙМЕРЫ СОБЫТИЙ === long eventTime; // для снятия текущего времени с начала старта long event_reconnect; // для переподключения long event_auto_ctrl; // для формирования команды автономного режима long event_bme_begin; // для подключения датчика BME280 long event_serial_output; long event_mqtt_publish; long event_lcd_output; time_t mem; //----------------------------------------------------------------------------- // ПРОВЕРКА ДОСТУПНОСТИ WiFi СЕТИ //----------------------------------------------------------------------------- boolean scanWIFI(String found) { uint8_t n = WiFi.scanNetworks(); for (uint8_t i = 0; i < n; i++) { String ssidMy = WiFi.SSID(i); if (ssidMy == found) return true; } return false; } //----------------------------------------------------------------------------- // ОПРОС ДАТЧИКА BME280 //----------------------------------------------------------------------------- void sensor_read(){ bme_sensor_ok = false; if (bme.begin()) { bme_sensor_ok = true; BME280::TempUnit tempUnit(BME280::TempUnit_Celsius); BME280::PresUnit presUnit(BME280::PresUnit_Pa); bme.read(p, t, h, tempUnit, presUnit); // считать значения давления, температуры, влажности, в метрической системе, давление в Ра temp = (temp * bme_n + t - 0.3) / (bme_n + 1); hum = (hum * bme_n + h) / (bme_n + 1); pres = round((pres * bme_n + p / 133.3) / (bme_n + 1));// convert to mmHg bme_n +=1; } } //----------------------------------------------------------------------------- // КОМАНДЫ ВЕНТИЛЯЦИИ ПО ДАТЧИКУ BME280 В АВТОНОМНОМ РЕЖИМЕ //----------------------------------------------------------------------------- void auto_ctrl(){ event_auto_ctrl = millis(); bme_n = 0; if (temp >= set_temp + 1.0) auto_cmd = true; // включить вентилятора втоматически, если жарко if (hum > set_hum) auto_cmd = true; // включить вентилятора втоматически, если высокая влажность if (temp <= set_temp - 1.0 && hum < set_hum ) auto_cmd = false; // выключить вентилятор автоматически, если не жарко и влажность в норме if (temp <= 20.0) auto_cmd = false; // выключить вентилятор автоматически, если температура не выше 20 град.С if (!bme_sensor_ok) { Serial.println(""BME280 не найден !!!""); auto_cmd = false; // выключить вентилятор автоматически, если датчик не найден if (mode_ctrl == 0) mode_ctrl = 1; // если режим автономный, переключить в дистанционный режим } /* // *** вывод данных от датчика в порт Serial.print (""Температура воздуха ""); Serial.print (temp); Serial.println ("" *C""); Serial.print (""Влажность воздуха ""); Serial.print (hum); Serial.println ("" %""); Serial.print (""Давление ""); Serial.print (pres); Serial.println ("" mmHg""); Serial.print(""Команда автономного режима = ""); Serial.println((auto_cmd)? ""ВКЛ."" : ""ВЫКЛ.""); */ } //----------------------------------------------------------------------------- // ВЫВОД ИНФОРМАЦИИ НА LCD //----------------------------------------------------------------------------- void lcd_output() { event_lcd_output = millis(); static char to_lcd[10]; String value; // - температура if (lcd_step == 0) { value = String(temp) + ""*C""; value.toCharArray(to_lcd, 10); u8g2.firstPage(); do { u8g2.setFont(u8g2_font_logisoso20_tf); u8g2.drawStr(20, 26, to_lcd); } while ( u8g2.nextPage() ); } // - влажность if (lcd_step == 1) { value = String(hum) + "" %""; value.toCharArray(to_lcd, 10); u8g2.firstPage(); do { u8g2.setFont(u8g2_font_logisoso20_tf); u8g2.drawStr(20,26,to_lcd); } while ( u8g2.nextPage() ); } // - давление if (lcd_step == 2) { value = String(pres) + ""mm.Hg""; value.toCharArray(to_lcd, 10); u8g2.firstPage(); do { u8g2.setFont(u8g2_font_logisoso20_tf); u8g2.drawStr(3,26,to_lcd); } while ( u8g2.nextPage() ); } lcd_step += 1; if (lcd_step > 2) lcd_step = 0; } //----------------------------------------------------------------------------- // КОМАНДА УПРАВЛЕНИЯ РЕЛЕ ВЕНТИЛЯЦИИ //----------------------------------------------------------------------------- boolean fan_ctrl() { boolean out = ((mode_ctrl==0) && auto_cmd) || ((mode_ctrl==1) && rem_cmd) || ((mode_ctrl==2) && man_cmd); if(out) ventilation_run = true; return out; } // ===== ПРЕОБРАЗОВАНИE МИНУТ И СЕКУНД ИЗ INT В STRING ВИДА ""ХХ"" ===== String digits_to_String(int digits) { if (digits < 10) return ""0"" + String(digits); return String(digits); } // ===== ПРЕОБРАЗОВАНИE RSSI dBm В ПРОЦЕНТЫ ===== unsigned int toWiFiQuality(int32_t rssi) { unsigned int qu; if (rssi <= -100) qu = 0; else if (rssi >= -50) qu = 100; else qu = 2 * (rssi + 100); return qu; } // ===== ПРЕОБРАЗОВАНИЕ STRING В FLOAT ===== float String_to_float(String s){ float out; String int_s = s.substring(0, (s.indexOf('.'))); String fract_s = s.substring((s.indexOf('.') + 1), s.length()); if(s.indexOf('.') != -1) { //если в строке была найдена точка if(fract_s.length() == 1) out = float(int_s.toInt() + float(fract_s.toInt() * 0.1)); if(fract_s.length() == 2) out = float(int_s.toInt() + float(fract_s.toInt() * 0.01)); if(fract_s.length() == 3) out = float(int_s.toInt() + float(fract_s.toInt() * 0.001)); } else out = float(s.toInt()); // если не было точки в строке return out; } // ===== ПРЕОБРАЗОВАНИЕ FLOAT В STRING ===== String float_to_String(float n){ String ansver = """"; ansver = String(n); String ansver1 = ansver.substring(0, ansver.indexOf('.')); //отделяем число до точки int accuracy; accuracy = ansver.length() - ansver.indexOf('.'); //определяем точность (сколько знаков после точки) int stepen = 10; for(int i = 0; i < accuracy; i++) stepen = stepen * 10; String ansver2 = String(n * stepen); // приводит float к целому значению с потеряй разделителя точки(в общем удаляет точку) String ansver3 = """"; ansver3 += ansver1 += '.'; ansver3 += ansver2.substring((ansver.length() - accuracy), (ansver.length() - 1)); ansver3 += '\\n'; return ansver3; } //----------------------------------------------------------------------------- // ПЕРЕЗАГРУЗКА //----------------------------------------------------------------------------- void reboot() { handleRoot(); delay(1000); ESP.reset(); } //----------------------------------------------------------------------------- // WEB-СЕРВЕР //----------------------------------------------------------------------------- void http_server() { // *** Обслуживание главной страницы server.on(""/"", handleRoot); server.on(""/ventilation_set"", ventilation_set); server.on(""/ventilation_ctrl"", ventilation_ctrl); // *** Обслуживание страницы изменения режима управления server.on(""/ctrl_mode"", ctrl_mode); server.on(""/ctrl_mode_set"", ctrl_mode_set); // *** Обслуживание страницы обновления версии ПО server.on(""/upd"", upd); server.on(""/update"", HTTP_POST, []() { server.sendHeader(""Connection"", ""close""); server.send(200, ""text/plain"", (Update.hasError()) ? ""FAIL"" : ""OK""); handleRoot(); delay(1000); ESP.restart(); }, []() { HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { Serial.setDebugOutput(true); WiFiUDP::stopAll(); Serial.printf(""Update: %s\\n"", upload.filename.c_str()); uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; if (!Update.begin(maxSketchSpace)) { //start with max available size Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_WRITE) { if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_END) { if (Update.end(true)) { //true to set the size to the current progress Serial.printf(""Update Success: %u\\nRebooting...\\n"", upload.totalSize); } else { Update.printError(Serial); } Serial.setDebugOutput(false); } yield(); }); // *** Перезагрузка модуля //server.on(""/reboot"", reboot); server.on(""/reboot"", HTTP_GET, []() { handleRoot(); delay(1000); ESP.reset(); }); // *** Старт WEB-сервера server.begin(); delay(1000); } // ===== ГЛАВНАЯ СТРАНИЦА. СОСТОЯНИЕ ВЕНТИЛЯЦИИ ===== void handleRoot(){ String str = """"; str += F(""""); str += F(""""); str += F(""""); str += F(""""); str += F(""ВЕНТИЛЯЦИЯ В ТЕПЛИЦЕ""); str += F(""""); str += F(""""); // *** Дата и время str += F(""

Дата : ""); str += F("" г.   Время : ""); str += F(""


""); // *** Вентиляция str += F(""БОЛЬШАЯ ТЕПЛИЦА. ВЕНТИЛЯЦИЯ
""); // *** Показания датчиков str += F(""

Атмосферное давление: ""); if (bme_sensor_ok) str += F(""""); else str += F(""""); str += String(pres); str += F("" mm.Hg

""); str += F(""

Температура воздуха: ""); if (bme_sensor_ok) str += F(""""); else str += F(""""); str += String(temp); str += F("" °С

""); str += F(""

Влажность воздуха: ""); if (bme_sensor_ok) str += F(""""); else str += F(""""); str += String(hum); str += F("" %

""); // *** Состояние вентиляции str += F(""

Вентиляция: ""); if(digitalRead(fan)) str += F("" ВКЛЮЧЕНА""); if(!digitalRead(fan)) str += F("" ВЫКЛЮЧЕНА""); str += F(""


""); // *** Режим управления str += F(""

Режим управления: ""); str += F(""

""); // *** Кнопки управления ВРУЧНУЮ if (mode_ctrl == 2) { str += F("" ""); str += F(""

""); } str += F(""
""); // *** Уставки АВТОНОМНОГО режима str += F(""УСТАВКИ АВТОНОМНОГО РЕЖИМА
""); str += F(""
""); str += F(""

Tемпература ""); str += F("" +/- 1.0 °С

""); str += F(""

Влажность ""); str += F("" %

""); str += F(""

""); str += F(""

""); // *** Информация о подключениях str += F(""
ИНФОРМАЦИЯ О ПОДКЛЮЧЕНИЯХ

""); str += F(""

WiFi SSID : ""); str += F(""""); str += WiFi.SSID(); str += F(""

""); if(WiFi.status() == WL_CONNECTED) { str += F(""

IP addres: ""); str += F(""""); str += WiFi.localIP().toString(); str += F(""

""); str += F(""

WiFi RSSI : ""); if (toWiFiQuality(WiFi.RSSI()) < 30) str += F("" ""); else str += F("" ""); str += String(toWiFiQuality(WiFi.RSSI())); str += F("" %


""); str += F(""

MQTT BROKER: ""); str += F(""""); str += String(mqtt_server); str += F("" : ""); str += String(mqtt_port); str += F(""

""); str += F(""

To MQTT ""); if(client.connect(""BigGreenHouse"")) str += F("" CONNECTED !

""); else str += F("" NOT CONNECTED !!!

""); } else { str += F(""

WiFi ""); str += F("" NOT CONNECTED !!!

""); } str += F(""
""); // *** Версия ПО и обновление str += F(""
""); str += F(""

Версия ПО: ""); str += F(""

""); str += F(""
""); str += F(""""); server.send ( 200, ""text/html"", str ); delay(1000); } // *** Управление вентиляцией ВРУЧНУЮ *** void ventilation_ctrl() { if (server.arg(0)==""on"") man_cmd = true; if (server.arg(0)==""off"") man_cmd = false; server.send ( 200, ""text/html"", root_str ); delay(1000); } // *** Изменить уставки для АВТОНОМНОГО режима *** void ventilation_set(){ float set = String_to_float(server.arg(0)); if (set != 0.0) set_temp = set; if (set_temp < 21.0) set_temp = 21.0; set = String_to_float(server.arg(1)); if (set != 0.0) set_hum = set; if (set_hum < 40.0) set_hum = 40.0; if (set_hum > 90.0) set_hum = 90.0; server.send ( 200, ""text/html"", root_str ); auto_ctrl(); // при изменении уставок вновь сформировать команду автономного режима delay(1000); } // ===== WEB-СЕРВЕР. ВЫБОР РЕЖИМА УПРАВЛЕНИЯ ===== void ctrl_mode(){ String str = """"; str += F(""""); str += F(""""); str += F(""ВЫБОР РЕЖИМА УПРАВЛЕНИЯ""); str += F(""""); str += F(""""); str += F(""ВЫБОР РЕЖИМА УПРАВЛЕНИЯ
""); str += F(""

Режим управления: ""); if(mode_ctrl == 0) str += F(""АВТОНОМНЫЙ""); if(mode_ctrl == 1) str += F(""ДИСТАНЦИОННЫЙ""); if(mode_ctrl == 2) str += F(""ВРУЧНУЮ""); str += F(""


""); str += F(""

Изменить режим :

""); str += F(""

""); str += F(""

""); str += F(""

""); str += F(""

""); str += F(""""); server.send ( 200, ""text/html"", str ); delay(1000); } // *** Изменить режим управления *** void ctrl_mode_set() { if (server.arg(0)==""auto"") mode_ctrl = 0; //if (server.arg(0)==""rem"" && client.connected()) mode_ctrl = 1; if (server.arg(0)==""rem"") mode_ctrl = 1; if (server.arg(0)==""man"") mode_ctrl = 2; set_ctrl = true; server.send ( 200, ""text/html"", root_str ); delay(1000); } // ===== ОБНОВЛЕНИЕ ПО. ВЫБОР ФАЙЛА. СТАРТ ===== void upd() { String str = """"; str += F(""""); str += F(""""); str += F(""ОБНОВЛЕНИЕ ПО""); str += F(""""); str += F(""""); str += F(""

ОБНОВЛЕНИЕ ПО


""); str += F(""
""); str += F(""


""); str += F(""

""); str += F(""
""); server.sendHeader(""Connection"", ""close""); server.send(200, ""text/html"", str); } //----------------------------------------------------------------------------- // MQTT CALLBACK // функция выполняется, когда публикуется сообщение в топик, на который есть подписка //----------------------------------------------------------------------------- void callback(char* top, byte* payload, unsigned int length) { // *** Сообщение прибыло в топик String topic(top); String message = """"; for (int i = 0 ; i < length; i++) { message += (char)payload[i]; } Serial.print("" - В топик : ""); Serial.print(topic); Serial.print("" получено сообщение :""); Serial.print(message); Serial.print("" длиной = ""); Serial.println(length); // *** Команда дистанционного режима управления if(topic == ""BigGreenHouse/ventilation/ctrl/cmd"") { if (message == ""1"" || message == ""true"" || message == ""start"") rem_cmd = true; if (message == ""0"" || message == ""false"" || message == ""stop"") rem_cmd = false; } // *** Изменение режима управления if (topic == ""BigGreenHouse/ventilation/ctrl/mode"") { if (message == ""1"" || message == ""rem"") mode_ctrl = 1; if (message == ""0"" || message == ""auto"") mode_ctrl = 0; } // *** Изменение уставок автономного режима if (mode_ctrl == 1) { float set = String_to_float(message); if (topic == ""BigGreenHouse/ventilation/ctrl/set_temperature"") { if (set != 0.0) set_temp = set; if (set_temp < 21.0) set_temp = 21.0; } if (topic == ""BigGreenHouse/ventilation/ctrl/set_humidity"") { if (set != 0.0) set_hum = set; if (set_hum < 40.0) set_hum = 40.0; if (set_hum > 90.0) set_hum = 90.0; } auto_ctrl(); // вновь сформировать команду автономного режима } } //----------------------------------------------------------------------------- // MQTT PUBLISH // функция публикации сообщений на MQTT брокере по одному сообщению за цикл //----------------------------------------------------------------------------- void publishData() { static char message[10]; if(mqtt_send) { if (step_mqtt_send == 0) event_mqtt_publish = millis(); // *** ПУБЛИКАЦИЯ ПО ОДНОМУ СООБЩЕНИЮ ЗА ЦИКЛ switch (step_mqtt_send) { // *** Состояние выхода управления реле вентиляции case 0: topic = ""BigGreenHouse/ventilation/status/out""; String(fan_ctrl()).toCharArray(message, 10); break; // *** Актуальный режим управления case 1: topic = ""BigGreenHouse/ventilation/status/mode""; String(mode_ctrl).toCharArray(message, 10); break; // *** Показания датчика атмосферного давления case 2: topic = ""BigGreenHouse/ventilation/status/pressure""; dtostrf(pres, 8, 0, message); break; // *** Показания датчика температуры case 3: topic = ""BigGreenHouse/ventilation/status/temperature""; dtostrf(temp, 8, 2, message); break; // *** Показания датчика влажности воздуха case 4: topic = ""BigGreenHouse/ventilation/status/humidity""; dtostrf(hum, 8, 2, message); break; // *** Статус датчика BME case 5: topic = ""BigGreenHouse/ventilation/status/bme_sensor""; String(bme_sensor_ok).toCharArray(message, 10); break; // *** Изменить режим управления на MQTT брокере case 6: topic = ""BigGreenHouse/ventilation/ctrl/mode""; String(mode_ctrl).toCharArray(message, 10); set_ctrl = false; break; } client.publish(topic.c_str(), message); step_mqtt_send += 1; if (step_mqtt_send > 6) { mqtt_send = false; step_mqtt_send = 0; } } } //----------------------------------------------------------------------------- // РЕЖИМ WiFi_STA. ПОДКЛЮЧЕНИЕ К РОУТЕРУ //----------------------------------------------------------------------------- void sta_wifi() { // - WiHome - if (wifi_sta == 1) { ssid = ""...""; pass = ""...""; ip = IPAddress(192,168,50,20); gw = IPAddress(192,168,50,1); mask = IPAddress(255,255,255,0); mqtt_server = ""192.168.50.222""; mqtt_port = 1883; connect_wifi(); } // - Keenetic-2927 - if (wifi_sta == 2) { ssid = ""...""; pass = ""...""; ip = IPAddress(192,168,123,20); gw = IPAddress(192,168,123,1); mask = IPAddress(255,255,255,0); mqtt_port = 1883; connect_wifi(); } } // ===== ПОДКЛЮЧЕНИЕ К WiFi РОУТЕРУ ===== void connect_wifi() { Serial.print(""To WiFi : ""); Serial.println(ssid); WiFi.config(ip, gw, mask, gw); WiFi.begin(ssid.c_str(), pass.c_str()); // инициализация подключения к роутеру byte tries = 10; while(--tries && WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("".""); } Serial.println(""""); Serial.print(""WiFi.status = ""); Serial.println(WiFi.status()); if (WiFi.status() == WL_CONNECTED) { wifi_sta = 0; if (WiFi.localIP() == ip) { WiFi.softAPdisconnect(true); // отключить точку доступа ESP } Serial.print(""Connected to ""); // Подключено к Serial.println(WiFi.SSID()); Serial.print(""IP address : ""); // IP-адрес : Serial.println(WiFi.localIP()); // *** инициализация клиента MQTT mqtt_client = ap_ssid; client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); } else if (wifi_sta < 2) wifi_sta += 1; else wifi_sta = 1; } //----------------------------------------------------------------------------- // СТАРТОВАЯ ИНИЦИАЛИЗАЦИЯ //----------------------------------------------------------------------------- void setup() { // *** SERIAL PORT Serial.begin(115200); Serial.println(); // *** EEPROM EEPROM.begin(512); int i; unsigned char k; char ch[100]; int len=0; while(k != '\\0' && len<100) { EEPROM.get(0+len, k); ch[len] = k; len++; } ch[len]='\\0'; eeprom_ok = (String(ch) == ap_ssid); Serial.println (""=== EEPROM ===""); Serial.println (String(ch)); Serial.println (ap_ssid); Serial.println (eeprom_ok); // *** GPIO MODE pinMode(fan, OUTPUT); pinMode(ESP_BUILTIN_LED, OUTPUT); // *** GPIO STATE digitalWrite(fan, LOW); digitalWrite(ESP_BUILTIN_LED, LOW); // *** VARIABLE STATE if (eeprom_ok) { byte state; EEPROM.get(114,mode_ctrl); // режим управления EEPROM.get(110,state); man_cmd = bitRead(state, 0); // команда ручного режима для реле вентилятора rem_cmd = bitRead(state, 1); // дистанционная команда для реле вентилятора auto_cmd = bitRead(state, 2); // локальная команда для реле вентилятора EEPROM.get(120,set_temp); // уставка температуры для включения вентиляции EEPROM.get(124,set_hum); // уставка влажности для включения вентиляции } else { mode_ctrl = 0; // режим = автономный rem_cmd = false; // дистанционная команда для реле вентилятора = выключить auto_cmd = false; // локальная команда для реле вентилятора = выключить man_cmd = false; // команда ручного режима для реле вентилятора = выключить } // *** ИНИЦИАЛИЗАЦИЯ ОПРОСА BME280 ЧЕРЕЗ I2C Wire.begin(); event_bme_begin = millis(); while(!bme.begin() && millis() - event_bme_begin < 5000); // ожидание подключения BME280 bme_n = 0; sensor_read(); // *** ИНИЦИАЛИЗАЦИЯ LCD DISPLAY u8g2.begin(); lcd_step = 0; lcd_output(); // *** ИНИЦИАЛИЗАЦИЯ ТОЧКИ ДОСТУПА (WiFi_AP) WiFi.hostname(ap_ssid); // DHCP Hostname (useful for finding device for static lease) WiFi.softAPConfig (ap_ip, ap_gateway, ap_subnet); WiFi.softAP(ap_ssid, ap_pass); if (WiFi.getPersistent() == true) WiFi.persistent(false); // *** НАСТРОЙКИ ПОДКЛЮЧЕНИЯ К РОУТЕРУ (WiFi_STA) WiFi.disconnect(); IPAddress dns2(8, 8, 8, 8); if (WiFi.getAutoConnect() != true) { // configuration will be saved into SDK flash area WiFi.setAutoConnect(true); // on power-on automatically connects to last used hwAP WiFi.setAutoReconnect(true); // automatically reconnects to hwAP in case it's disconnected } delay(100); wifi_sta = 1; // *** WEB-СЕРВЕР http_server(); // *** ИНИЦИАЛИЗАЦИЯ ТАЙМЕРОВ СОБЫТИЙ mem = now(); event_serial_output = millis(); //event_lcd_output = millis(); Serial.println(""Ready""); // ""Готово"" digitalWrite(ESP_BUILTIN_LED, HIGH); } //----------------------------------------------------------------------------- // ОСНОВНОЙ ЦИКЛ //----------------------------------------------------------------------------- void loop() { // *** режимы управления if (mode_ctrl > 2) mode_ctrl = 2; if (mode_ctrl < 0) mode_ctrl = 0; if (mode_ctrl != 2) man_cmd = fan_ctrl(); // ""безударный"" переход в ручной режим // *** опрос датчика BME280 sensor_read(); // *** формирование команды автономного режима по температуре и влажности if((millis() - event_auto_ctrl) >= 60000) auto_ctrl(); // *** включение реле вентиляции digitalWrite(fan, fan_ctrl()); // *** вывод информации на LCD if((millis() - event_lcd_output) >= 10000) lcd_output(); // *** обработка запросов к WEB-серверу server.handleClient(); // *** если подключение к WiFi роутеру отсутствует, подключить if (WiFi.status() != WL_CONNECTED) { if (wifi_sta == 0) WiFi.softAP(ap_ssid, ap_pass); // только включить точку доступа, если соединение с роутером уже было установлено ранее else { sta_wifi(); // попытка подключения к роутеру, если ранее подключение отсутствовало } } // *** если подключен к WiFi роутеру, клиент MQTT if (WiFi.status() == WL_CONNECTED) { // если клиент подключен к MQTT, публикация данных каждые 10 секунд по одному сообщению за цикл if (client.connected()) { client.loop(); if ((millis() - event_mqtt_publish) >= 10000) mqtt_send = true; publishData(); } // иначе, повторять попытку подключения к MQTT брокеру каждые 5 секунд else if ((millis() - event_reconnect) >= 5000) { if (mode_ctrl == 1) mode_ctrl = 0; // переключить с дистанционного на автономный режим Serial.print(""MQTT connected failed, rc=""); // подключение к брокеру отсутствует Serial.println(client.state()); event_reconnect = millis(); if (client.connect(mqtt_client.c_str())) { Serial.print(""client MQTT connected OK. Subscribe : ""); // *** Подписка на топики управления вентиляцией topic = ""BigGreenHouse/ventilation/ctrl/#""; //client.subscribe(topic.c_str()); if (client.subscribe(topic.c_str())) Serial.println(topic); // подписка на топики } } } // *** вывод информации в порт if (millis() - event_serial_output > 20000) { // повторять через 20 секунд event_serial_output = millis(); Serial.print(""Режим управления :""); switch (mode_ctrl) { case 0: Serial.println(""АВТОНОМНЫЙ""); break; case 1: Serial.println(""ДИСТАНЦИОННЫЙ""); break; case 2: Serial.println(""ВРУЧНУЮ""); break; } Serial.print(""Реле вентилятора = ""); Serial.println((digitalRead(fan)) ? ""ВКЛ."" : ""ВЫКЛ.""); WiFi.printDiag(Serial); Serial.print(""WiFi status = ""); switch (WiFi.status()) { case 0: Serial.println(""0: WL_IDLE_STATUS – WiFi в процессе между сменой статусов""); break; case 1: Serial.println(""1: WL_NO_SSID_AVAIL – заданный SSID находится вне зоны доступа""); break; case 2: Serial.println(""2: ????""); break; case 3: Serial.println(""3: WL_CONNECTED – успешно подключен к WiFi""); break; case 4: Serial.println(""4: WL_CONNECT_FAILED – задан неправильный пароль""); break; case 5: Serial.println(""5: ????""); break; case 6: Serial.println(""6: WL_DISCONNECTED – ESP8266 не в режиме станции""); break; } String state = """"; state +=F(""Присвоен IP адрес: ""); state += WiFi.localIP().toString(); Serial.println((WiFi.status() == WL_CONNECTED) ? state : ""Не подключен к роутеру""); Serial.print(""MAC: ""); Serial.println(WiFi.macAddress()); } // *** Обновление значений в EEPROM char charBuf[100]; ap_ssid.toCharArray(charBuf, 100); EEPROM.put(0, charBuf); EEPROM.put(114,mode_ctrl); // режим управления byte state = 0; bitWrite(state, 0, man_cmd); // команда ручного режима для реле клапана полива bitWrite(state, 1, rem_cmd); // дистанционная команда для реле клапана полива bitWrite(state, 2, auto_cmd); // локальная команда для реле клапана полива EEPROM.put(110, state); EEPROM.put(120,set_temp); // уставка температуры для включения вентиляции EEPROM.put(124,set_hum); // уставка влажности для включения вентиляции //boolean result = EEPROM.commit(); if (!EEPROM.commit()) Serial.println(""ERROR! EEPROM commit failed""); delay(100); } ",16275,True,3462.3706700631765,median "/* Copyright (c) 2010 Trevor McCauley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.senocular.display.transform { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.events.Event; import flash.events.EventPhase; import flash.events.MouseEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.ui.Mouse; // TODO: event metadata // TODO: position restrictions? // TODO: what happens when fitToTarget (or others?) gets called while dragging? /** * A tool used for transforming display objects visually on the screen. * TransformTool instances are placed in a display object container along * with the objects it will transform. * @author Trevor McCauley * @version 2010.12.07 */ public class TransformTool extends Sprite { /** * Transform method for transforming a target object by updating * DisplayObject.transform.matrix. */ public static const TRANSFORM_MATRIX:String = ""matrix""; /** * Transform method for transforming a target object by updating * properties such as DisplayObject.width, DisplayObject.height and * DisplayObject.rotation. */ public static const TRANSFORM_PROPERTIES:String = ""properties""; /** * Event constant for cursorChanged event types. */ public static const CURSOR_CHANGED:String = ""cursorChanged""; /** * Event constant for targetChanged event types. */ public static const TARGET_CHANGED:String = ""targetChanged""; /** * Event constant for transformChanged event types. */ public static const TRANSFORM_CHANGED:String = ""transformChanged""; /** * Event constant for targetTransformed event types. */ public static const TARGET_TRANSFORMED:String = ""targetTransformed""; /** * Event constant for redraw event types. */ public static const REDRAW:String = ""redraw""; /** * Event constant for restrict event types. */ public static const RESTRICT:String = ""restrict""; /** * Event constant for commit event types. */ public static const COMMIT:String = ""commit""; /** * The cursor to be displayed by the Transform Tool. Cursors are * generally defined in and set by controls. Using the ControlCursor * control, the cursor can be seen in the TransformTool instance * itself. Otherwise, cursors will have to be manually displayed by * listening for the CURSOR_CHANGED event. */ public function get cursor():DisplayObject { return _cursor; } public function set cursor(value:DisplayObject):void { setCursor(value, null); } /** * Sets the cursor for the transform tool with a respective cursor * event that identifies the event that caused the change in the cursor. * @param value The cursor display object to be used for the current * Transform Tool cursor. * @param cursorEvent The event that invoked the change in the cursor. */ public function setCursor(value:DisplayObject, cursorEvent:Event = null):void { _cursorEvent = value ? cursorEvent : null; if (value == _cursor){ return; } cleanupCursor(); _cursor = value; setupCursor(); } private var _cursor:DisplayObject; /** * Setup steps when defining a new cursor value. You may need to * override this method to control the order of operations when * adding content to the set cursor setter. This is called after * a new cursor value is set. */ protected function setupCursor():void { if (_cursorHidesMouse){ if (_cursor == null){ Mouse.show(); }else{ Mouse.hide(); } } dispatchEvent( new Event(CURSOR_CHANGED) ); } /** * Cleanup steps when defining a new cursor value. You may need to * override this method to control the order of operations when * adding content to the set cursor setter. This is called before * a new cursor value is set. */ protected function cleanupCursor():void { // do nothing; may be overridden } /** * The event that invoked a change in the cursor. */ public function get cursorEvent():Event { return _cursorEvent; } protected var _cursorEvent:Event; /** * When true, the native mouse cursor will be hidden with * Mouse.hide() when the cursor is non-null. */ public function get cursorHidesMouse():Boolean { return _cursorHidesMouse; } public function set cursorHidesMouse(value:Boolean):void { _cursorHidesMouse = value; } private var _cursorHidesMouse:Boolean = false; /** * The registration manager used to keep track of registration * points in target objects. When using multiple instances of * TransformTool, you may want to have each instance use the same * registration manager so that each Transform Tool uses the same * registration points for objects. * @throws ArgumentError The specified value is null. */ public function get registrationManager():RegistrationManager { return _registrationManager; } public function set registrationManager(value:RegistrationManager):void { if (value){ if (value != _registrationManager){ _registrationManager = value; retrieveRegistration(); } }else{ throw new ArgumentError(""Parameter registrationManager cannot be null""); } } private var _registrationManager:RegistrationManager; /** * The current location of the registration point in the context * of the target object's coordinate space. This value will always * be a Point instance. When there is no target, the value will be * (0, 0). The registration manager uses this value to store * registration points for objects. */ public function get localRegistration():Point { return _localRegistration; } private var _localRegistration:Point = new Point(0, 0); /** * The minimum width along the transformed x axis that a target * object is allowed to have. If both a minWidth and minScaleX * are specified, the value resulting in the highest value will * be used. */ public function get minWidth():Number { return _minWidth; } public function set minWidth(value:Number):void { _minWidth = value; } private var _minWidth:Number; /** * The maximum width along the transformed x axis that a target * object is allowed to have. If both a maxWidth and maxScaleX * are specified, the value resulting in the smallest value will * be used. */ public function get maxWidth():Number { return _maxWidth; } public function set maxWidth(value:Number):void { _maxWidth = value; } private var _maxWidth:Number; /** * The minimum height along the transformed y axis that a target * object is allowed to have. If both a minHeight and minScaleY * are specified, the value resulting in the highest value will * be used. */ public function get minHeight():Number { return _minHeight; } public function set minHeight(value:Number):void { _minHeight = value; } private var _minHeight:Number; /** * The maximum height along the transformed y axis that a target * object is allowed to have. If both a maxHeight and maxScaleY * are specified, the value resulting in the smallest value will * be used. */ public function get maxHeight():Number { return _maxHeight; } public function set maxHeight(value:Number):void { _maxHeight = value; } private var _maxHeight:Number; /** * The minimum scale along the transformed x axis that a target * object is allowed to have. If both a minWidth and minScaleX * are specified, the value resulting in the highest value will * be used. */ public function get minScaleX():Number { return _minScaleX; } public function set minScaleX(value:Number):void { _minScaleX = value; } private var _minScaleX:Number; /** * The maximum scale along the transformed x axis that a target * object is allowed to have. If both a maxWidth and maxScaleX * are specified, the value resulting in the smallest value will * be used. */ public function get maxScaleX():Number { return _maxScaleX; } public function set maxScaleX(value:Number):void { _maxScaleX = value; } private var _maxScaleX:Number; /** * The minimum scale along the transformed y axis that a target * object is allowed to have. If both a minHeight and minScaleY * are specified, the value resulting in the highest value will * be used. */ public function get minScaleY():Number { return _minScaleY; } public function set minScaleY(value:Number):void { _minScaleY = value; } private var _minScaleY:Number; /** * The maximum scale along the transformed y axis that a target * object is allowed to have. If both a maxHeight and maxScaleY * are specified, the value resulting in the smallest value will * be used. */ public function get maxScaleY():Number { return _maxScaleY; } public function set maxScaleY(value:Number):void { _maxScaleY = value; } private var _maxScaleY:Number; /** * Determines whether or not transforming is allowed to result in * negative scales. When true, negative scaling is allowed and a * transformed target object can be mirrored along its x and/or y * axes. When false, negative scaling is not allowed and scale for * both axes will always be positive. */ public function get negativeScaling():Boolean { return _negativeScaling; } public function set negativeScaling(value:Boolean):void { _negativeScaling = value; } private var _negativeScaling:Boolean = true; /** * The minimum rotation allowed for a transformed target object. * Ranges between minRotation and maxRotation depend on which value * of the two is greater. */ public function get minRotation():Number { return _minRotation; } public function set minRotation(value:Number):void { _minRotation = value; } private var _minRotation:Number; /** * The maximum rotation allowed for a transformed target object. * Ranges between minRotation and maxRotation depend on which value * of the two is greater. */ public function get maxRotation():Number { return _maxRotation; } public function set maxRotation(value:Number):void { _maxRotation = value; } private var _maxRotation:Number; /** * A reference point (metric) indicating the location of the * registration point within the TransformTool coordinate space. */ public var registration:Point = new Point(); /** * A reference point (metric) indicating the location of the local * top left corner of the target object in the TransformTool * coordinate space. */ public var topLeft:Point = new Point(); /** * A reference point (metric) indicating the location of the local * top right corner of the target object in the TransformTool * coordinate space. */ public var topRight:Point = new Point(); /** * A reference point (metric) indicating the location of the local * bottom left corner of the target object in the TransformTool * coordinate space. */ public var bottomLeft:Point = new Point(); /** * A reference point (metric) indicating the location of the local * bottom right corner of the target object in the TransformTool * coordinate space. */ public var bottomRight:Point = new Point(); /** * Target display object to be transformed by the TransformTool. */ public function get target():DisplayObject { return _target; } public function set target(value:DisplayObject):void { setTarget(value, null); } public function setTarget(value:DisplayObject, targetEvent:Event = null):void { // define persistent target event and a mouse point // which remembers the stage mouse at the point // in time this call is first made (it may change // within the mouse event if the target moves) _targetEvent = value ? targetEvent : null; var targetMouseEvent:MouseEvent = _targetEvent as MouseEvent; if (targetMouseEvent){ _targetEventMouse = new Point(targetMouseEvent.stageX, targetMouseEvent.stageY); }else{ _targetEventMouse = null; } // checked after target event is set; the // mouse can be changed even if the target // stays the same if (value == _target){ return; } cleanupTarget(); _target = value; setupTarget(); } private var _target:DisplayObject; protected function setupTarget():void { // get the new registration for the new target retrieveRegistration(); if (_target){ // tool is hidden unless // a target is available visible = true; if (_autoRaise){ raise(); } fitToTarget(); }else{ visible = false; } dispatchEvent( new Event(TARGET_CHANGED) ); } /** * Cleanup steps when defining a new target value. You may need to * override this method to control the order of operations when * adding content to the set target setter. This is called before * a new target value is set. */ protected function cleanupTarget():void { if (_target){ // update the saved registration point for // the old target so it can be referenced // when the tool is reassigned to it later saveRegistration(); } } /** * A saved reference to the event that selected the * target when TransformTool.select was used. This allows * controls to use that event to perform appropriate actions * during selection, such as starting a drag (move) operation * on the target. */ public function get targetEvent():Event { return _targetEvent; } protected var _targetEvent:Event; public function get targetEventMouse():Point { return _targetEventMouse; } protected var _targetEventMouse:Point; /** * A representation of the TransformTool's display list in * array form. Control sets are assigned to this property. */ public function get controls():Array { var value:Array = []; // objects in display list // loop through display list one child at a time // adding them to the return value array var i:int = numChildren; while(i--){ value[i] = getChildAt(i); } return value; } public function set controls(value:Array):void { var child:DisplayObject; // child to be added var childrenOffset:int = 0; // number of invalid children in array // loop through array adding a display list child // for each child in the value array var i:int, n:int = value ? value.length : 0; for (i=0; i end){ removeChildAt(end); } } /** * The ""committed"" matrix transformation of a target * object. This is the matrix on which other transformations * are based. This is set when the target is set and when * is committed with methods like commitTarget(). When * preTransform and postTransform are applied, they're applied * to the baseMatrix value to resolve the calculatedMatrix. */ public function get baseMatrix():Matrix { return _baseMatrix; } protected var _baseMatrix:Matrix = new Matrix(); public function get preTransform():Matrix { return _preTransform; } protected var _preTransform:Matrix = new Matrix(); public function get postTransform():Matrix { return _postTransform; } protected var _postTransform:Matrix = new Matrix(); /** * The current transformation matrix of the Transform Tool. This * is updated when the target is defined and when * calculateTransform is called. Controls will automatically call * calculateTransform when used, updating the calculatedMatrix * during transformations. */ public function get calculatedMatrix():Matrix { return _calculatedMatrix; } protected var _calculatedMatrix:Matrix = new Matrix(); /** * Determines the method by which tool transformations * are applied to the target display object. */ public function get transformMethod():String { return _transformMethod; } public function set transformMethod(value:String):void { _transformMethod = value; } private var _transformMethod:String = TRANSFORM_MATRIX; /** * When true, the target is visually transformed with the tool * between target commits as the user changes the transform with * interactive controls. If false, target objects are only updated * when the target is committed which (typically) occurs only after * interaction with a control has completed. */ public function get livePreview():Boolean { return _livePreview; } public function set livePreview(value:Boolean):void { _livePreview = value; } private var _livePreview:Boolean = true; /** * When true, the targets will raise to the top of their * display lists, though not above the Transform Tool, when * assigned as targets of the tool. */ public function get autoRaise():Boolean { return _autoRaise; } public function set autoRaise(value:Boolean):void { _autoRaise = value; } private var _autoRaise:Boolean = false; /** * Indicates that a transform control has assumed control * of the tool for interaction. Other controls would check * this value to see if it is able to interact with the * tool without interference from other controls. */ public function get isActive():Boolean { return _isActive; } public function set isActive(value:Boolean):void { _isActive = value; } private var _isActive:Boolean = false; /** * Constructor for new TransformTool instances. * @param controls An array of controls to be added to the display * list. * @param registrationManager The registration manager to use for * target objects assigned to this TransformTool instance. If one is * not specified, one is created automatically. */ public function TransformTool(controls:Array = null, registrationManager:RegistrationManager = null){ visible = false; if (controls != null){ this.controls = controls; } if (registrationManager != null){ this.registrationManager = registrationManager; }else{ this.registrationManager = new RegistrationManager(); } } /** * Helper selection handler for selecting target objects. Set this * handler as the listener for a MouseEvent.MOUSE_DOWN event of an * object or a container of objects to have targets automatically set * to the Transform Tool when clicked. This event handler uses either * Event.target or Event.currentTarget as TransformTool.target * depending on which is in the same display object container as the * Transform Tool itself. * It is not required that you use this event handler. It is only a * helper function that can optionally be used to help ease * development. */ public function select(event:Event):void { // the selected object will either be the // event target or current target. The current // target is checked first followed by target. // The parent of the target must match the // parent of the tool to be selected this way. if (event.currentTarget != this && event.currentTarget.parent == parent){ setTarget(event.currentTarget as DisplayObject, event); }else if (event.target != this && event.target.parent == parent){ setTarget(event.target as DisplayObject, event); } } /** * Helper selection handler for deselecting target objects. Set this * handler as the listener for an event that would cause the * deselection of a target object. * It is not required that you use this event handler. It is only a * helper function that can optionally be used to help ease * development. */ public function deselect(event:Event):void { if (_target != null && event.eventPhase == EventPhase.AT_TARGET){ setTarget(null, null); } } /** * Fits the Transform Tool to match the current state of the target. * Use this when the target object is transformed outside of the * Transform Tool. */ public function fitToTarget():void { if (_target == null){ return; } resetTransformModifiers(); calculateTransform(false); update(); } /** * Moves the Transform Tool and the target object to the tops * of their respective parent display lists. This is automatically * called when a target is set and autoRaise is true. */ public function raise():void { var container:DisplayObjectContainer; // raise target first if (_target){ container = _target.parent; if (container){ container.setChildIndex(_target, container.numChildren - 1); } } // raise the tool second // to go above the target container = this.parent; if (container){ container.setChildIndex(this, container.numChildren - 1); } } /** * Calculates the value of calculatedMatrix by applying the values of * preTransform and postTransform to the baseMatrix. The value of * calculatedMatrix is used when transforms are being applied to the * tool and its target object. * @param reset When true, the preTransform and postTransform * modifiers will be reset to their identity matrix after the * calculation is complete. * @param enforceNegativeScaling When false, scale restrictions that * use negativeScaling to restrict calculatedMatrix are ignored. */ public function calculateTransform(reset:Boolean = true, enforceNegativeScaling:Boolean = true):void { // to compare with the new matrix to see if // a change has occurred var originalMatrix:Matrix = _calculatedMatrix.clone(); // our final transform starts with the preTransform // followed by the base transform of the last commit point _calculatedMatrix.identity(); _calculatedMatrix.concat(_preTransform); _calculatedMatrix.concat(_baseMatrix); // next, the post transform is concatenated on top // of the previous result, but for the post transform, // translation (x,y) values are not transformed. They're // saved with the respective post transform offset, then // reassigned after concatenating the post transformation var tx:Number = _calculatedMatrix.tx + _postTransform.tx; var ty:Number = _calculatedMatrix.ty + _postTransform.ty; // finally, concatenate post transform on to final _calculatedMatrix.concat(_postTransform); // reassign saved tx and ty values with the // included registration offset _calculatedMatrix.tx = tx; _calculatedMatrix.ty = ty; // apply restrictions before // offsetting the registration restrict(enforceNegativeScaling); // registration handling is done after // all transforms; the tool has to re-position // itself so that the new position of the // registration point now matches the old applyRegistrationOffset(); if (reset){ resetTransformModifiers(false); } if (!matrixEquals(originalMatrix, _calculatedMatrix)){ dispatchEvent( new Event(TRANSFORM_CHANGED) ); } } /** * Resets the registration point to its default location relative * to the (0,0) position in the target object's local coordinate * space. */ public function resetRegistration():void { // reset local values _localRegistration.x = 0; _localRegistration.y = 0; // update the registration manager saveRegistration(); // the only metric that need updating as // as result of local registration changing registration = _calculatedMatrix.transformPoint(_localRegistration); } /** * Resets the transformation of the target object to it's * unmodified state. */ public function resetTransform():void { resetTransformModifiers(false); normalizeBase(); // counter base transform with an inverted // post transform. This will transform the // target to the identity (reset) transform. _postTransform.identity(); _postTransform.concat(_baseMatrix); _postTransform.invert(); // do not transform position _postTransform.tx = 0; _postTransform.ty = 0; // calc transform to apply updated base // to final transform as well as handle // restrictions etc. For restrictions // negative scaling is off to make sure // the transform can be properly reset and // is not restricted in that manner calculateTransform(true, false); } /** * Performs a full update of the Transform Tool. This includes: * updating the metrics, updating the target (with optional * commit) and updating the controls. * @param commit When true, the target is updated with a call * to commitTarget. When false, updateTarget is used. */ public function update(commit:Boolean = true):void { updateMetrics(); if (commit){ commitTarget(); }else{ updateTarget(); } updateControls(); } /** * Dispatches an update event (REDRAW) allowing controls * within the tool to update themselves to match the * current calculatedMatrix transform. */ public function updateControls():void { dispatchEvent( new Event(REDRAW) ); } /** * Applies the calculatedMatrix transform to the target * object. Updates are only applied here if livePreview * is true. For non-livePreview updates, commitTarget is * required. */ public function updateTarget():void { if (_livePreview){ if (applyTransformToTarget()){ dispatchEvent( new Event(TARGET_TRANSFORMED) ); } } } /** * Applies the calculatedMatrix transform to the target * object and commits the target to the transformation. * This will reset all transformation modifiers * (preTransform and postTransform) and set the baseMatrix * to the updated transform of the target. */ public function commitTarget():void { // do not commit the target if the tool is currently // active, meaning a control is currently being dragged // and transforming the tool and target based on an // expected, previous commit if (!_isActive){ var transformed:Boolean = applyTransformToTarget(); resetTransformModifiers(); if (transformed){ dispatchEvent( new Event(TARGET_TRANSFORMED) ); } dispatchEvent( new Event(COMMIT) ); } } protected function validateTargetMatrix():Boolean { // no target fails validation if (_target == null){ return false; } // make sure the target has a 2D matrix if (_target.transform.matrix == null){ _target.transform.matrix = new Matrix(1, 0, 0, 1, _target.x, _target.y); } // target passes validation // whether or not a new 2D matrix was // created for it return true; } /** * Updates references used to identify points of interest in the * Transform Tool. These include points like the registration point, * topLeft, bottomRight, etc. Metrics should be updated when the * calculatedMatrix is updated and controls need to be redrawn as * many controls use these properties to position themselves. */ public function updateMetrics():void { var bounds:Rectangle = _target.getBounds(_target); retrieveRegistration(); registration = _calculatedMatrix.transformPoint(_localRegistration); var referencePoint:Point = new Point(bounds.left, bounds.top); topLeft = _calculatedMatrix.transformPoint(referencePoint); referencePoint.x = bounds.right; topRight = _calculatedMatrix.transformPoint(referencePoint); referencePoint.y = bounds.bottom; bottomRight = _calculatedMatrix.transformPoint(referencePoint); referencePoint.x = bounds.left; bottomLeft = _calculatedMatrix.transformPoint(referencePoint); } /** * Applies the transform defined by calculatedMatrix to the target * object. How this is applied depends on the value of * transformMethod. * @return True if the target object was changed, false if not. */ protected function applyTransformToTarget():Boolean { // if the target transform already matches the // calculated tansform of the tool, don't update if (!validateTargetMatrix() || matrixEquals(_target.transform.matrix, _calculatedMatrix)){ return false; } switch (_transformMethod){ case TRANSFORM_MATRIX:{ // assign adjusted matrix directly to // the matrix of the target instance _target.transform.matrix = _calculatedMatrix; break; } case TRANSFORM_PROPERTIES:{ // get the internal boundaries of the target instance // this is used to set the appropriate size var bounds:Rectangle = _target.getBounds(_target); if (bounds.width == 0 || bounds.height == 0){ // cannot set the size of an object with no content // doing so can corrupt the object's dimensions return false; } // first, any rotation needs to be removed so that // applications of width and height are accurate _target.rotation = 0; // get necessary transform data from the matrix // this is limited to size and rotation. Skew // transforms cannot be applied through // non-matrix properties var ratioX:Number = Math.sqrt(_calculatedMatrix.a*_calculatedMatrix.a + _calculatedMatrix.b*_calculatedMatrix.b); var ratioY:Number = Math.sqrt(_calculatedMatrix.c*_calculatedMatrix.c + _calculatedMatrix.d*_calculatedMatrix.d); var angle:Number = Math.atan2(_calculatedMatrix.b, _calculatedMatrix.a); // assign width and height followed by rotation and position _target.width = bounds.width * ratioX; _target.height = bounds.height * ratioY; _target.rotation = angle * (180/Math.PI); _target.x = _calculatedMatrix.tx; _target.y = _calculatedMatrix.ty; break; } default:{ // unrecognized transform type // do nothing return false; break; } } return true; } /** * Resets the values of preTransform, postTransform, and optionally * baseMatrix to their defaults. The pre and post transforms are set * to their identity matrices. The baseMatrix is set to the transform * matrix of the target object. * @param resetBase When true, baseMatrix is reset along with * preTransform and postTransform. */ protected function resetTransformModifiers(resetBase:Boolean = true):void { _preTransform.identity(); _postTransform.identity(); if (resetBase){ _baseMatrix.identity(); if (validateTargetMatrix()){ _baseMatrix.concat( _target.transform.matrix ); // flip the transform (if inverted and mirroring is // not permitted) around the axis that would be more // appropriate to flip around - the one which would // get the transform getting closest to right-side-up if (!_negativeScaling && !isPositiveScale(_baseMatrix)){ var baseRotation:Number = Math.atan2(_baseMatrix.a + _baseMatrix.c, _baseMatrix.d + _baseMatrix.b); if (baseRotation < -(3*Math.PI/4) || baseRotation > (Math.PI/4)){ _calculatedMatrix.c = -_calculatedMatrix.c; _calculatedMatrix.d = -_calculatedMatrix.d; }else{ _calculatedMatrix.a = -_calculatedMatrix.a; _calculatedMatrix.b = -_calculatedMatrix.b; } } } } } /** * For zero-scale transformations, this function will reset * the base scale to represent a positive value represented * by the amount value. This would be needed if transformations * expect a non-zero scale, for example if scaling the existing * scale which, if zero, would not scale at all. * @param amount The amount by which the base transformation * is normalized in scale. This amount is a pixel value based * on the internal bounds of the target object. * @return True if the base transform was normalized at all, * false if no changes were made. */ public function normalizeBase(amount:Number = 1):Boolean { if (_target == null){ return false; } var changed:Boolean = false; var bounds:Rectangle = _target.getBounds(_target); if (bounds.width != 0 && bounds.height != 0){ if (_baseMatrix.a == 0 && _baseMatrix.b == 0){ _baseMatrix.a = amount/bounds.width; changed = true; } if (_baseMatrix.d == 0 && _baseMatrix.c == 0){ _baseMatrix.d = amount/bounds.height; changed = true; } } return changed; } /** * Retrieves the current registration point from the registration * manager assigning it to localRegistration. */ protected function retrieveRegistration():void { var saved:Point = _registrationManager.getRegistration(_target); if (saved != null){ _localRegistration.x = saved.x; _localRegistration.y = saved.y; }else{ _localRegistration.x = 0; _localRegistration.y = 0; } } /** * Saves the current registration point value in localRegistration to * the registration manager. */ public function saveRegistration():void { _registrationManager.setRegistration(_target, _localRegistration); } /** * Adds registration offset to transformation matrix. This * assumes deriveFinalTransform has already been called. */ protected function applyRegistrationOffset():void { // update localRegistration from the registration manager retrieveRegistration(); if (_localRegistration.x != 0 || _localRegistration.y != 0){ // the registration offset is the change in x and y // of the pseudo registration point since the // transformation occurred. At this point, the final // transform should all ready be calculated var reg:Point = _baseMatrix.deltaTransformPoint(_localRegistration); var regOffset:Point = _calculatedMatrix.deltaTransformPoint(_localRegistration); regOffset = reg.subtract(regOffset); _calculatedMatrix.translate(regOffset.x, regOffset.y); } } // RESTRICTIONS /** * Goes under the assumption that scaling is handled by * the preTransform and rotation is handled by the * postTransform matrices. */ protected function restrict(enforceNegativeScaling:Boolean = true):void { // dispatch a cancelable RESTRICT event. // if the event is canceled, don't perform // the restict operations. Controls may do // this if they want to implement restrictions // on their own and not have interference // from the normal tool operations var restrictEvent:Event = new Event(RESTRICT, false, true); dispatchEvent(restrictEvent); if (restrictEvent.isDefaultPrevented()){ return; } restrictScale(enforceNegativeScaling); restrictRotation(); } /** * Applies restrictions to scaling. * @param enforceNegativeScaling When false, the value of negativeScaling * is not enforced when restricting scale. This should be set to false when * rotating a the Transform Tool since rotation can result in what could be * considered a negative scale. */ public function restrictScale(enforceNegativeScaling:Boolean = true):void { var bounds:Rectangle = _target.getBounds(_target); // cannot scale an object with no size if (bounds.width == 0 || bounds.height == 0){ return; } // find the values of min and max to use for // scale. Since these can come from either // width/height or scaleX/scaleY, both are // first checked for a value and then, if both // are set, the smallest variation is used. // if neither are set, the value will be // defined as NaN. var minX:Number; if (isNaN(_minWidth)){ minX = _minScaleX; }else{ if (isNaN(_minScaleX)){ minX = _minWidth/bounds.width; }else{ minX = Math.max(_minScaleX, _minWidth/bounds.width); } } var maxX:Number; if (isNaN(_maxWidth)){ maxX = _maxScaleX; }else{ if (isNaN(_maxScaleX)){ maxX = _maxWidth/bounds.width; }else{ maxX = Math.min(_maxScaleX, _maxWidth/bounds.width); } } var minY:Number; if (isNaN(_minHeight)){ minY = _minScaleY; }else{ if (isNaN(_minScaleY)){ minY = _minHeight/bounds.height; }else{ minY = Math.max(_minScaleY, _minHeight/bounds.height); } } var maxY:Number; if (isNaN(_maxHeight)){ maxY = _maxScaleY; }else{ if (isNaN(_maxScaleY)){ maxY = _maxHeight/bounds.height; }else{ maxY = Math.min(_maxScaleY, _maxHeight/bounds.height); } } // make sure each limit is positive if (minX < 0) minX = -minX; if (maxX < 0) maxX = -maxX; if (minY < 0) minY = -minY; if (maxY < 0) maxY = -maxY; var currScaleX:Number = Math.sqrt(_calculatedMatrix.a*_calculatedMatrix.a + _calculatedMatrix.b*_calculatedMatrix.b); var currScaleY:Number = Math.sqrt(_calculatedMatrix.c*_calculatedMatrix.c + _calculatedMatrix.d*_calculatedMatrix.d); // if negative scaling is not allowed // we need to figure out if the current scale // in either direction is going into the // negatives or not. To do this, the angle // of each axis is compared against the base // transform angles if (enforceNegativeScaling && !_negativeScaling){ var currAngleX:Number = Math.atan2(_calculatedMatrix.b, _calculatedMatrix.a); var baseAngleX:Number = Math.atan2(_baseMatrix.b, _baseMatrix.a); if (currScaleX != 0 && Math.abs(baseAngleX - currAngleX) > Math.PI/2){ currScaleX = -currScaleX; } var currAngleY:Number = Math.atan2(_calculatedMatrix.c, _calculatedMatrix.d); var baseAngleY:Number = Math.atan2(_baseMatrix.c, _baseMatrix.d); if (currScaleY != 0 && Math.abs(baseAngleY - currAngleY) > Math.PI/2){ currScaleY = -currScaleY; } } var scale:Number; // limited scale; NaN if not scaling var angle:Number; // angle of scale when basing on base if (!isNaN(minX) && currScaleX < minX){ scale = minX; }else if (!isNaN(maxX) && currScaleX > maxX){ scale = maxX; }else{ scale = Number.NaN; } if (!isNaN(scale)){ if (currScaleX){ scale = (scale/currScaleX); _calculatedMatrix.a *= scale; _calculatedMatrix.b *= scale; }else{ angle = Math.atan2(_baseMatrix.b, _baseMatrix.a); _calculatedMatrix.a = scale * Math.cos(angle); _calculatedMatrix.b = scale * Math.sin(angle); } } if (!isNaN(minY) && currScaleY < minY){ scale = minY; }else if (!isNaN(maxY) && currScaleY > maxY){ scale = maxY; }else{ scale = Number.NaN; } if (!isNaN(scale)){ if (currScaleY){ scale = (scale/currScaleY); _calculatedMatrix.c *= scale; _calculatedMatrix.d *= scale; }else{ angle = Math.atan2(_baseMatrix.c, _baseMatrix.d); _calculatedMatrix.c = scale * Math.sin(angle); _calculatedMatrix.d = scale * Math.cos(angle); } } // undo any negative scaling if (enforceNegativeScaling && !_negativeScaling && !isPositiveScale(_calculatedMatrix)){ // flip the final transform around the axis // to best match the base var baseX:Number = _baseMatrix.a + _baseMatrix.c; var toolX:Number = _calculatedMatrix.a + _calculatedMatrix.c; if ((toolX < 0 && baseX >= 0) || (toolX >= 0 && baseX < 0)){ _calculatedMatrix.a = -_calculatedMatrix.a; _calculatedMatrix.b = -_calculatedMatrix.b; }else{ _calculatedMatrix.c = -_calculatedMatrix.c; _calculatedMatrix.d = -_calculatedMatrix.d; } } } /** * Applies restrictions to rotation. */ public function restrictRotation():void { // both min and max rotation need to be set // in order to restrict rotation if (!isNaN(_minRotation) && !isNaN(_maxRotation)){ var min:Number = _minRotation * (Math.PI/180); var max:Number = _maxRotation * (Math.PI/180); var angle:Number = Math.atan2(_calculatedMatrix.b, _calculatedMatrix.a); // restrict to a single rotation value if (min == max){ if (angle != min){ setRotation(min); } // restricting to a range }else if (min < max){ if (angle < min){ setRotation(min); }else if (angle > max){ setRotation(max); } }else if (angle < min && angle > max){ if (Math.abs(angle - min) > Math.abs(angle - max)){ setRotation(max); }else{ setRotation(min); } } } } // HELPER FUNCTIONS /** * Determines if a matrix is scaled positively or not. * @param matrix The matrix to determine if it is positively scaled. * If not specified, calculatedMatrix is used. * @return Returns true if the matrix is positively scaled, false if * not. */ public function isPositiveScale(matrix:Matrix = null):Boolean { if (matrix == null) matrix = _calculatedMatrix; return Boolean(matrix.a*matrix.d - matrix.c*matrix.b > 0); } /** * Compares two matrices to see if they're equal. * @param m1 A matrix to be compared with another matrix. * @param m2 The matrix to be compared with the first matrix. * If this value is not provided calculatedMatrix is used. * @return True if the matrices match, false if not. */ public function matrixEquals(m1:Matrix, m2:Matrix = null):Boolean { if (m2 == null) m2 = _calculatedMatrix; if (m1.a != m2.a || m1.d != m2.d || m1.b != m2.b || m1.c != m2.c || m1.tx != m2.tx || m1.ty != m2.ty){ return false; } return true; } /** * Returns the rotation of target object based on the current value * of calculatedMatrix. A matrix's general rotation is based on the * rotation of its x axis. * @param matrix The matrix from which to find a rotation. If not * specified, calculatedMatrix is used. * @return The rotation of a matrix in radians. */ public function getRotation():Number { return getRotationX(null); } /** * Returns the rotation of a matrix on its x axis. * @param matrix The matrix from which to find a rotation. If not * specified, calculatedMatrix is used. * @return The rotation of a matrix along it's x axis in radians. */ public function getRotationX(matrix:Matrix = null):Number { if (matrix == null) matrix = _calculatedMatrix; return Math.atan2(matrix.b, matrix.a); } /** * Returns the rotation of a matrix on its y axis. * @param matrix The matrix from which to find a rotation. If not * specified, calculatedMatrix is used. * @return The rotation of a matrix along it's y axis in radians. */ public function getRotationY(matrix:Matrix = null):Number { if (matrix == null) matrix = _calculatedMatrix; return Math.atan2(matrix.c, matrix.d); } /** * Sets the rotation of a matrix. The rotation set is based on the x * axis. * @param value A new rotation value in radians. * @param matrix The matrix on which to set a rotation. If not * specified, calculatedMatrix is used. */ public function setRotation(value:Number, matrix:Matrix = null):void { if (isNaN(value)) return; if (matrix == null) matrix = _calculatedMatrix; var tx:Number = matrix.tx; var ty:Number = matrix.ty; var angle:Number = Math.atan2(matrix.b, matrix.a); matrix.rotate(value - angle); matrix.tx = tx; matrix.ty = ty; } /** * Returns the scale of a matrix along its x axis. * @param matrix The matrix from which to get the scale. If not * specified, calculatedMatrix is used. * @return The scale of a matrix along its x axis. */ public function getScaleX(matrix:Matrix = null):Number { if (matrix == null) matrix = _calculatedMatrix; return Math.sqrt(_calculatedMatrix.a*_calculatedMatrix.a + _calculatedMatrix.b*_calculatedMatrix.b); } /** * Sets the scale of a matrix along its x axis. * @param matrix The matrix for which to set a scale. If not * specified, calculatedMatrix is used. */ public function setScaleX(value:Number, matrix:Matrix = null):void { if (isNaN(value)) return; if (matrix == null) matrix = _calculatedMatrix; var angle:Number = Math.atan2(matrix.b, matrix.a); matrix.a = value * Math.cos(angle); matrix.b = value * Math.sin(angle); } /** * Returns the scale of a matrix along its y axis. * @param matrix The matrix from which to get the scale. If not * specified, calculatedMatrix is used. * @return The scale of a matrix along its y axis. */ public function getScaleY(matrix:Matrix = null):Number { if (matrix == null) matrix = _calculatedMatrix; return Math.sqrt(_calculatedMatrix.c*_calculatedMatrix.c + _calculatedMatrix.d*_calculatedMatrix.d); } /** * Sets the scale of a matrix along its y axis. * @param matrix The matrix for which to set a scale. If not * specified, calculatedMatrix is used. */ public function setScaleY(value:Number, matrix:Matrix = null):void { if (isNaN(value)) return; if (matrix == null) matrix = _calculatedMatrix; var angle:Number = Math.atan2(matrix.c, matrix.d); matrix.c = value * Math.sin(angle); matrix.d = value * Math.cos(angle); } /** * Returns the width of the target object based on its size within * its transformed x axis and the current value of calculatedMatrix. * This is different from the normal width reported by DisplayObject * which is based on the width of the object within its parent's * coordinate space. If no target exists 0 is returned. * @return The height of the target object. */ public function getWidth():Number { if (_target == null){ return 0; } var bounds:Rectangle = _target.getBounds(_target); return bounds.width * getScaleX(_calculatedMatrix); } /** * Sets the width of calculatedMatrix based on the size of the * current target. If target is null or the value passed is not a * number, calculatedMatrix is unchanged. * @param value The height value for the target object. */ public function setWidth(value:Number):void { if (_target == null || isNaN(value)){ return; } var bounds:Rectangle = _target.getBounds(_target); var ratio:Number = Math.abs(value)/bounds.width; ratio /= getScaleX(_calculatedMatrix); calculatedMatrix.a *= ratio; calculatedMatrix.b *= ratio; } /** * Returns the height of the target object based on its size within * its transformed y axis and the current value of calculatedMatrix. * This is different from the normal height reported by DisplayObject * which is based on the height of the object within its parent's * coordinate space. If no target exists 0 is returned. * @return The height of the target object. */ public function getHeight():Number { if (_target == null){ return 0; } var bounds:Rectangle = _target.getBounds(_target); return bounds.height * getScaleY(_calculatedMatrix); } /** * Sets the height of calculatedMatrix based on the size of the * current target. If target is null or the value passed is not a * number, calculatedMatrix is unchanged. * @param value The height value for the target object. */ public function setHeight(value:Number):void { if (_target == null || isNaN(value)){ return; } var bounds:Rectangle = _target.getBounds(_target); var ratio:Number = Math.abs(value)/bounds.height; ratio /= getScaleY(_calculatedMatrix); calculatedMatrix.c *= ratio; calculatedMatrix.d *= ratio; } /** * Set a custom scale for transformation controls (except for * the border and the ones for the rotation). * @param scale The new scale for the controls. * @param update Indicate if controls should then be updated with their new scale, true by default. **/ public function setControlScale(scale:Number, update:Boolean = true):void { if (!controls) return; var l:uint = controls.length; for (var i:int = 0; i < l; i++) { if (controls[i] is ControlBorder || controls[i] is ControlUVRotate) continue; controls[i].scaleX = controls[i].scaleY = scale; } if (update) updateControls(); } } }",12359,False,2141.956098235125,median "// *************************************************************************** // ***** ***** // ***** AtMega328P UART ANSI Terminal with 60x25 Character VGA and PS/2 ***** // ***** ***** // ***** written by Carsten Herting 02.06.2021 Version 2.2 ***** // ***** US-International version by Augusto Baffa Dec/21 ***** // ***** ***** // *************************************************************************** // Pin C0-5: terminal input bits 0-5 // Pin D0-7: parallel pixel output to 74166, in between: D6-7 terminal input bits 6-7 // Pin B0: CLKO ATmega328 system clock output // Pin B1: DATA_NEW input handshake // Pin B2: /VSYNC VGA (timer1, every 1/60s, could also be done) // Pin B3: /PE low pulse (by hand inside ISR for 74166 /PE pixel shift register sync parallel load) // Pin B4: /HSYNC VGA (by hand inside ISR, every 32µs) // Pin B5: DATA_ACK output handshake // See license at the end of this file. // // ** Fixed Escapes to clean line and screen jan, 6 2022 Augusto Baffa // Fuse: BF | DA | FD | FF #define WIDTH 60 #define HEIGHT 25 char row = 0, col = 0; // current cursor position in terminal window //char saved_row = 0, saved_col = 0; // current cursor position in terminal window //bool show_cursor = true; volatile int vline = 0; // current vertical position of pixel video output volatile byte vram[HEIGHT][WIDTH];// array of VideoRAM volatile char start = 0; // start line of the VideoRAM (thus avoiding moving data while scrolling) volatile int frames = 0; // 1/60s frame counter for cursor blinking volatile byte regout = 0; // index of current output position in queue volatile byte regin = 0; // index of current input position in queue volatile byte __attribute__ ((aligned (256))) reg[256]; // ring buffer data of keyboard input register const volatile byte __attribute__ ((aligned (256))) charset[8][256] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x18, 0x66, 0x66, 0x18, 0x62, 0x3C, 0x06, 0x0C, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x18, 0x3C, 0x3C, 0x06, 0x7E, 0x3C, 0x7E, 0x3C, 0x3C, 0x00, 0x00, 0x0E, 0x00, 0x70, 0x3C, 0x3C, 0x18, 0x7C, 0x3C, 0x78, 0x7E, 0x7E, 0x3C, 0x66, 0x3C, 0x1E, 0x66, 0x60, 0x63, 0x66, 0x3C, 0x7C, 0x3C, 0x7C, 0x3C, 0x7E, 0x66, 0x66, 0x63, 0x66, 0x66, 0x7E, 0x3C, 0x00, 0x3C, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0xFF, 0xFF, 0x01, 0x80, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0xE7, 0x99, 0x99, 0xE7, 0x9D, 0xC3, 0xF9, 0xF3, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0xE7, 0xC3, 0xC3, 0xF9, 0x81, 0xC3, 0x81, 0xC3, 0xC3, 0xFF, 0xFF, 0xF1, 0xFF, 0x8F, 0xC3, 0xC3, 0xE7, 0x83, 0xC3, 0x87, 0x81, 0x81, 0xC3, 0x99, 0xC3, 0xE1, 0x99, 0x9F, 0x9C, 0x99, 0xC3, 0x83, 0xC3, 0x83, 0xC3, 0x81, 0x99, 0x99, 0x9C, 0x99, 0x99, 0x81, 0xC3, 0xFF, 0xC3, 0xFF, 0xFF, 0x9F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF1, 0xE7, 0x8F, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x18, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x0C, 0x18, 0x18, 0x66, 0x18, 0x00, 0x00, 0x00, 0x03, 0x66, 0x18, 0x66, 0x66, 0x0E, 0x60, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x18, 0x00, 0x18, 0x66, 0x66, 0x3C, 0x66, 0x66, 0x6C, 0x60, 0x60, 0x66, 0x66, 0x18, 0x0C, 0x6C, 0x60, 0x77, 0x76, 0x66, 0x66, 0x66, 0x66, 0x66, 0x18, 0x66, 0x66, 0x63, 0x66, 0x66, 0x06, 0x30, 0x60, 0x0C, 0x18, 0x00, 0x30, 0x00, 0x60, 0x00, 0x06, 0x00, 0x0E, 0x00, 0x60, 0x18, 0x06, 0x60, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7F, 0xFE, 0x03, 0xC0, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0xE7, 0x99, 0x99, 0xC1, 0x99, 0x99, 0xF3, 0xE7, 0xE7, 0x99, 0xE7, 0xFF, 0xFF, 0xFF, 0xFC, 0x99, 0xE7, 0x99, 0x99, 0xF1, 0x9F, 0x99, 0x99, 0x99, 0x99, 0xFF, 0xFF, 0xE7, 0xFF, 0xE7, 0x99, 0x99, 0xC3, 0x99, 0x99, 0x93, 0x9F, 0x9F, 0x99, 0x99, 0xE7, 0xF3, 0x93, 0x9F, 0x88, 0x89, 0x99, 0x99, 0x99, 0x99, 0x99, 0xE7, 0x99, 0x99, 0x9C, 0x99, 0x99, 0xF9, 0xCF, 0x9F, 0xF3, 0xE7, 0xFF, 0xCF, 0xFF, 0x9F, 0xFF, 0xF9, 0xFF, 0xF1, 0xFF, 0x9F, 0xE7, 0xF9, 0x9F, 0xC7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x70, 0x00, 0x18, 0x66, 0xFF, 0x60, 0x0C, 0x3C, 0x18, 0x30, 0x0C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x06, 0x6E, 0x38, 0x06, 0x06, 0x1E, 0x7C, 0x60, 0x0C, 0x66, 0x66, 0x18, 0x18, 0x30, 0x7E, 0x0C, 0x06, 0x6E, 0x66, 0x66, 0x60, 0x66, 0x60, 0x60, 0x60, 0x66, 0x18, 0x0C, 0x78, 0x60, 0x7F, 0x7E, 0x66, 0x66, 0x66, 0x66, 0x60, 0x18, 0x66, 0x66, 0x63, 0x3C, 0x66, 0x0C, 0x30, 0x30, 0x0C, 0x3C, 0x00, 0x18, 0x3C, 0x60, 0x3C, 0x06, 0x3C, 0x18, 0x3E, 0x60, 0x00, 0x00, 0x60, 0x18, 0x66, 0x7C, 0x3C, 0x7C, 0x3E, 0x7C, 0x3E, 0x7E, 0x66, 0x66, 0x63, 0x66, 0x66, 0x7E, 0x18, 0x18, 0x18, 0x00, 0x30, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x1C, 0x38, 0x3F, 0xFC, 0x07, 0xE0, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0xE7, 0x99, 0x00, 0x9F, 0xF3, 0xC3, 0xE7, 0xCF, 0xF3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xF9, 0x91, 0xC7, 0xF9, 0xF9, 0xE1, 0x83, 0x9F, 0xF3, 0x99, 0x99, 0xE7, 0xE7, 0xCF, 0x81, 0xF3, 0xF9, 0x91, 0x99, 0x99, 0x9F, 0x99, 0x9F, 0x9F, 0x9F, 0x99, 0xE7, 0xF3, 0x87, 0x9F, 0x80, 0x81, 0x99, 0x99, 0x99, 0x99, 0x9F, 0xE7, 0x99, 0x99, 0x9C, 0xC3, 0x99, 0xF3, 0xCF, 0xCF, 0xF3, 0xC3, 0xFF, 0xE7, 0xC3, 0x9F, 0xC3, 0xF9, 0xC3, 0xE7, 0xC1, 0x9F, 0xFF, 0xFF, 0x9F, 0xE7, 0x99, 0x83, 0xC3, 0x83, 0xC1, 0x83, 0xC1, 0x81, 0x99, 0x99, 0x9C, 0x99, 0x99, 0x81, 0xE7, 0xE7, 0xE7, 0xFF, 0xCF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x38, 0x00, 0x18, 0x00, 0x66, 0x3C, 0x18, 0x38, 0x00, 0x30, 0x0C, 0xFF, 0x7E, 0x00, 0x7E, 0x00, 0x0C, 0x76, 0x18, 0x0C, 0x1C, 0x66, 0x06, 0x7C, 0x18, 0x3C, 0x3E, 0x00, 0x00, 0x60, 0x00, 0x06, 0x0C, 0x6E, 0x7E, 0x7C, 0x60, 0x66, 0x78, 0x78, 0x6E, 0x7E, 0x18, 0x0C, 0x70, 0x60, 0x6B, 0x7E, 0x66, 0x7C, 0x66, 0x7C, 0x3C, 0x18, 0x66, 0x66, 0x6B, 0x18, 0x3C, 0x18, 0x30, 0x18, 0x0C, 0x66, 0x00, 0x00, 0x06, 0x7C, 0x60, 0x3E, 0x66, 0x3E, 0x66, 0x7C, 0x38, 0x06, 0x6C, 0x18, 0x7F, 0x66, 0x66, 0x66, 0x66, 0x66, 0x60, 0x18, 0x66, 0x66, 0x6B, 0x3C, 0x66, 0x0C, 0x70, 0x18, 0x0E, 0x3B, 0x7F, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0xFF, 0x07, 0xE0, 0x0F, 0xF0, 0x1F, 0xF8, 0x0F, 0xF0, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x0F, 0xF0, 0xFF, 0xE7, 0xFF, 0x99, 0xC3, 0xE7, 0xC7, 0xFF, 0xCF, 0xF3, 0x00, 0x81, 0xFF, 0x81, 0xFF, 0xF3, 0x89, 0xE7, 0xF3, 0xE3, 0x99, 0xF9, 0x83, 0xE7, 0xC3, 0xC1, 0xFF, 0xFF, 0x9F, 0xFF, 0xF9, 0xF3, 0x91, 0x81, 0x83, 0x9F, 0x99, 0x87, 0x87, 0x91, 0x81, 0xE7, 0xF3, 0x8F, 0x9F, 0x94, 0x81, 0x99, 0x83, 0x99, 0x83, 0xC3, 0xE7, 0x99, 0x99, 0x94, 0xE7, 0xC3, 0xE7, 0xCF, 0xE7, 0xF3, 0x99, 0xFF, 0xFF, 0xF9, 0x83, 0x9F, 0xC1, 0x99, 0xC1, 0x99, 0x83, 0xC7, 0xF9, 0x93, 0xE7, 0x80, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9F, 0xE7, 0x99, 0x99, 0x94, 0xC3, 0x99, 0xF3, 0x8F, 0xE7, 0xF1, 0xC4, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x1C, 0x00, 0x00, 0x00, 0xFF, 0x06, 0x30, 0x67, 0x00, 0x30, 0x0C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x18, 0x66, 0x18, 0x30, 0x06, 0x7F, 0x06, 0x66, 0x18, 0x66, 0x06, 0x00, 0x00, 0x30, 0x7E, 0x0C, 0x18, 0x60, 0x66, 0x66, 0x60, 0x66, 0x60, 0x60, 0x66, 0x66, 0x18, 0x0C, 0x78, 0x60, 0x63, 0x6E, 0x66, 0x60, 0x66, 0x78, 0x06, 0x18, 0x66, 0x66, 0x7F, 0x3C, 0x18, 0x30, 0x30, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x3E, 0x66, 0x60, 0x66, 0x7E, 0x18, 0x66, 0x66, 0x18, 0x06, 0x78, 0x18, 0x7F, 0x66, 0x66, 0x66, 0x66, 0x60, 0x3C, 0x18, 0x66, 0x66, 0x7F, 0x18, 0x66, 0x18, 0x18, 0x18, 0x18, 0x6E, 0x7F, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0xFF, 0x0F, 0xF0, 0x07, 0xE0, 0x0F, 0xF0, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xF9, 0xCF, 0x98, 0xFF, 0xCF, 0xF3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xE7, 0x99, 0xE7, 0xCF, 0xF9, 0x80, 0xF9, 0x99, 0xE7, 0x99, 0xF9, 0xFF, 0xFF, 0xCF, 0x81, 0xF3, 0xE7, 0x9F, 0x99, 0x99, 0x9F, 0x99, 0x9F, 0x9F, 0x99, 0x99, 0xE7, 0xF3, 0x87, 0x9F, 0x9C, 0x91, 0x99, 0x9F, 0x99, 0x87, 0xF9, 0xE7, 0x99, 0x99, 0x80, 0xC3, 0xE7, 0xCF, 0xCF, 0xF3, 0xF3, 0xFF, 0xFF, 0xFF, 0xC1, 0x99, 0x9F, 0x99, 0x81, 0xE7, 0x99, 0x99, 0xE7, 0xF9, 0x87, 0xE7, 0x80, 0x99, 0x99, 0x99, 0x99, 0x9F, 0xC3, 0xE7, 0x99, 0x99, 0x80, 0xE7, 0x99, 0xE7, 0xE7, 0xE7, 0xE7, 0x91, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x0E, 0x00, 0x00, 0x00, 0x66, 0x7C, 0x66, 0x66, 0x00, 0x18, 0x18, 0x66, 0x18, 0x18, 0x00, 0x18, 0x30, 0x66, 0x18, 0x60, 0x66, 0x06, 0x66, 0x66, 0x18, 0x66, 0x66, 0x18, 0x18, 0x18, 0x00, 0x18, 0x00, 0x66, 0x66, 0x66, 0x66, 0x6C, 0x60, 0x60, 0x66, 0x66, 0x18, 0x6C, 0x6C, 0x60, 0x63, 0x66, 0x66, 0x60, 0x3C, 0x6C, 0x66, 0x18, 0x66, 0x3C, 0x77, 0x66, 0x18, 0x60, 0x30, 0x06, 0x0C, 0x00, 0x00, 0x00, 0x66, 0x66, 0x60, 0x66, 0x60, 0x18, 0x3E, 0x66, 0x18, 0x06, 0x6C, 0x18, 0x6B, 0x66, 0x66, 0x7C, 0x3E, 0x60, 0x06, 0x18, 0x66, 0x3C, 0x3E, 0x3C, 0x3E, 0x30, 0x18, 0x18, 0x18, 0x00, 0x30, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x38, 0x00, 0x00, 0x07, 0xE0, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x99, 0x83, 0x99, 0x99, 0xFF, 0xE7, 0xE7, 0x99, 0xE7, 0xE7, 0xFF, 0xE7, 0xCF, 0x99, 0xE7, 0x9F, 0x99, 0xF9, 0x99, 0x99, 0xE7, 0x99, 0x99, 0xE7, 0xE7, 0xE7, 0xFF, 0xE7, 0xFF, 0x99, 0x99, 0x99, 0x99, 0x93, 0x9F, 0x9F, 0x99, 0x99, 0xE7, 0x93, 0x93, 0x9F, 0x9C, 0x99, 0x99, 0x9F, 0xC3, 0x93, 0x99, 0xE7, 0x99, 0xC3, 0x88, 0x99, 0xE7, 0x9F, 0xCF, 0xF9, 0xF3, 0xFF, 0xFF, 0xFF, 0x99, 0x99, 0x9F, 0x99, 0x9F, 0xE7, 0xC1, 0x99, 0xE7, 0xF9, 0x93, 0xE7, 0x94, 0x99, 0x99, 0x83, 0xC1, 0x9F, 0xF9, 0xE7, 0x99, 0xC3, 0xC1, 0xC3, 0xC1, 0xCF, 0xE7, 0xE7, 0xE7, 0xFF, 0xCF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x07, 0x00, 0x18, 0x00, 0x66, 0x18, 0x46, 0x3F, 0x00, 0x0C, 0x30, 0x00, 0x00, 0x18, 0x00, 0x18, 0x60, 0x3C, 0x7E, 0x7E, 0x3C, 0x06, 0x3C, 0x3C, 0x18, 0x3C, 0x3C, 0x00, 0x18, 0x0E, 0x00, 0x70, 0x18, 0x3C, 0x66, 0x7C, 0x3C, 0x78, 0x7E, 0x60, 0x3C, 0x66, 0x3C, 0x38, 0x66, 0x7E, 0x63, 0x66, 0x3C, 0x60, 0x0E, 0x66, 0x3C, 0x18, 0x3C, 0x18, 0x63, 0x66, 0x18, 0x7E, 0x3C, 0x03, 0x3C, 0x00, 0x00, 0x00, 0x3E, 0x7C, 0x3C, 0x3E, 0x3C, 0x18, 0x06, 0x66, 0x3C, 0x06, 0x66, 0x3C, 0x63, 0x66, 0x3C, 0x60, 0x06, 0x60, 0x7C, 0x0E, 0x3E, 0x18, 0x36, 0x66, 0x0C, 0x7E, 0x0E, 0x18, 0x70, 0x00, 0x10, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x03, 0xC0, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xFF, 0x99, 0xE7, 0xB9, 0xC0, 0xFF, 0xF3, 0xCF, 0xFF, 0xFF, 0xE7, 0xFF, 0xE7, 0x9F, 0xC3, 0x81, 0x81, 0xC3, 0xF9, 0xC3, 0xC3, 0xE7, 0xC3, 0xC3, 0xFF, 0xE7, 0xF1, 0xFF, 0x8F, 0xE7, 0xC3, 0x99, 0x83, 0xC3, 0x87, 0x81, 0x9F, 0xC3, 0x99, 0xC3, 0xC7, 0x99, 0x81, 0x9C, 0x99, 0xC3, 0x9F, 0xF1, 0x99, 0xC3, 0xE7, 0xC3, 0xE7, 0x9C, 0x99, 0xE7, 0x81, 0xC3, 0xFC, 0xC3, 0xFF, 0xFF, 0xFF, 0xC1, 0x83, 0xC3, 0xC1, 0xC3, 0xE7, 0xF9, 0x99, 0xC3, 0xF9, 0x99, 0xC3, 0x9C, 0x99, 0xC3, 0x9F, 0xF9, 0x9F, 0x83, 0xF1, 0xC1, 0xE7, 0xC9, 0x99, 0xF3, 0x81, 0xF1, 0xE7, 0x8F, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x01, 0x80, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x0F, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x83, 0xFF, 0xFF, 0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x9F, 0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x87, 0xFF, 0xFF, 0xE7, 0xFF, 0xFF, 0xFF }; void setup() { noInterrupts(); // disable interrupts before messing around with timer registers DDRC = 0b00000000; // PORTC is always input PORTC = 0b00000000; DDRD = 0b11111111; // PORTD is always output PORTD = 0b00000000; DDRB = 0b00111100; // B0-1: terminal input bits 0-1, B2: VSYNC (timer1), B3: 74165 /PL (timer2 or by hand???), B4: HSync by hand inside ISR PORTB = 0b00011000; // HSYNC=1, /PE=1 GTCCR = 0b10000011; // set TSM, PSRSYNC und PSRASY to correlate all 3 timers // ***************************** // ***** Timer0: VGA HSYNC ***** // ***************************** TCNT0 = 68; // align VSYNC and HSYNC pulses TCCR0A = (1 << WGM01) | (0 << WGM00); // mode 2: Clear Timer on Compare Match (CTC) TCCR0B = (0 << WGM02) | (0 << CS02) | (1 << CS01) | (0 << CS00); // x8 prescaler -> 0.5µs OCR0A = 95; // 95, 79, 16MHz: 63, compare match register A (TOP) -> 32µs TIMSK0 = (1 << OCIE0A); // Output Compare Match A Interrupt Enable (not working: TOIE1 with ISR TIMER0_TOIE1_vect because it is already defined by timing functions) // ***************************** // ***** Timer1: VGA VSYNC ***** // ***************************** TCNT1 = 0; TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << WGM11) | (1 << WGM10); // mode 15 (Fast PWM), set OC1B on Compare Match, clear OC1B at BOTTOM, controlling OC1B pin 10 TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (0 << CS11) | (1 << CS10); // x1024 prescaler -> 64µs OCR1A = 389; // 389, 324, 16MHz: 259, compare match register A (TOP) -> 16.64ms OCR1B = 0; // compare match register B -> 64µs TIMSK1 = (1 << TOIE1); // enable timer overflow interrupt setting vlines = 0 // ************************************************ // ***** Timer2: only used for jitter control ***** // ************************************************ TCNT2 = 0; TCCR2A = (0< 62.5ns; OCR2A = 7; // compare match register A (TOP) -> 250ns TIMSK2 = 0; // no interrupts here GTCCR = 0; // clear TSM => all timers start synchronously interrupts(); UCSR0B = 0; // brute-force the USART off just in case... memset((void*)vram, 32, WIDTH * HEIGHT); // clear the entire VRAM } void loop() { static bool cursor = false; if ((frames & 63) == 32) { //if (show_cursor && (frames & 63) == 32) { if(!cursor){ cursor = true; if((vram[row][col] & 0b10000000) == 0) vram[row][col] |= 0b10000000; else vram[row][col] &= 0b01111111; } } if ((frames & 63) == 0) if (col < WIDTH) { if(cursor){ cursor = false; if((vram[row][col] & 0b10000000) > 0) vram[row][col] &= 0b01111111; else vram[row][col] |= 0b10000000; } } if (regout != regin) // was a character received { if (col < WIDTH & cursor) { cursor = false; if((vram[row][col] & 0b10000000) > 0) vram[row][col] &= 0b01111111; // restore character beneath the cursor BEFORE a possible scrolling happens else vram[row][col] |= 0b10000000; } do ProcessChar(reg[regout++]); while (regout != regin); // process the character } } int main() { setup(); while (true) loop(); } // enforce main() loop w/o serial handler ISR(TIMER1_OVF_vect) { vline = 0; frames++; } // timer1 overflow interrupt resets vline at HSYNC // ***************************************************************** // ***** ***** // ***** ANSI Terminal Implementation (add new functions here) ***** // ***** ***** // ***************************************************************** void ProcessChar(byte inbyte) // processes a character (accepts some VT52/GEMDOS ESC sequences, control chars, normal chars) { static bool reverse = false; static byte escvalid = 0; // Number of valid characters in escbuffer[] static byte esccount = 0; static byte escbuffer[5] = { 0,0,0,0,0 }; byte anz; byte r; frames = 30; // make cursor invisible for a very short time after receiving a character if (escvalid > 11) escvalid = 0; // Delete unprocessable ESC sequences and process this character normally if (esccount >= 5) escvalid = 0; // Delete unprocessable ESC sequences and process this character normally if (inbyte == 27) { escvalid = 1; esccount = 0; memset((void*)escbuffer, 0, 5); return; } // start new ESC sequence if (escvalid > 0) // AN ESC IS ALREADY ACTIVE { if (escvalid < 2) { if (inbyte == '[') escvalid++; // '[' MUST come as the 2nd character else escvalid = 0; } else if(inbyte == 0x20) // ignore espaces while in escape mode return; else // '\\e[' has already been received correctly ... { //escbuffer[escvalid++] = inbyte; // add another character escvalid++; switch (inbyte) // For each ESC sequence it must be checked whether the command is complete { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':{ // add numbers to ESC sequence escbuffer[esccount] *= 10; escbuffer[esccount] += inbyte - 48; break; } case ';': { //case '?': esccount++; break; } case 'A': // ESC[#A moves cursor up # lines { anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++) if (row != start) { row--; if (row < 0) row = HEIGHT-1; } escvalid = 0; break; } case 'B': // ESC[#B moves cursor down # lines { anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++) { byte oldrow = row; row++; if (row > HEIGHT-1) row = 0; if (row == start) row = oldrow; } escvalid = 0; break; } case 'C': // ESC[#C moves cursor right # columns { anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++) if (col < WIDTH-1) col++; escvalid = 0; break; } case 'D': // ESC[#D moves cursor left # columns { anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++) if (col > 0) col--; escvalid = 0; break; } case 'd': // move cursor to an absolute x position (left border: 1) { if (escbuffer[esccount] > 0) { row = start + min(HEIGHT-1, max(0, escbuffer[esccount]-1)); if (row > HEIGHT-1) row -=HEIGHT; } else row = start; escvalid = 0; break; } case 'E': // ESC[#E moves cursor to beginning of next line, # lines down { col = 0; anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++) { byte oldrow = row; row++; if (row > HEIGHT-1) row = 0; if (row == start) row = oldrow; } escvalid = 0; break; } case 'F': // ESC[#F moves cursor to beginning of previous line, # lines up { col = 0; anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++) if (row != start) { row--; if (row < 0) row = HEIGHT-1; } escvalid = 0; break; } case 'G': // ESC[#G moves cursor to column # { if (escbuffer[esccount] > 0) col = min(WIDTH-1, max(0, escbuffer[esccount]-1)); else col = 0; escvalid = 0; break; } case 'H': case 'f':{ // move cursor to upper left corner if(esccount == 1){ row = start + min(HEIGHT-1, max(0, escbuffer[0]-1)); if (row > HEIGHT-1) row -=HEIGHT; col = min(WIDTH-1, max(0, escbuffer[1]-1)); } else{ row = start; col = 0; } escvalid = 0; break; } /* case 'h':{ // Cursor visible //if (escbuffer[1] == 25) show_cursor = true; escvalid = 0; } */ case 'J': // clear VRAM from cursor onwards { anz = escbuffer[esccount]; switch(anz){ case 0:{ // erase from cursor until end of screen r = row; memset((void*)&vram[r++][col], 32, WIDTH-col); while (r != start && r < HEIGHT){ memset((void*)&vram[r++][0], 32, WIDTH); } break; } case 1:{ //erase from cursor to beginning of screen r = row; memset((void*)&vram[r][0], 32, col+1); if(r > 0){ do{ memset((void*)&vram[--r][0], 32, WIDTH); } while (r > 0); } break; } case 2:case 3:{ // erase entire screen start = 0; row = 0; col = 0; memset((void*)vram, 32, WIDTH * HEIGHT); // clear the entire VRAM break; } } escvalid = 0; break; } case 'K': // clear line from cursor onwards (does not move the cursor) anz = escbuffer[esccount]; switch(anz){ case 0:{ memset((void*)&vram[row][col], 32, WIDTH-col); // ESC[K = ESC[0K erase from cursor to end of line break; } case 1:{ // erase start of line to the cursor memset((void*)&vram[row][0], 32, col+1); break; } case 2:{ // erase the entire line memset((void*)&vram[row][0], 32, WIDTH); break; } } escvalid = 0; break; /* case 'l':{ // Cursor invisible if (escbuffer[1] == 25) show_cursor = false; escvalid = 0; } */ case 'm': { for(r = 0; r <=esccount; r++){ anz = escbuffer[r]; switch(anz){ case 0: case 27:{ //reset all modes / reset inverse mode reverse = false; break; } case 7:{ //set inverse/reverse mode reverse = true; break; } } } escvalid = 0; break; } case 'S':{ anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++){ memset((void*)&vram[start][0], 32, WIDTH); start++; if (start > HEIGHT-1) start = 0; row++; if (row > HEIGHT-1) row = 0; } escvalid = 0; break; } /* case 's':{ // save the cursor position saved_row = row; saved_col = col; } */ case 'T':{ anz = escbuffer[esccount] > 0 ? escbuffer[esccount] : 1; for (r = 0; r < anz; r++){ start--; if (start < 0) start = HEIGHT-1; row--; if (row < 0) row = HEIGHT-1; memset((void*)&vram[start][0], 32, WIDTH); } escvalid = 0; break; } /* case 'u':{ // move cursor to previously saved position row = start + min(HEIGHT-1, max(0, saved_row)); if (row > HEIGHT-1) row -=HEIGHT; col = min(WIDTH-1, max(0, saved_col)); escvalid = 0; break; } */ default: escvalid = 0; break; // all other chars -> end ESC sequence } } } else // NO ESC SEQUENCE => ORDINARY CHARACTER { switch (inbyte) { case '\\r': col = 0; break; // Catch the special character 'carriage return' case '\\n': // Catch the special character 'newline' col = 0; if (row < HEIGHT-1) row++; else row=0; if (row == start) { memset((void*)&vram[row][0], 32, WIDTH); start++; if (start > HEIGHT-1) start = 0; } break; case 8: // Catch the special character 'BACKSPACE' if (col > 0) vram[row][--col] =32; else if (row != start) { if (row > 0) row--; else row = HEIGHT-1; vram[row][WIDTH-1] = 32; col = WIDTH-1; } break; default: if (inbyte >= 32) // start of printable characters { vram[row][col++] = (reverse ? inbyte | 0b10000000 : inbyte); // Output characters in the terminal if (col > WIDTH-1) { col = 0; if (row < HEIGHT-1) row++; else row=0; if (row == start) { memset((void*)&vram[row][0], 32, WIDTH); start++; if (start > HEIGHT-1) start = 0; } } } break; } } } /* ----------- MIT License ----------- Copyright (c) 2021 Carsten Herting Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ ",16310,True,3576.547149833736,median "/* LSM9DS1_MS5611_t3 Basic Example Code by: Kris Winer date: November 1, 2014 license: Beerware - Use this code however you'd like. If you find it useful you can buy me a beer some time. Demonstrate basic LSM9DS1 functionality including parameterizing the register addresses, initializing the sensor, getting properly scaled accelerometer, gyroscope, and magnetometer data out. Added display functions to allow display to on breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the Teensy 3.1. This sketch is intended specifically for the LSM9DS1+MS5611 Add-on shield for the Teensy 3.1. It uses SDA/SCL on pins 17/16, respectively, and it uses the Teensy 3.1-specific Wire library i2c_t3.h. The MS5611 is a simple but high resolution pressure sensor, which can be used in its high resolution mode but with power consumption od 20 microAmp, or in a lower resolution mode with power consumption of only 1 microAmp. The choice will depend on the application. SDA and SCL should have external pull-up resistors (to 3.3V). 4K7 resistors are on the LSM9DS1+MS5611 Teensy 3.1 add-on shield/breakout board. Hardware setup: LSM9DS1Breakout --------- Arduino VDD ---------------------- 3.3V VDDI --------------------- 3.3V SDA ----------------------- A4 SCL ----------------------- A5 GND ---------------------- GND Note: The LSM9DS1 is an I2C sensor and can use the Arduino Wire library. Because the sensor is not 5V tolerant, we are using either a 3.3 V 8 MHz Pro Mini or a 3.3 V Teensy 3.1. We have disabled the internal pull-ups used by the Wire library in the Wire.h/twi.c utility file. We are also using the 400 kHz fast I2C mode by setting the TWI_FREQ to 400000L /twi.h utility file. */ #include ""Wire.h"" //#include #include //#include //#include // Using NOKIA 5110 monochrome 84 x 48 pixel display // pin 7 - Serial clock out (SCLK) // pin 6 - Serial data out (DIN) // pin 5 - Data/Command select (D/C) // pin 3 - LCD chip select (SCE) // pin 4 - LCD reset (RST) //Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 3, 4); // See MS5611-02BA03 Low Voltage Barometric Pressure Sensor Data Sheet #define MS5611_RESET 0x1E #define MS5611_CONVERT_D1 0x40 #define MS5611_CONVERT_D2 0x50 #define MS5611_ADC_READ 0x00 // See also LSM9DS1 Register Map and Descriptions, http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/DM00103319.pdf // // Accelerometer and Gyroscope registers #define LSM9DS1XG_ACT_THS 0x04 #define LSM9DS1XG_ACT_DUR 0x05 #define LSM9DS1XG_INT_GEN_CFG_XL 0x06 #define LSM9DS1XG_INT_GEN_THS_X_XL 0x07 #define LSM9DS1XG_INT_GEN_THS_Y_XL 0x08 #define LSM9DS1XG_INT_GEN_THS_Z_XL 0x09 #define LSM9DS1XG_INT_GEN_DUR_XL 0x0A #define LSM9DS1XG_REFERENCE_G 0x0B #define LSM9DS1XG_INT1_CTRL 0x0C #define LSM9DS1XG_INT2_CTRL 0x0D #define LSM9DS1XG_WHO_AM_I 0x0F // should return 0x68 #define LSM9DS1XG_CTRL_REG1_G 0x10 #define LSM9DS1XG_CTRL_REG2_G 0x11 #define LSM9DS1XG_CTRL_REG3_G 0x12 #define LSM9DS1XG_ORIENT_CFG_G 0x13 #define LSM9DS1XG_INT_GEN_SRC_G 0x14 #define LSM9DS1XG_OUT_TEMP_L 0x15 #define LSM9DS1XG_OUT_TEMP_H 0x16 #define LSM9DS1XG_STATUS_REG 0x17 #define LSM9DS1XG_OUT_X_L_G 0x18 #define LSM9DS1XG_OUT_X_H_G 0x19 #define LSM9DS1XG_OUT_Y_L_G 0x1A #define LSM9DS1XG_OUT_Y_H_G 0x1B #define LSM9DS1XG_OUT_Z_L_G 0x1C #define LSM9DS1XG_OUT_Z_H_G 0x1D #define LSM9DS1XG_CTRL_REG4 0x1E #define LSM9DS1XG_CTRL_REG5_XL 0x1F #define LSM9DS1XG_CTRL_REG6_XL 0x20 #define LSM9DS1XG_CTRL_REG7_XL 0x21 #define LSM9DS1XG_CTRL_REG8 0x22 #define LSM9DS1XG_CTRL_REG9 0x23 #define LSM9DS1XG_CTRL_REG10 0x24 #define LSM9DS1XG_INT_GEN_SRC_XL 0x26 //#define LSM9DS1XG_STATUS_REG 0x27 // duplicate of 0x17! #define LSM9DS1XG_OUT_X_L_XL 0x28 #define LSM9DS1XG_OUT_X_H_XL 0x29 #define LSM9DS1XG_OUT_Y_L_XL 0x2A #define LSM9DS1XG_OUT_Y_H_XL 0x2B #define LSM9DS1XG_OUT_Z_L_XL 0x2C #define LSM9DS1XG_OUT_Z_H_XL 0x2D #define LSM9DS1XG_FIFO_CTRL 0x2E #define LSM9DS1XG_FIFO_SRC 0x2F #define LSM9DS1XG_INT_GEN_CFG_G 0x30 #define LSM9DS1XG_INT_GEN_THS_XH_G 0x31 #define LSM9DS1XG_INT_GEN_THS_XL_G 0x32 #define LSM9DS1XG_INT_GEN_THS_YH_G 0x33 #define LSM9DS1XG_INT_GEN_THS_YL_G 0x34 #define LSM9DS1XG_INT_GEN_THS_ZH_G 0x35 #define LSM9DS1XG_INT_GEN_THS_ZL_G 0x36 #define LSM9DS1XG_INT_GEN_DUR_G 0x37 // // Magnetometer registers #define LSM9DS1M_OFFSET_X_REG_L_M 0x05 #define LSM9DS1M_OFFSET_X_REG_H_M 0x06 #define LSM9DS1M_OFFSET_Y_REG_L_M 0x07 #define LSM9DS1M_OFFSET_Y_REG_H_M 0x08 #define LSM9DS1M_OFFSET_Z_REG_L_M 0x09 #define LSM9DS1M_OFFSET_Z_REG_H_M 0x0A #define LSM9DS1M_WHO_AM_I 0x0F // should be 0x3D #define LSM9DS1M_CTRL_REG1_M 0x20 #define LSM9DS1M_CTRL_REG2_M 0x21 #define LSM9DS1M_CTRL_REG3_M 0x22 #define LSM9DS1M_CTRL_REG4_M 0x23 #define LSM9DS1M_CTRL_REG5_M 0x24 #define LSM9DS1M_STATUS_REG_M 0x27 #define LSM9DS1M_OUT_X_L_M 0x28 #define LSM9DS1M_OUT_X_H_M 0x29 #define LSM9DS1M_OUT_Y_L_M 0x2A #define LSM9DS1M_OUT_Y_H_M 0x2B #define LSM9DS1M_OUT_Z_L_M 0x2C #define LSM9DS1M_OUT_Z_H_M 0x2D #define LSM9DS1M_INT_CFG_M 0x30 #define LSM9DS1M_INT_SRC_M 0x31 #define LSM9DS1M_INT_THS_L_M 0x32 #define LSM9DS1M_INT_THS_H_M 0x33 // Using the LSM9DS1+MS5611 Teensy 3.1 Add-On shield, ADO is set to 1 // Seven-bit device address of accel/gyro is 110101 for ADO = 0 and 110101 for ADO = 1 #define ADO 1 #if ADO #define LSM9DS1XG_ADDRESS 0x6B // Device address when ADO = 1 #define LSM9DS1M_ADDRESS 0x1E // Address of magnetometer #define MS5611_ADDRESS 0x77 // Address of altimeter #else #define LSM9DS1XG_ADDRESS 0x6A // Device address when ADO = 0 #define LSM9DS1M_ADDRESS 0x1D // Address of magnetometer #define MS5611_ADDRESS 0x77 // Address of altimeter #endif #define SerialDebug true // set to true to get Serial output for debugging // Set initial input parameters enum Ascale { // set of allowable accel full scale settings AFS_2G = 0, AFS_16G, AFS_4G, AFS_8G }; enum Aodr { // set of allowable gyro sample rates AODR_PowerDown = 0, AODR_10Hz, AODR_50Hz, AODR_119Hz, AODR_238Hz, AODR_476Hz, AODR_952Hz }; enum Abw { // set of allowable accewl bandwidths ABW_408Hz = 0, ABW_211Hz, ABW_105Hz, ABW_50Hz }; enum Gscale { // set of allowable gyro full scale settings GFS_245DPS = 0, GFS_500DPS, GFS_NoOp, GFS_2000DPS }; enum Godr { // set of allowable gyro sample rates GODR_PowerDown = 0, GODR_14_9Hz, GODR_59_5Hz, GODR_119Hz, GODR_238Hz, GODR_476Hz, GODR_952Hz }; enum Gbw { // set of allowable gyro data bandwidths GBW_low = 0, // 14 Hz at Godr = 238 Hz, 33 Hz at Godr = 952 Hz GBW_med, // 29 Hz at Godr = 238 Hz, 40 Hz at Godr = 952 Hz GBW_high, // 63 Hz at Godr = 238 Hz, 58 Hz at Godr = 952 Hz GBW_highest // 78 Hz at Godr = 238 Hz, 100 Hz at Godr = 952 Hz }; enum Mscale { // set of allowable mag full scale settings MFS_4G = 0, MFS_8G, MFS_12G, MFS_16G }; enum Mmode { MMode_LowPower = 0, MMode_MedPerformance, MMode_HighPerformance, MMode_UltraHighPerformance }; enum Modr { // set of allowable mag sample rates MODR_0_625Hz = 0, MODR_1_25Hz, MODR_2_5Hz, MODR_5Hz, MODR_10Hz, MODR_20Hz, MODR_80Hz }; #define ADC_256 0x00 // define pressure and temperature conversion rates #define ADC_512 0x02 #define ADC_1024 0x04 #define ADC_2048 0x06 #define ADC_4096 0x08 #define ADC_D1 0x40 #define ADC_D2 0x50 // Specify sensor full scale uint8_t OSR = ADC_4096; // set pressure amd temperature oversample rate uint8_t Gscale = GFS_245DPS; // gyro full scale uint8_t Godr = GODR_238Hz; // gyro data sample rate uint8_t Gbw = GBW_med; // gyro data bandwidth uint8_t Ascale = AFS_2G; // accel full scale uint8_t Aodr = AODR_238Hz; // accel data sample rate uint8_t Abw = ABW_50Hz; // accel data bandwidth uint8_t Mscale = MFS_4G; // mag full scale uint8_t Modr = MODR_10Hz; // mag data sample rate uint8_t Mmode = MMode_HighPerformance; // magnetometer operation mode float aRes, gRes, mRes; // scale resolutions per LSB for the sensors // Pin definitions int myLed = 13; uint16_t Pcal[8]; // calibration constants from MS5611 PROM registers unsigned char nCRC; // calculated check sum to ensure PROM integrity uint32_t D_1 = 0, D_2 = 0; // raw MS5611 pressure and temperature data double dT, OFFSET, SENS, T2, OFFSET2, SENS2; // First order and second order corrections for raw S5637 temperature and pressure data int16_t accelCount[3], gyroCount[3], magCount[3]; // Stores the 16-bit signed accelerometer, gyro, and mag sensor output float gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0}, magBias[3] = {0, 0, 0}; // Bias corrections for gyro, accelerometer, and magnetometer int16_t tempCount; // temperature raw count output float temperature; // Stores the LSM9DS1gyro internal chip temperature in degrees Celsius double Temperature, Pressure; // stores MS5611 pressures sensor pressure and temperature // global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System) float GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error in rads/s (start at 40 deg/s) float GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s) // There is a tradeoff in the beta parameter between accuracy and response speed. // In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy. // However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion. // Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car! // By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec // I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense; // the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy. // In any case, this is the free parameter in the Madgwick filtering and fusion scheme. float beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value #define Kp 2.0f * 5.0f // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral #define Ki 0.0f uint32_t delt_t = 0, count = 0, sumCount = 0; // used to control display output rate float pitch, yaw, roll; float deltat = 0.0f, sum = 0.0f; // integration interval for both filter schemes uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval uint32_t Now = 0; // used to calculate integration interval float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values float q[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // vector to hold quaternion float eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for Mahony method void setup() { Wire1.begin(); // TWBR = 12; // 400 kbit/sec I2C speed for Pro Mini // Setup for Master mode, pins 16/17, external pullups, 400kHz for Teensy 3.1 //Wire.begin(I2C_MASTER, 0x00, I2C_PINS_16_17, I2C_PULLUP_EXT, I2C_RATE_400); // reset writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG8, 0x05); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG2_M, 0x0c); delay(100); Serial.begin(38400); // Initialize LED pin pinMode(myLed, OUTPUT); digitalWrite(myLed, HIGH); /* display.begin(); // Initialize the display display.setContrast(40); // Set the contrast // Start device display with ID of sensor display.clearDisplay(); display.setTextSize(2); display.setCursor(0,0); display.print(""LSM9DS1""); display.setTextSize(1); display.setCursor(0, 20); display.print(""9-DOF 16-bit""); display.setCursor(0, 30); display.print(""motion sensor""); display.setCursor(20,40); display.print(""60 ug LSB""); display.display(); delay(1000); // Set up for data display display.setTextSize(1); // Set text size to normal, 2 is twice normal etc. display.setTextColor(BLACK); // Set pixel color; 1 on the monochrome screen display.clearDisplay(); // clears the screen and buffer */ // Read the WHO_AM_I registers, this is a good test of communication Serial.println(""LSM9DS1 9-axis motion sensor...""); byte c = readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_WHO_AM_I); // Read WHO_AM_I register for LSM9DS1 accel/gyro Serial.print(""LSM9DS1 accel/gyro""); Serial.print(""I AM ""); Serial.print(c, HEX); Serial.print("" I should be ""); Serial.println(0x68, HEX); byte d = readByte(LSM9DS1M_ADDRESS, LSM9DS1M_WHO_AM_I); // Read WHO_AM_I register for LSM9DS1 magnetometer Serial.print(""LSM9DS1 magnetometer""); Serial.print(""I AM ""); Serial.print(d, HEX); Serial.print("" I should be ""); Serial.println(0x3D, HEX); /* display.setCursor(20,0); display.print(""LSM9DS1""); display.setCursor(0,10); display.print(""I AM""); display.print(c, HEX); display.setCursor(0,20); display.print(""I Should Be""); display.print(0x68, HEX); display.setCursor(0,30); display.print(""I AM""); display.print(d, HEX); display.setCursor(0,40); display.print(""I Should Be""); display.print(0x3D, HEX); display.display(); delay(1000); */ if (c == 0x68 && d == 0x3D) // WHO_AM_I should always be 0x0E for the accel/gyro and 0x3C for the mag { Serial.println(""LSM9DS1 is online...""); // get sensor resolutions, only need to do this once getAres(); getGres(); getMres(); Serial.print(""accel sensitivity is ""); Serial.print(1./(1000.*aRes)); Serial.println("" LSB/mg""); Serial.print(""gyro sensitivity is ""); Serial.print(1./(1000.*gRes)); Serial.println("" LSB/mdps""); Serial.print(""mag sensitivity is ""); Serial.print(1./(1000.*mRes)); Serial.println("" LSB/mGauss""); Serial.println(""Perform gyro and accel self test""); selftestLSM9DS1(); // check function of gyro and accelerometer via self test Serial.println("" Calibrate gyro and accel""); accelgyrocalLSM9DS1(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers Serial.println(""accel biases (mg)""); Serial.println(1000.*accelBias[0]); Serial.println(1000.*accelBias[1]); Serial.println(1000.*accelBias[2]); Serial.println(""gyro biases (dps)""); Serial.println(gyroBias[0]); Serial.println(gyroBias[1]); Serial.println(gyroBias[2]); magcalLSM9DS1(magBias); Serial.println(""mag biases (mG)""); Serial.println(1000.*magBias[0]); Serial.println(1000.*magBias[1]); Serial.println(1000.*magBias[2]); delay(2000); // add delay to see results before serial spew of data initLSM9DS1(); Serial.println(""LSM9DS1 initialized for active data mode....""); // Initialize device for active mode read of acclerometer, gyroscope, and temperature /* display.clearDisplay(); display.setCursor(0, 0); display.print(""LSM9DS1bias""); display.setCursor(0, 8); display.print("" x y z ""); display.setCursor(0, 16); display.print((int)(1000*accelBias[0])); display.setCursor(24, 16); display.print((int)(1000*accelBias[1])); display.setCursor(48, 16); display.print((int)(1000*accelBias[2])); display.setCursor(72, 16); display.print(""mg""); display.setCursor(0, 24); display.print(gyroBias[0], 1); display.setCursor(24, 24); display.print(gyroBias[1], 1); display.setCursor(48, 24); display.print(gyroBias[2], 1); display.setCursor(66, 24); display.print(""o/s""); display.display(); delay(1000); */ } else { Serial.print(""Could not connect to LSM9DS1: 0x""); Serial.println(c, HEX); while(1) ; // Loop forever if communication doesn't happen } } void loop() { if (readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_STATUS_REG) & 0x01) { // check if new accel data is ready readAccelData(accelCount); // Read the x/y/z adc values // Now we'll calculate the accleration value into actual g's ax = (float)accelCount[0]*aRes - accelBias[0]; // get actual g value, this depends on scale being set ay = (float)accelCount[1]*aRes - accelBias[1]; az = (float)accelCount[2]*aRes - accelBias[2]; } if (readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_STATUS_REG) & 0x02) { // check if new gyro data is ready readGyroData(gyroCount); // Read the x/y/z adc values // Calculate the gyro value into actual degrees per second gx = (float)gyroCount[0]*gRes - gyroBias[0]; // get actual gyro value, this depends on scale being set gy = (float)gyroCount[1]*gRes - gyroBias[1]; gz = (float)gyroCount[2]*gRes - gyroBias[2]; } if (readByte(LSM9DS1M_ADDRESS, LSM9DS1M_STATUS_REG_M) & 0x08) { // check if new mag data is ready readMagData(magCount); // Read the x/y/z adc values // Calculate the magnetometer values in milliGauss // Include factory calibration per data sheet and user environmental corrections mx = (float)magCount[0]*mRes; // - magBias[0]; // get actual magnetometer value, this depends on scale being set my = (float)magCount[1]*mRes; // - magBias[1]; mz = (float)magCount[2]*mRes; // - magBias[2]; } Now = micros(); deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update lastUpdate = Now; sum += deltat; // sum for averaging filter update rate sumCount++; // Sensors x, y, and z axes of the accelerometer and gyro are aligned. The magnetometer // the magnetometer z-axis (+ up) is aligned with the z-axis (+ up) of accelerometer and gyro, but the magnetometer // x-axis is aligned with the -x axis of the gyro and the magnetometer y axis is aligned with the y axis of the gyro! // We have to make some allowance for this orientation mismatch in feeding the output to the quaternion filter. // For the LSM9DS1, we have chosen a magnetic rotation that keeps the sensor forward along the x-axis just like // in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention. // This is ok by aircraft orientation standards! // Pass gyro rate as rad/s MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, -mx, my, mz); // MahonyQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, -mx, my, mz); // Serial print and/or display at 0.5 s rate independent of data rates delt_t = millis() - count; if (delt_t > 50) { // update LCD once per half-second independent of read rate if(SerialDebug) { // Serial.print(""ax = ""); Serial.print((int)1000*ax); // Serial.print("" ay = ""); Serial.print((int)1000*ay); // Serial.print("" az = ""); Serial.print((int)1000*az); Serial.println("" mg""); // Serial.print(""gx = ""); Serial.print( gx, 2); // Serial.print("" gy = ""); Serial.print( gy, 2); // Serial.print("" gz = ""); Serial.print( gz, 2); Serial.println("" deg/s""); // Serial.print(""mx = ""); Serial.print( (int)1000*mx ); // Serial.print("" my = ""); Serial.print( (int)1000*my ); // Serial.print("" mz = ""); Serial.print( (int)1000*mz ); Serial.println("" mG""); // Serial.print(""q0 = ""); Serial.print(q[0]); // Serial.print("" ;qx = ""); Serial.print(q[1]); // Serial.print("" ;qy = ""); Serial.print(q[2]); // Serial.print("" ;qz = ""); Serial.println(q[3]); // Formated for postprocessing in touchdesigner/maxmsp Serial.print(q[0]); Serial.print("";""); Serial.print(q[1]); Serial.print("";""); Serial.print(q[2]); Serial.print("";""); Serial.println(q[3]); } tempCount = readTempData(); // Read the gyro adc values temperature = ((float) tempCount/256. + 25.0); // Gyro chip temperature in degrees Centigrade // Print temperature in degrees Centigrade // Serial.print(""Gyro temperature is ""); Serial.print(temperature, 1); Serial.println("" degrees C""); // Print T values to tenths of s degree C // Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation. // In this coordinate system, the positive z-axis is down toward Earth. // Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise. // Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative. // Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll. // These arise from the definition of the homogeneous rotation matrix constructed from quaternions. // Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be // applied in the correct order which for this configuration is yaw, pitch, and then roll. // For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links. yaw = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]); pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2])); roll = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]); pitch *= 180.0f / PI; yaw *= 180.0f / PI; yaw -= 13.22f; // Declination at Los Altos, California is ~13 degrees 13 minutes on 2020-07-19 roll *= 180.0f / PI; // if(SerialDebug) { // Serial.print(""Yaw, Pitch, Roll: ""); // Serial.print(yaw, 2); // Serial.print("", ""); // Serial.print(pitch, 2); // Serial.print("", ""); // Serial.println(roll, 2); // // Serial.print(""rate = ""); Serial.print((float)sumCount/sum, 2); Serial.println("" Hz\\n""); // } /* display.clearDisplay(); display.setCursor(0, 0); display.print("" x y z ""); display.setCursor(0, 8); display.print((int)(1000*ax)); display.setCursor(24, 8); display.print((int)(1000*ay)); display.setCursor(48, 8); display.print((int)(1000*az)); display.setCursor(72, 8); display.print(""mg""); display.setCursor(0, 16); display.print((int)(gx)); display.setCursor(24, 16); display.print((int)(gy)); display.setCursor(48, 16); display.print((int)(gz)); display.setCursor(66, 16); display.print(""o/s""); display.setCursor(0, 24); display.print((int)(mx)); display.setCursor(24, 24); display.print((int)(my)); display.setCursor(48, 24); display.print((int)(mz)); display.setCursor(72, 24); display.print(""mG""); display.setCursor(0, 32); display.print((int)(yaw)); display.setCursor(24, 32); display.print((int)(pitch)); display.setCursor(48, 32); display.print((int)(roll)); display.setCursor(66, 32); display.print(""ypr""); */ // With these settings the filter is updating at a ~145 Hz rate using the Madgwick scheme and // >200 Hz using the Mahony scheme even though the display refreshes at only 2 Hz. // The filter update rate is determined mostly by the mathematical steps in the respective algorithms, // the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR: // an ODR of 10 Hz for the magnetometer produce the above rates, maximum magnetometer ODR of 100 Hz produces // filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony schemes, respectively. // This is presumably because the magnetometer read takes longer than the gyro or accelerometer reads. // This filter update rate should be fast enough to maintain accurate platform orientation for // stabilization control of a fast-moving robot or quadcopter. Compare to the update rate of 200 Hz // produced by the on-board Digital Motion Processor of Invensense's MPU6050 6 DoF and MPU9150 9DoF sensors. // The 3.3 V 8 MHz Pro Mini is doing pretty well! /* display.setCursor(0, 40); display.print(altitude, 0); display.print(""ft""); display.setCursor(68, 0); display.print(9.*Temperature/5. + 32., 0); display.setCursor(42, 40); display.print((float) sumCount / (1000.*sum), 2); display.print(""kHz""); display.display(); */ digitalWrite(myLed, !digitalRead(myLed)); count = millis(); sumCount = 0; sum = 0; } } //=================================================================================================================== //====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data //=================================================================================================================== void getMres() { switch (Mscale) { // Possible magnetometer scales (and their register bit settings) are: // 4 Gauss (00), 8 Gauss (01), 12 Gauss (10) and 16 Gauss (11) case MFS_4G: mRes = 4.0/32768.0; break; case MFS_8G: mRes = 8.0/32768.0; break; case MFS_12G: mRes = 12.0/32768.0; break; case MFS_16G: mRes = 16.0/32768.0; break; } } void getGres() { switch (Gscale) { // Possible gyro scales (and their register bit settings) are: // 245 DPS (00), 500 DPS (01), and 2000 DPS (11). case GFS_245DPS: gRes = 245.0/32768.0; break; case GFS_500DPS: gRes = 500.0/32768.0; break; case GFS_2000DPS: gRes = 2000.0/32768.0; break; } } void getAres() { switch (Ascale) { // Possible accelerometer scales (and their register bit settings) are: // 2 Gs (00), 16 Gs (01), 4 Gs (10), and 8 Gs (11). case AFS_2G: aRes = 2.0/32768.0; break; case AFS_16G: aRes = 16.0/32768.0; break; case AFS_4G: aRes = 4.0/32768.0; break; case AFS_8G: aRes = 8.0/32768.0; break; } } void readAccelData(int16_t * destination) { uint8_t rawData[6]; // x/y/z accel register data stored here readBytes(LSM9DS1XG_ADDRESS, LSM9DS1XG_OUT_X_L_XL, 6, &rawData[0]); // Read the six raw data registers into data array destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; } void readGyroData(int16_t * destination) { uint8_t rawData[6]; // x/y/z gyro register data stored here readBytes(LSM9DS1XG_ADDRESS, LSM9DS1XG_OUT_X_L_G, 6, &rawData[0]); // Read the six raw data registers sequentially into data array destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; } void readMagData(int16_t * destination) { uint8_t rawData[6]; // x/y/z gyro register data stored here readBytes(LSM9DS1M_ADDRESS, LSM9DS1M_OUT_X_L_M, 6, &rawData[0]); // Read the six raw data registers sequentially into data array destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; // Data stored as little Endian destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; } int16_t readTempData() { uint8_t rawData[2]; // x/y/z gyro register data stored here readBytes(LSM9DS1XG_ADDRESS, LSM9DS1XG_OUT_TEMP_L, 2, &rawData[0]); // Read the two raw data registers sequentially into data array return (((int16_t)rawData[1] << 8) | rawData[0]); // Turn the MSB and LSB into a 16-bit signed value } void initLSM9DS1() { // enable the 3-axes of the gyroscope writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG4, 0x38); // configure the gyroscope writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG1_G, Godr << 5 | Gscale << 3 | Gbw); delay(200); // enable the three axes of the accelerometer writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG5_XL, 0x38); // configure the accelerometer-specify bandwidth selection with Abw writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG6_XL, Aodr << 5 | Ascale << 3 | 0x04 |Abw); delay(200); // enable block data update, allow auto-increment during multiple byte read writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG8, 0x44); // configure the magnetometer-enable temperature compensation of mag data writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG1_M, 0x80 | Mmode << 5 | Modr << 2); // select x,y-axis mode writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG2_M, Mscale << 5 ); // select mag full scale writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG3_M, 0x00 ); // continuous conversion mode writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG4_M, Mmode << 2 ); // select z-axis mode writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG5_M, 0x40 ); // select block update mode } void selftestLSM9DS1() { float accel_noST[3] = {0., 0., 0.}, accel_ST[3] = {0., 0., 0.}; float gyro_noST[3] = {0., 0., 0.}, gyro_ST[3] = {0., 0., 0.}; writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG10, 0x00); // disable self test accelgyrocalLSM9DS1(gyro_noST, accel_noST); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG10, 0x05); // enable gyro/accel self test accelgyrocalLSM9DS1(gyro_ST, accel_ST); float gyrodx = (gyro_ST[0] - gyro_noST[0]); float gyrody = (gyro_ST[1] - gyro_noST[1]); float gyrodz = (gyro_ST[2] - gyro_noST[2]); Serial.println(""Gyro self-test results: ""); Serial.print(""x-axis = ""); Serial.print(gyrodx); Serial.print("" dps""); Serial.println("" should be between 20 and 250 dps""); Serial.print(""y-axis = ""); Serial.print(gyrody); Serial.print("" dps""); Serial.println("" should be between 20 and 250 dps""); Serial.print(""z-axis = ""); Serial.print(gyrodz); Serial.print("" dps""); Serial.println("" should be between 20 and 250 dps""); float accdx = 1000.*(accel_ST[0] - accel_noST[0]); float accdy = 1000.*(accel_ST[1] - accel_noST[1]); float accdz = 1000.*(accel_ST[2] - accel_noST[2]); Serial.println(""Accelerometer self-test results: ""); Serial.print(""x-axis = ""); Serial.print(accdx); Serial.print("" mg""); Serial.println("" should be between 60 and 1700 mg""); Serial.print(""y-axis = ""); Serial.print(accdy); Serial.print("" mg""); Serial.println("" should be between 60 and 1700 mg""); Serial.print(""z-axis = ""); Serial.print(accdz); Serial.print("" mg""); Serial.println("" should be between 60 and 1700 mg""); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG10, 0x00); // disable self test delay(200); } // Function which accumulates gyro and accelerometer data after device initialization. It calculates the average // of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers. void accelgyrocalLSM9DS1(float * dest1, float * dest2) { uint8_t data[6] = {0, 0, 0, 0, 0, 0}; int32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0}; uint16_t samples, ii; // enable the 3-axes of the gyroscope writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG4, 0x38); // configure the gyroscope writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG1_G, Godr << 5 | Gscale << 3 | Gbw); delay(200); // enable the three axes of the accelerometer writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG5_XL, 0x38); // configure the accelerometer-specify bandwidth selection with Abw writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG6_XL, Aodr << 5 | Ascale << 3 | 0x04 |Abw); delay(200); // enable block data update, allow auto-increment during multiple byte read writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG8, 0x44); // First get gyro bias byte c = readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9, c | 0x02); // Enable gyro FIFO delay(50); // Wait for change to take effect writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_FIFO_CTRL, 0x20 | 0x1F); // Enable gyro FIFO stream mode and set watermark at 32 samples delay(1000); // delay 1000 milliseconds to collect FIFO samples samples = (readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_FIFO_SRC) & 0x2F); // Read number of stored samples for(ii = 0; ii < samples ; ii++) { // Read the gyro data stored in the FIFO int16_t gyro_temp[3] = {0, 0, 0}; readBytes(LSM9DS1XG_ADDRESS, LSM9DS1XG_OUT_X_L_G, 6, &data[0]); gyro_temp[0] = (int16_t) (((int16_t)data[1] << 8) | data[0]); // Form signed 16-bit integer for each sample in FIFO gyro_temp[1] = (int16_t) (((int16_t)data[3] << 8) | data[2]); gyro_temp[2] = (int16_t) (((int16_t)data[5] << 8) | data[4]); gyro_bias[0] += (int32_t) gyro_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases gyro_bias[1] += (int32_t) gyro_temp[1]; gyro_bias[2] += (int32_t) gyro_temp[2]; } gyro_bias[0] /= samples; // average the data gyro_bias[1] /= samples; gyro_bias[2] /= samples; dest1[0] = (float)gyro_bias[0]*gRes; // Properly scale the data to get deg/s dest1[1] = (float)gyro_bias[1]*gRes; dest1[2] = (float)gyro_bias[2]*gRes; c = readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9, c & ~0x02); //Disable gyro FIFO delay(50); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_FIFO_CTRL, 0x00); // Enable gyro bypass mode // now get the accelerometer bias c = readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9, c | 0x02); // Enable accel FIFO delay(50); // Wait for change to take effect writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_FIFO_CTRL, 0x20 | 0x1F); // Enable accel FIFO stream mode and set watermark at 32 samples delay(1000); // delay 1000 milliseconds to collect FIFO samples samples = (readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_FIFO_SRC) & 0x2F); // Read number of stored samples for(ii = 0; ii < samples ; ii++) { // Read the accel data stored in the FIFO int16_t accel_temp[3] = {0, 0, 0}; readBytes(LSM9DS1XG_ADDRESS, LSM9DS1XG_OUT_X_L_XL, 6, &data[0]); accel_temp[0] = (int16_t) (((int16_t)data[1] << 8) | data[0]); // Form signed 16-bit integer for each sample in FIFO accel_temp[1] = (int16_t) (((int16_t)data[3] << 8) | data[2]); accel_temp[2] = (int16_t) (((int16_t)data[5] << 8) | data[4]); accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases accel_bias[1] += (int32_t) accel_temp[1]; accel_bias[2] += (int32_t) accel_temp[2]; } accel_bias[0] /= samples; // average the data accel_bias[1] /= samples; accel_bias[2] /= samples; if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) (1.0/aRes);} // Remove gravity from the z-axis accelerometer bias calculation else {accel_bias[2] += (int32_t) (1.0/aRes);} dest2[0] = (float)accel_bias[0]*aRes; // Properly scale the data to get g dest2[1] = (float)accel_bias[1]*aRes; dest2[2] = (float)accel_bias[2]*aRes; c = readByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_CTRL_REG9, c & ~0x02); //Disable accel FIFO delay(50); writeByte(LSM9DS1XG_ADDRESS, LSM9DS1XG_FIFO_CTRL, 0x00); // Enable accel bypass mode } void magcalLSM9DS1(float * dest1) { uint8_t data[6]; // data array to hold mag x, y, z, data uint16_t ii = 0, sample_count = 0; int32_t mag_bias[3] = {0, 0, 0}; int16_t mag_max[3] = {0, 0, 0}, mag_min[3] = {0, 0, 0}; // configure the magnetometer-enable temperature compensation of mag data writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG1_M, 0x80 | Mmode << 5 | Modr << 2); // select x,y-axis mode writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG2_M, Mscale << 5 ); // select mag full scale writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG3_M, 0x00 ); // continuous conversion mode writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG4_M, Mmode << 2 ); // select z-axis mode writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_CTRL_REG5_M, 0x40 ); // select block update mode Serial.println(""Mag Calibration: Wave device in a figure eight until done!""); delay(4000); sample_count = 128; for(ii = 0; ii < sample_count; ii++) { int16_t mag_temp[3] = {0, 0, 0}; readBytes(LSM9DS1M_ADDRESS, LSM9DS1M_OUT_X_L_M, 6, &data[0]); // Read the six raw data registers into data array mag_temp[0] = (int16_t) (((int16_t)data[1] << 8) | data[0]) ; // Form signed 16-bit integer for each sample in FIFO mag_temp[1] = (int16_t) (((int16_t)data[3] << 8) | data[2]) ; mag_temp[2] = (int16_t) (((int16_t)data[5] << 8) | data[4]) ; for (int jj = 0; jj < 3; jj++) { if(mag_temp[jj] > mag_max[jj]) mag_max[jj] = mag_temp[jj]; if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj]; } delay(105); // at 10 Hz ODR, new mag data is available every 100 ms } // Serial.println(""mag x min/max:""); Serial.println(mag_max[0]); Serial.println(mag_min[0]); // Serial.println(""mag y min/max:""); Serial.println(mag_max[1]); Serial.println(mag_min[1]); // Serial.println(""mag z min/max:""); Serial.println(mag_max[2]); Serial.println(mag_min[2]); mag_bias[0] = (mag_max[0] + mag_min[0])/2; // get average x mag bias in counts mag_bias[1] = (mag_max[1] + mag_min[1])/2; // get average y mag bias in counts mag_bias[2] = (mag_max[2] + mag_min[2])/2; // get average z mag bias in counts dest1[0] = (float) mag_bias[0]*mRes; // save mag biases in G for main program dest1[1] = (float) mag_bias[1]*mRes; dest1[2] = (float) mag_bias[2]*mRes; //write biases to accelerometermagnetometer offset registers as counts); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_OFFSET_X_REG_L_M, (int16_t) mag_bias[0] & 0xFF); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_OFFSET_X_REG_H_M, ((int16_t)mag_bias[0] >> 8) & 0xFF); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_OFFSET_Y_REG_L_M, (int16_t) mag_bias[1] & 0xFF); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_OFFSET_Y_REG_H_M, ((int16_t)mag_bias[1] >> 8) & 0xFF); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_OFFSET_Z_REG_L_M, (int16_t) mag_bias[2] & 0xFF); writeByte(LSM9DS1M_ADDRESS, LSM9DS1M_OFFSET_Z_REG_H_M, ((int16_t)mag_bias[2] >> 8) & 0xFF); Serial.println(""Mag Calibration done!""); } // I2C read/write functions for the LSM9DS1and AK8963 sensors void writeByte(uint8_t address, uint8_t subAddress, uint8_t data) { Wire1.beginTransmission(address); // Initialize the Tx buffer Wire1.write(subAddress); // Put slave register address in Tx buffer Wire1.write(data); // Put data in Tx buffer Wire1.endTransmission(); // Send the Tx buffer } uint8_t readByte(uint8_t address, uint8_t subAddress) { uint8_t data; // `data` will store the register data Wire1.beginTransmission(address); // Initialize the Tx buffer Wire1.write(subAddress); // Put slave register address in Tx buffer // Wire.endTransmission(I2C_NOSTOP); // Send the Tx buffer, but send a restart to keep connection alive Wire1.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive // Wire.requestFrom(address, 1); // Read one byte from slave register address Wire1.requestFrom(address, (size_t) 1); // Read one byte from slave register address data = Wire1.read(); // Fill Rx buffer with result return data; // Return data read from slave register } void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest) { Wire1.beginTransmission(address); // Initialize the Tx buffer Wire1.write(subAddress); // Put slave register address in Tx buffer // Wire.endTransmission(I2C_NOSTOP); // Send the Tx buffer, but send a restart to keep connection alive Wire1.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive uint8_t i = 0; Wire1.requestFrom(address, count); // Read bytes from slave register address // Wire.requestFrom(address, (size_t) count); // Read bytes from slave register address while (Wire1.available()) { dest[i++] = Wire1.read(); } // Put read results in the Rx buffer } void MadgwickQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz) { float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability float norm; float hx, hy, _2bx, _2bz; float s1, s2, s3, s4; float qDot1, qDot2, qDot3, qDot4; // Auxiliary variables to avoid repeated arithmetic float _2q1mx; float _2q1my; float _2q1mz; float _2q2mx; float _4bx; float _4bz; float _2q1 = 2.0f * q1; float _2q2 = 2.0f * q2; float _2q3 = 2.0f * q3; float _2q4 = 2.0f * q4; float _2q1q3 = 2.0f * q1 * q3; float _2q3q4 = 2.0f * q3 * q4; float q1q1 = q1 * q1; float q1q2 = q1 * q2; float q1q3 = q1 * q3; float q1q4 = q1 * q4; float q2q2 = q2 * q2; float q2q3 = q2 * q3; float q2q4 = q2 * q4; float q3q3 = q3 * q3; float q3q4 = q3 * q4; float q4q4 = q4 * q4; // Normalise accelerometer measurement norm = sqrt(ax * ax + ay * ay + az * az); if (norm == 0.0f) return; // handle NaN norm = 1.0f/norm; ax *= norm; ay *= norm; az *= norm; // Normalise magnetometer measurement norm = sqrt(mx * mx + my * my + mz * mz); if (norm == 0.0f) return; // handle NaN norm = 1.0f/norm; mx *= norm; my *= norm; mz *= norm; // Reference direction of Earth's magnetic field _2q1mx = 2.0f * q1 * mx; _2q1my = 2.0f * q1 * my; _2q1mz = 2.0f * q1 * mz; _2q2mx = 2.0f * q2 * mx; hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4; hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4; _2bx = sqrt(hx * hx + hy * hy); _2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4; _4bx = 2.0f * _2bx; _4bz = 2.0f * _2bz; // Gradient decent algorithm corrective step s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz); s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz); s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz); s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz); norm = sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step magnitude norm = 1.0f/norm; s1 *= norm; s2 *= norm; s3 *= norm; s4 *= norm; // Compute rate of change of quaternion qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1; qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2; qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3; qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4; // Integrate to yield quaternion q1 += qDot1 * deltat; q2 += qDot2 * deltat; q3 += qDot3 * deltat; q4 += qDot4 * deltat; norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion norm = 1.0f/norm; q[0] = q1 * norm; q[1] = q2 * norm; q[2] = q3 * norm; q[3] = q4 * norm; } ",16130,False,2213.4341719455233,median "// Urho3D editor hierarchy window handling const int ITEM_NONE = 0; const int ITEM_NODE = 1; const int ITEM_COMPONENT = 2; const int ITEM_UI_ELEMENT = 3; const uint NO_ITEM = M_MAX_UNSIGNED; const StringHash SCENE_TYPE(""Scene""); const StringHash NODE_TYPE(""Node""); const StringHash STATICMODEL_TYPE(""StaticModel""); const StringHash ANIMATEDMODEL_TYPE(""AnimatedModel""); const StringHash STATICMODELGROUP_TYPE(""StaticModelGroup""); const StringHash SPLINEPATH_TYPE(""SplinePath""); const StringHash CONSTRAINT_TYPE(""Constraint""); const String NO_CHANGE(uint8(0)); const StringHash TYPE_VAR(""Type""); const StringHash NODE_ID_VAR(""NodeID""); const StringHash COMPONENT_ID_VAR(""ComponentID""); const StringHash UI_ELEMENT_ID_VAR(""UIElementID""); const StringHash DRAGDROPCONTENT_VAR(""DragDropContent""); const StringHash[] ID_VARS = { StringHash(""""), NODE_ID_VAR, COMPONENT_ID_VAR, UI_ELEMENT_ID_VAR }; Color nodeTextColor(1.0f, 1.0f, 1.0f); Color componentTextColor(0.7f, 1.0f, 0.7f); Window@ hierarchyWindow; ListView@ hierarchyList; bool showID = true; // UIElement does not have unique ID, so use a running number to generate a new ID each time an item is inserted into hierarchy list const uint UI_ELEMENT_BASE_ID = 1; uint uiElementNextID = UI_ELEMENT_BASE_ID; bool showInternalUIElement = false; bool showTemporaryObject = false; Array hierarchyUpdateSelections; Variant GetUIElementID(UIElement@ element) { Variant elementID = element.GetVar(UI_ELEMENT_ID_VAR); if (elementID.empty) { // Generate new ID elementID = uiElementNextID++; // Store the generated ID element.vars[UI_ELEMENT_ID_VAR] = elementID; } return elementID; } UIElement@ GetUIElementByID(const Variant&in id) { return id == UI_ELEMENT_BASE_ID ? editorUIElement : editorUIElement.GetChild(UI_ELEMENT_ID_VAR, id, true); } void CreateHierarchyWindow() { if (hierarchyWindow !is null) return; hierarchyWindow = LoadEditorUI(""UI/EditorHierarchyWindow.xml""); hierarchyList = hierarchyWindow.GetChild(""HierarchyList""); ui.root.AddChild(hierarchyWindow); int height = Min(ui.root.height - 60, 500); hierarchyWindow.SetSize(300, height); hierarchyWindow.SetPosition(35, 100); hierarchyWindow.opacity = uiMaxOpacity; hierarchyWindow.BringToFront(); UpdateHierarchyItem(editorScene); // Set selection to happen on click end, so that we can drag nodes to the inspector without resetting the inspector view hierarchyList.selectOnClickEnd = true; // Set drag & drop target mode on the node list background, which is used to parent nodes back to the root node hierarchyList.contentElement.dragDropMode = DD_TARGET; hierarchyList.scrollPanel.dragDropMode = DD_TARGET; SubscribeToEvent(hierarchyWindow.GetChild(""CloseButton"", true), ""Released"", ""HideHierarchyWindow""); SubscribeToEvent(hierarchyWindow.GetChild(""ExpandButton"", true), ""Released"", ""ExpandCollapseHierarchy""); SubscribeToEvent(hierarchyWindow.GetChild(""CollapseButton"", true), ""Released"", ""ExpandCollapseHierarchy""); SubscribeToEvent(hierarchyWindow.GetChild(""ResetButton"", true), ""Released"", ""CollapseHierarchy""); SubscribeToEvent(hierarchyWindow.GetChild(""ShowID"", true), ""Toggled"", ""HandleShowID""); SubscribeToEvent(hierarchyList, ""SelectionChanged"", ""HandleHierarchyListSelectionChange""); SubscribeToEvent(hierarchyList, ""ItemDoubleClicked"", ""HandleHierarchyListDoubleClick""); SubscribeToEvent(hierarchyList, ""ItemClicked"", ""HandleHierarchyItemClick""); SubscribeToEvent(""DragDropTest"", ""HandleDragDropTest""); SubscribeToEvent(""DragDropFinish"", ""HandleDragDropFinish""); SubscribeToEvent(editorScene, ""NodeAdded"", ""HandleNodeAdded""); SubscribeToEvent(editorScene, ""NodeRemoved"", ""HandleNodeRemoved""); SubscribeToEvent(editorScene, ""ComponentAdded"", ""HandleComponentAdded""); SubscribeToEvent(editorScene, ""ComponentRemoved"", ""HandleComponentRemoved""); SubscribeToEvent(editorScene, ""NodeNameChanged"", ""HandleNodeNameChanged""); SubscribeToEvent(editorScene, ""NodeEnabledChanged"", ""HandleNodeEnabledChanged""); SubscribeToEvent(editorScene, ""ComponentEnabledChanged"", ""HandleComponentEnabledChanged""); SubscribeToEvent(""TemporaryChanged"", ""HandleTemporaryChanged""); } bool ToggleHierarchyWindow() { if (hierarchyWindow.visible == false) ShowHierarchyWindow(); else HideHierarchyWindow(); return true; } void ShowHierarchyWindow() { hierarchyWindow.visible = true; hierarchyWindow.BringToFront(); } void HideHierarchyWindow() { hierarchyWindow.visible = false; } void ExpandCollapseHierarchy(StringHash eventType, VariantMap& eventData) { Button@ button = eventData[""Element""].GetPtr(); bool enable = button.name == ""ExpandButton""; CheckBox@ checkBox = hierarchyWindow.GetChild(""AllCheckBox"", true); bool all = checkBox.checked; checkBox.checked = false; // Auto-reset Array selections = hierarchyList.selections; for (uint i = 0; i < selections.length; ++i) hierarchyList.Expand(selections[i], enable, all); } void EnableExpandCollapseButtons(bool enable) { String[] buttons = { ""ExpandButton"", ""CollapseButton"", ""AllCheckBox"" }; for (uint i = 0; i < buttons.length; ++i) { UIElement@ element = hierarchyWindow.GetChild(buttons[i], true); element.enabled = enable; element.children[0].color = enable ? normalTextColor : nonEditableTextColor; } } void UpdateHierarchyItem(Serializable@ serializable, bool clear = false) { if (clear) { // Remove the current selection before updating the list item (in turn trigger an update on the attribute editor) hierarchyList.ClearSelection(); // Clear copybuffer when whole window refreshed sceneCopyBuffer.Clear(); uiElementCopyBuffer.Clear(); } // In case of item's parent is not found in the hierarchy list then the item will be inserted at the list root level Serializable@ parent; switch (GetType(serializable)) { case ITEM_NODE: parent = cast(serializable).parent; break; case ITEM_COMPONENT: parent = cast(serializable).node; break; case ITEM_UI_ELEMENT: parent = cast(serializable).parent; break; default: break; } UIElement@ parentItem = hierarchyList.items[GetListIndex(parent)]; UpdateHierarchyItem(GetListIndex(serializable), serializable, parentItem); } uint UpdateHierarchyItem(uint itemIndex, Serializable@ serializable, UIElement@ parentItem) { // Whenever we're updating, disable layout update to optimize speed hierarchyList.contentElement.DisableLayoutUpdate(); if (serializable is null) { hierarchyList.RemoveItem(itemIndex); hierarchyList.contentElement.EnableLayoutUpdate(); hierarchyList.contentElement.UpdateLayout(); return itemIndex; } int itemType = GetType(serializable); Variant id = GetID(serializable, itemType); // Remove old item if exists if (itemIndex < hierarchyList.numItems && MatchID(hierarchyList.items[itemIndex], id, itemType)) hierarchyList.RemoveItem(itemIndex); Text@ text = Text(); hierarchyList.InsertItem(itemIndex, text, parentItem); text.style = ""FileSelectorListText""; if (serializable.type == SCENE_TYPE || serializable is editorUIElement) // The root node (scene) and editor's root UIElement cannot be moved by drag and drop text.dragDropMode = DD_TARGET; else // Internal UIElement is not able to participate in drag and drop action text.dragDropMode = itemType == ITEM_UI_ELEMENT && cast(serializable).internal ? DD_DISABLED : DD_SOURCE_AND_TARGET; // Advance the index for the child items if (itemIndex == M_MAX_UNSIGNED) itemIndex = hierarchyList.numItems; else ++itemIndex; String iconType = serializable.typeName; if (serializable is editorUIElement) iconType = ""Root"" + iconType; IconizeUIElement(text, iconType); SetID(text, serializable, itemType); switch (itemType) { case ITEM_NODE: { Node@ node = cast(serializable); text.text = GetNodeTitle(node); text.color = nodeTextColor; SetIconEnabledColor(text, node.enabled); // Update components first for (uint i = 0; i < node.numComponents; ++i) { Component@ component = node.components[i]; if (showTemporaryObject || !component.temporary) AddComponentItem(itemIndex++, component, text); } // Then update child nodes recursively for (uint i = 0; i < node.numChildren; ++i) { Node@ childNode = node.children[i]; if (showTemporaryObject || !childNode.temporary) itemIndex = UpdateHierarchyItem(itemIndex, childNode, text); } break; } case ITEM_COMPONENT: { Component@ component = cast(serializable); text.text = GetComponentTitle(component); text.color = componentTextColor; SetIconEnabledColor(text, component.enabledEffective); break; } case ITEM_UI_ELEMENT: { UIElement@ element = cast(serializable); text.text = GetUIElementTitle(element); SetIconEnabledColor(text, element.visible); // Update child elements recursively for (uint i = 0; i < element.numChildren; ++i) { UIElement@ childElement = element.children[i]; if ((showInternalUIElement || !childElement.internal) && (showTemporaryObject || !childElement.temporary)) itemIndex = UpdateHierarchyItem(itemIndex, childElement, text); } break; } default: break; } // Re-enable layout update (and do manual layout) now hierarchyList.contentElement.EnableLayoutUpdate(); hierarchyList.contentElement.UpdateLayout(); return itemIndex; } void UpdateHierarchyItemText(uint itemIndex, bool iconEnabled, const String&in textTitle = NO_CHANGE) { Text@ text = hierarchyList.items[itemIndex]; if (text is null) return; SetIconEnabledColor(text, iconEnabled); if (textTitle != NO_CHANGE) text.text = textTitle; } void AddComponentItem(uint compItemIndex, Component@ component, UIElement@ parentItem) { Text@ text = Text(); hierarchyList.InsertItem(compItemIndex, text, parentItem); text.style = ""FileSelectorListText""; text.vars[TYPE_VAR] = ITEM_COMPONENT; text.vars[NODE_ID_VAR] = component.node.id; text.vars[COMPONENT_ID_VAR] = component.id; text.text = GetComponentTitle(component); text.color = componentTextColor; // Components currently act only as drag targets text.dragDropMode = DD_TARGET; IconizeUIElement(text, component.typeName); SetIconEnabledColor(text, component.enabledEffective); } int GetType(Serializable@ serializable) { if (cast(serializable) !is null) return ITEM_NODE; else if (cast(serializable) !is null) return ITEM_COMPONENT; else if (cast(serializable) !is null) return ITEM_UI_ELEMENT; else return ITEM_NONE; } void SetID(Text@ text, Serializable@ serializable, int itemType = ITEM_NONE) { // If item type is not provided, auto detect it if (itemType == ITEM_NONE) itemType = GetType(serializable); text.vars[TYPE_VAR] = itemType; text.vars[ID_VARS[itemType]] = GetID(serializable, itemType); // Set node ID as drag and drop content for node ID editing if (itemType == ITEM_NODE) text.vars[DRAGDROPCONTENT_VAR] = String(text.vars[NODE_ID_VAR].GetUInt()); switch (itemType) { case ITEM_COMPONENT: text.vars[NODE_ID_VAR] = cast(serializable).node.id; break; case ITEM_UI_ELEMENT: // Subscribe to UI-element events SubscribeToEvent(serializable, ""NameChanged"", ""HandleElementNameChanged""); SubscribeToEvent(serializable, ""VisibleChanged"", ""HandleElementVisibilityChanged""); SubscribeToEvent(serializable, ""Resized"", ""HandleElementAttributeChanged""); SubscribeToEvent(serializable, ""Positioned"", ""HandleElementAttributeChanged""); break; default: break; } } uint GetID(Serializable@ serializable, int itemType = ITEM_NONE) { // If item type is not provided, auto detect it if (itemType == ITEM_NONE) itemType = GetType(serializable); switch (itemType) { case ITEM_NODE: return cast(serializable).id; case ITEM_COMPONENT: return cast(serializable).id; case ITEM_UI_ELEMENT: return GetUIElementID(cast(serializable)).GetUInt(); } return M_MAX_UNSIGNED; } bool MatchID(UIElement@ element, const Variant&in id, int itemType) { return element.GetVar(TYPE_VAR).GetInt() == itemType && element.GetVar(ID_VARS[itemType]) == id; } uint GetListIndex(Serializable@ serializable) { if (serializable is null) return NO_ITEM; int itemType = GetType(serializable); Variant id = GetID(serializable, itemType); uint numItems = hierarchyList.numItems; for (uint i = 0; i < numItems; ++i) { if (MatchID(hierarchyList.items[i], id, itemType)) return i; } return NO_ITEM; } UIElement@ GetListUIElement(uint index) { UIElement@ item = hierarchyList.items[index]; if (item is null) return null; // Get the text item's ID and use it to retrieve the actual UIElement the text item is associated to return GetUIElementByID(GetUIElementID(item)); } Node@ GetListNode(uint index) { UIElement@ item = hierarchyList.items[index]; if (item is null) return null; return editorScene.GetNode(item.vars[NODE_ID_VAR].GetUInt()); } Component@ GetListComponent(uint index) { UIElement@ item = hierarchyList.items[index]; return GetListComponent(item); } Component@ GetListComponent(UIElement@ item) { if (item is null) return null; if (item.vars[TYPE_VAR].GetInt() != ITEM_COMPONENT) return null; return editorScene.GetComponent(item.vars[COMPONENT_ID_VAR].GetUInt()); } uint GetComponentListIndex(Component@ component) { if (component is null) return NO_ITEM; uint numItems = hierarchyList.numItems; for (uint i = 0; i < numItems; ++i) { UIElement@ item = hierarchyList.items[i]; if (item.vars[TYPE_VAR].GetInt() == ITEM_COMPONENT && item.vars[COMPONENT_ID_VAR].GetUInt() == component.id) return i; } return NO_ITEM; } String GetUIElementTitle(UIElement@ element) { String ret; // Only top level UI-element has this variable String modifiedStr = element.GetVar(MODIFIED_VAR).GetBool() ? ""*"" : """"; ret = (element.name.empty ? element.typeName : element.name) + modifiedStr + "" ["" + GetUIElementID(element).ToString() + ""]""; if (element.temporary) ret += "" (Temp)""; return ret; } String GetNodeTitle(Node@ node) { String ret; if (node.name.empty) ret = node.typeName; else ret = node.name; if (showID) { if (node.id >= FIRST_LOCAL_ID) ret += "" (Local "" + String(node.id) + "")""; else ret += "" ("" + String(node.id) + "")""; if (node.temporary) ret += "" (Temp)""; } return ret; } String GetComponentTitle(Component@ component) { String ret = component.typeName; if (showID) { if (component.id >= FIRST_LOCAL_ID) ret += "" (Local)""; if (component.temporary) ret += "" (Temp)""; } return ret; } void SelectNode(Node@ node, bool multiselect) { if (node is null && !multiselect) { hierarchyList.ClearSelection(); return; } lastSelectedNode = node; uint index = GetListIndex(node); uint numItems = hierarchyList.numItems; if (index < numItems) { // Expand the node chain now if (!multiselect || !hierarchyList.IsSelected(index)) { // Go in the parent chain up to make sure the chain is expanded Node@ current = node; do { hierarchyList.Expand(GetListIndex(current), true); current = current.parent; } while (current !is null); } // This causes an event to be sent, in response we set the node/component selections, and refresh editors if (!multiselect) hierarchyList.selection = index; else hierarchyList.ToggleSelection(index); } else if (!multiselect) hierarchyList.ClearSelection(); } void SelectComponent(Component@ component, bool multiselect) { if (component is null && !multiselect) { hierarchyList.ClearSelection(); return; } Node@ node = component.node; if (node is null && !multiselect) { hierarchyList.ClearSelection(); return; } uint nodeIndex = GetListIndex(node); uint componentIndex = GetComponentListIndex(component); uint numItems = hierarchyList.numItems; if (nodeIndex < numItems && componentIndex < numItems) { // Expand the node chain now if (!multiselect || !hierarchyList.IsSelected(componentIndex)) { // Go in the parent chain up to make sure the chain is expanded Node@ current = node; do { hierarchyList.Expand(GetListIndex(current), true); current = current.parent; } while (current !is null); } // This causes an event to be sent, in response we set the node/component selections, and refresh editors if (!multiselect) hierarchyList.selection = componentIndex; else hierarchyList.ToggleSelection(componentIndex); } else if (!multiselect) hierarchyList.ClearSelection(); } void SelectUIElement(UIElement@ element, bool multiselect) { uint index = GetListIndex(element); uint numItems = hierarchyList.numItems; if (index < numItems) { // Expand the node chain now if (!multiselect || !hierarchyList.IsSelected(index)) { // Go in the parent chain up to make sure the chain is expanded UIElement@ current = element; do { hierarchyList.Expand(GetListIndex(current), true); current = current.parent; } while (current !is null); } if (!multiselect) hierarchyList.selection = index; else hierarchyList.ToggleSelection(index); } else if (!multiselect) hierarchyList.ClearSelection(); } // Find the first selected StaticModel/AtimatedModel component or node with it Model@ FindFirstSelectedModel() { for (uint i = 0; i < selectedComponents.length; ++i) { // Get SM, but also works well for AnimatedModel StaticModel@ sm = cast(selectedComponents[i]); if (sm !is null && sm.model !is null) return sm.model; } for (uint i = 0; i < selectedNodes.length; ++i) { for (uint j = 0; j < selectedNodes[i].numComponents; ++j) { StaticModel@ sm = cast(selectedNodes[i].components[j]); if (sm !is null && sm.model !is null) return sm.model; } } return null; } void UpdateModelInfo(Model@ model) { if (model is null) { modelInfoText.text = """"; return; } String infoStr = ""Model: "" + model.name; infoStr += ""\\n Morphs: "" + model.numMorphs; for (uint g = 0; g < model.numGeometries; ++g) { infoStr += ""\\n Geometry "" + g + ""\\n Lods: "" + model.numGeometryLodLevels[g]; } modelInfoText.text = infoStr; } void HandleHierarchyListSelectionChange() { if (inSelectionModify) return; ClearSceneSelection(); ClearUIElementSelection(); Array indices = hierarchyList.selections; // Enable Expand/Collapse button when there is selection EnableExpandCollapseButtons(indices.length > 0); for (uint i = 0; i < indices.length; ++i) { uint index = indices[i]; UIElement@ item = hierarchyList.items[index]; int type = item.vars[TYPE_VAR].GetInt(); if (type == ITEM_COMPONENT) { Component@ comp = GetListComponent(index); if (comp !is null) selectedComponents.Push(comp); } else if (type == ITEM_NODE) { Node@ node = GetListNode(index); if (node !is null) selectedNodes.Push(node); } else if (type == ITEM_UI_ELEMENT) { UIElement@ element = GetListUIElement(index); if (element !is null && element !is editorUIElement) selectedUIElements.Push(element); } } // If only one node/UIElement selected, use it for editing if (selectedNodes.length == 1) editNode = selectedNodes[0]; if (selectedUIElements.length == 1) editUIElement = selectedUIElements[0]; // If selection contains only components, and they have a common node, use it for editing if (selectedNodes.empty && !selectedComponents.empty) { Node@ commonNode; for (uint i = 0; i < selectedComponents.length; ++i) { if (i == 0) commonNode = selectedComponents[i].node; else { if (selectedComponents[i].node !is commonNode) commonNode = null; } } editNode = commonNode; } UpdateModelInfo(FindFirstSelectedModel()); // Now check if the component(s) can be edited. If many selected, must have same type or have same edit node if (!selectedComponents.empty) { if (editNode is null) { StringHash compType = selectedComponents[0].type; bool sameType = true; for (uint i = 1; i < selectedComponents.length; ++i) { if (selectedComponents[i].type != compType) { sameType = false; break; } } if (sameType) editComponents = selectedComponents; } else { editComponents = selectedComponents; numEditableComponentsPerNode = selectedComponents.length; } } // If just nodes selected, and no components, show as many matching components for editing as possible if (!selectedNodes.empty && selectedComponents.empty && selectedNodes[0].numComponents > 0) { uint count = 0; for (uint j = 0; j < selectedNodes[0].numComponents; ++j) { StringHash compType = selectedNodes[0].components[j].type; bool sameType = true; for (uint i = 1; i < selectedNodes.length; ++i) { if (selectedNodes[i].numComponents <= j || selectedNodes[i].components[j].type != compType) { sameType = false; break; } } if (sameType) { ++count; for (uint i = 0; i < selectedNodes.length; ++i) editComponents.Push(selectedNodes[i].components[j]); } } if (count > 1) numEditableComponentsPerNode = count; } if (selectedNodes.empty && editNode !is null) editNodes.Push(editNode); else { editNodes = selectedNodes; // Cannot multi-edit on scene and node(s) together as scene and node do not share identical attributes, // editing via gizmo does not make too much sense either if (editNodes.length > 1 && editNodes[0] is editorScene) editNodes.Erase(0); } if (selectedUIElements.empty && editUIElement !is null) editUIElements.Push(editUIElement); else editUIElements = selectedUIElements; PositionGizmo(); UpdateAttributeInspector(); UpdateCameraPreview(); } void HandleHierarchyListDoubleClick(StringHash eventType, VariantMap& eventData) { UIElement@ item = eventData[""Item""].GetPtr(); int type = item.vars[TYPE_VAR].GetInt(); // Locate nodes from the scene by double-clicking if (type == ITEM_NODE) { Node@ node = editorScene.GetNode(item.vars[NODE_ID_VAR].GetUInt()); LocateNode(node); } bool isExpanded = hierarchyList.IsExpanded(hierarchyList.selection); if (!isExpanded && eventData[""Button""].GetInt() == MOUSEB_LEFT) { isExpanded = !isExpanded; hierarchyList.Expand(hierarchyList.selection, isExpanded, false); } } void HandleHierarchyItemClick(StringHash eventType, VariantMap& eventData) { if (eventData[""Button""].GetInt() != MOUSEB_RIGHT) return; UIElement@ uiElement = eventData[""Item""].GetPtr(); int selectionIndex = eventData[""Selection""].GetInt(); Array actions; int type = uiElement.vars[TYPE_VAR].GetInt(); // Adds left clicked items to selection which is not normal listview behavior if (type == ITEM_COMPONENT || type == ITEM_NODE) { if (input.keyDown[KEY_LSHIFT]) hierarchyList.AddSelection(selectionIndex); else { hierarchyList.ClearSelection(); hierarchyList.AddSelection(selectionIndex); } } if (type == ITEM_COMPONENT) { Component@ targetComponent = editorScene.GetComponent(uiElement.vars[COMPONENT_ID_VAR].GetUInt()); if (targetComponent is null) return; actions.Push(CreateContextMenuItem(""Copy"", ""HandleHierarchyContextCopy"")); actions.Push(CreateContextMenuItem(""Cut"", ""HandleHierarchyContextCut"")); actions.Push(CreateContextMenuItem(""Delete"", ""HandleHierarchyContextDelete"")); actions.Push(CreateContextMenuItem(""Paste"", ""HandleHierarchyContextPaste"")); actions.Push(CreateContextMenuItem(""Enable/disable"", ""HandleHierarchyContextEnableDisable"")); /* actions.Push(CreateBrowserFileActionMenu(""Edit"", ""HandleBrowserEditResource"", file)); */ } else if (type == ITEM_NODE) { actions.Push(CreateContextMenuItem(""Create Replicated Node"", ""HandleHierarchyContextCreateReplicatedNode"")); actions.Push(CreateContextMenuItem(""Create Local Node"", ""HandleHierarchyContextCreateLocalNode"")); actions.Push(CreateContextMenuItem(""Duplicate"", ""HandleHierarchyContextDuplicate"")); actions.Push(CreateContextMenuItem(""Copy"", ""HandleHierarchyContextCopy"")); actions.Push(CreateContextMenuItem(""Cut"", ""HandleHierarchyContextCut"")); actions.Push(CreateContextMenuItem(""Delete"", ""HandleHierarchyContextDelete"")); actions.Push(CreateContextMenuItem(""Paste"", ""HandleHierarchyContextPaste"")); actions.Push(CreateContextMenuItem(""Reset to default"", ""HandleHierarchyContextResetToDefault"")); actions.Push(CreateContextMenuItem(""Reset position"", ""HandleHierarchyContextResetPosition"")); actions.Push(CreateContextMenuItem(""Reset rotation"", ""HandleHierarchyContextResetRotation"")); actions.Push(CreateContextMenuItem(""Reset scale"", ""HandleHierarchyContextResetScale"")); actions.Push(CreateContextMenuItem(""Enable/disable"", ""HandleHierarchyContextEnableDisable"")); actions.Push(CreateContextMenuItem(""Unparent"", ""HandleHierarchyContextUnparent"")); } else if (type == ITEM_UI_ELEMENT) { // close ui element actions.Push(CreateContextMenuItem(""Close UI-Layout"", ""HandleHierarchyContextUIElementCloseUILayout"")); actions.Push(CreateContextMenuItem(""Close all UI-layouts"", ""HandleHierarchyContextUIElementCloseAllUILayouts"")); } if (actions.length > 0) ActivateContextMenu(actions); } void HandleDragDropTest(StringHash eventType, VariantMap& eventData) { UIElement@ source = eventData[""Source""].GetPtr(); UIElement@ target = eventData[""Target""].GetPtr(); int itemType; eventData[""Accept""] = TestDragDrop(source, target, itemType); } void HandleDragDropFinish(StringHash eventType, VariantMap& eventData) { UIElement@ source = eventData[""Source""].GetPtr(); UIElement@ target = eventData[""Target""].GetPtr(); int itemType = ITEM_NONE; bool accept = TestDragDrop(source, target, itemType); eventData[""Accept""] = accept; if (!accept) return; // resource browser if (source !is null && source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt() > 0) { int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); BrowserFile@ browserFile = GetBrowserFileFromId(source.vars[TEXT_VAR_FILE_ID].GetUInt()); if (browserFile is null) return; Component@ createdComponent; if (itemType == ITEM_NODE) { Node@ targetNode = editorScene.GetNode(target.vars[NODE_ID_VAR].GetUInt()); if (targetNode is null) return; if (type == RESOURCE_TYPE_PREFAB) { LoadNode(browserFile.GetFullPath(), targetNode); } else if(type == RESOURCE_TYPE_SCRIPTFILE) { // TODO: not sure what to do here. lots of choices. } else if(type == RESOURCE_TYPE_MODEL) { CreateModelWithStaticModel(browserFile.resourceKey, targetNode); return; } else if (type == RESOURCE_TYPE_PARTICLEEFFECT) { if (browserFile.extension == ""xml"") { ParticleEffect@ effect = cache.GetResource(""ParticleEffect"", browserFile.resourceKey); if (effect is null) return; ParticleEmitter@ emitter = targetNode.CreateComponent(""ParticleEmitter""); emitter.effect = effect; createdComponent = emitter; } } else if (type == RESOURCE_TYPE_2D_PARTICLE_EFFECT) { if (browserFile.extension == ""xml"") { Resource@ effect = cache.GetResource(""ParticleEffect2D"", browserFile.resourceKey); if (effect is null) return; ResourceRef effectRef; effectRef.type = effect.type; effectRef.name = effect.name; Component@ emitter = targetNode.CreateComponent(""ParticleEmitter2D""); emitter.SetAttribute(""Particle Effect"", Variant(effectRef)); createdComponent = emitter; } } } else if (itemType == ITEM_COMPONENT) { Component@ targetComponent = editorScene.GetComponent(target.vars[COMPONENT_ID_VAR].GetUInt()); if (targetComponent is null) return; if (type == RESOURCE_TYPE_MATERIAL) { StaticModel@ model = cast(targetComponent); if (model is null) return; AssignMaterial(model, browserFile.resourceKey); } else if (type == RESOURCE_TYPE_MODEL) { StaticModel@ staticModel = cast(targetComponent); if (staticModel is null) return; AssignModel(staticModel, browserFile.resourceKey); } } else { LineEdit@ text = cast(target); if (text is null) return; text.text = browserFile.resourceKey; VariantMap data(); data[""Element""] = text; data[""Text""] = text.text; text.SendEvent(""TextFinished"", data); } if (createdComponent !is null) { CreateLoadedComponent(createdComponent); } return; } if (itemType == ITEM_NODE) { Node@ targetNode = editorScene.GetNode(target.vars[NODE_ID_VAR].GetUInt()); // If target is null, parent to scene if (targetNode is null) targetNode = editorScene; Array sourceNodes = GetMultipleSourceNodes(source); if (sourceNodes.length > 0) { if (sourceNodes.length > 1) SceneChangeParent(sourceNodes[0], sourceNodes, targetNode); else SceneChangeParent(sourceNodes[0], targetNode); // Focus the node at its new position in the list which in turn should trigger a refresh in attribute inspector FocusNode(sourceNodes[0]); } } else if (itemType == ITEM_UI_ELEMENT) { UIElement@ sourceElement = GetUIElementByID(source.vars[UI_ELEMENT_ID_VAR].GetUInt()); UIElement@ targetElement = GetUIElementByID(target.vars[UI_ELEMENT_ID_VAR].GetUInt()); // If target is null, cannot proceed if (targetElement is null) return; // Perform the reparenting if (!UIElementChangeParent(sourceElement, targetElement)) return; // Focus the element at its new position in the list which in turn should trigger a refresh in attribute inspector FocusUIElement(sourceElement); } else if (itemType == ITEM_COMPONENT) { Array sourceNodes = GetMultipleSourceNodes(source); Component@ targetComponent = editorScene.GetComponent(target.vars[COMPONENT_ID_VAR].GetUInt()); if (targetComponent !is null && sourceNodes.length > 0) { // Drag node to StaticModelGroup to make it an instance StaticModelGroup@ smg = cast(targetComponent); if (smg !is null) { // Save undo action EditAttributeAction action; uint attrIndex = GetAttributeIndex(smg, ""Instance Nodes""); Variant oldIDs = smg.attributes[attrIndex]; for (uint i = 0; i < sourceNodes.length; ++i) smg.AddInstanceNode(sourceNodes[i]); action.Define(smg, attrIndex, oldIDs); SaveEditAction(action); SetSceneModified(); } // Drag node to SplinePath to make it a control point SplinePath@ spline = cast(targetComponent); if (spline !is null) { // Save undo action EditAttributeAction action; uint attrIndex = GetAttributeIndex(spline, ""Control Points""); Variant oldIDs = spline.attributes[attrIndex]; for (uint i = 0; i < sourceNodes.length; ++i) spline.AddControlPoint(sourceNodes[i]); action.Define(spline, attrIndex, oldIDs); SaveEditAction(action); SetSceneModified(); } // Drag a node to Constraint to make it the remote end of the constraint Constraint@ constraint = cast(targetComponent); RigidBody@ rigidBody = sourceNodes[0].GetComponent(""RigidBody""); if (constraint !is null && rigidBody !is null) { // Save undo action EditAttributeAction action; uint attrIndex = GetAttributeIndex(constraint, ""Other Body NodeID""); Variant oldID = constraint.attributes[attrIndex]; constraint.otherBody = rigidBody; action.Define(constraint, attrIndex, oldID); SaveEditAction(action); SetSceneModified(); } } } } Array GetMultipleSourceNodes(UIElement@ source) { Array nodeList; Node@ node = editorScene.GetNode(source.vars[NODE_ID_VAR].GetUInt()); if (node !is null) nodeList.Push(node); // Handle additional selected children from a ListView if (source.parent !is null && source.parent.typeName == ""HierarchyContainer"") { ListView@ listView_ = cast(source.parent.parent.parent); if (listView_ is null) return nodeList; bool sourceIsSelected = false; for (uint i = 0; i < listView_.selectedItems.length; ++i) { if (listView_.selectedItems[i] is source) { sourceIsSelected = true; break; } } if (sourceIsSelected) { for (uint i = 0; i < listView_.selectedItems.length; ++i) { UIElement@ item_ = listView_.selectedItems[i]; // The source item is already added if (item_ is source) continue; if (item_.vars[TYPE_VAR] == ITEM_NODE) { Node@ n = editorScene.GetNode(item_.vars[NODE_ID_VAR].GetUInt()); if (n !is null) nodeList.Push(n); } } } } return nodeList; } bool TestDragDrop(UIElement@ source, UIElement@ target, int& itemType) { int targetItemType = target.GetVar(TYPE_VAR).GetInt(); if (targetItemType == ITEM_NODE) { Node@ sourceNode; Node@ targetNode; Variant variant = source.GetVar(NODE_ID_VAR); if (!variant.empty) sourceNode = editorScene.GetNode(variant.GetUInt()); variant = target.GetVar(NODE_ID_VAR); if (!variant.empty) targetNode = editorScene.GetNode(variant.GetUInt()); if (sourceNode !is null && targetNode !is null) { itemType = ITEM_NODE; if (sourceNode.parent is targetNode) return false; if (targetNode.parent is sourceNode) return false; } // Resource browser if (sourceNode is null && targetNode !is null) { itemType = ITEM_NODE; int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); return type == RESOURCE_TYPE_PREFAB || type == RESOURCE_TYPE_SCRIPTFILE || type == RESOURCE_TYPE_MODEL || type == RESOURCE_TYPE_PARTICLEEFFECT || type == RESOURCE_TYPE_2D_PARTICLE_EFFECT; } return true; } else if (targetItemType == ITEM_UI_ELEMENT) { UIElement@ sourceElement; UIElement@ targetElement; Variant variant = source.GetVar(UI_ELEMENT_ID_VAR); if (!variant.empty) sourceElement = GetUIElementByID(variant.GetUInt()); variant = target.GetVar(UI_ELEMENT_ID_VAR); if (!variant.empty) targetElement = GetUIElementByID(variant.GetUInt()); if (sourceElement !is null && targetElement !is null) { itemType = ITEM_UI_ELEMENT; if (sourceElement.parent is targetElement) return false; if (targetElement.parent is sourceElement) return false; } return true; } else if (targetItemType == ITEM_COMPONENT) { // Now only support dragging of nodes to StaticModelGroup, SplinePath or Constraint. Can be expanded to support others Node@ sourceNode; Component@ targetComponent; Variant variant = source.GetVar(NODE_ID_VAR); if (!variant.empty) sourceNode = editorScene.GetNode(variant.GetUInt()); variant = target.GetVar(COMPONENT_ID_VAR); if (!variant.empty) targetComponent = editorScene.GetComponent(variant.GetUInt()); itemType = ITEM_COMPONENT; if (sourceNode !is null && targetComponent !is null && (targetComponent.type == STATICMODELGROUP_TYPE || targetComponent.type == CONSTRAINT_TYPE || targetComponent.type == SPLINEPATH_TYPE)) return true; // resource browser int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); if (targetComponent.type == STATICMODEL_TYPE || targetComponent.type == ANIMATEDMODEL_TYPE) return type == RESOURCE_TYPE_MATERIAL || type == RESOURCE_TYPE_MODEL; return false; } else if (source.vars.Contains(TEXT_VAR_RESOURCE_TYPE)) // only testing resource browser ui elements { int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); // test against resource pickers LineEdit@ lineEdit = cast(target); if (lineEdit !is null) { StringHash resourceType = GetResourceTypeFromPickerLineEdit(lineEdit); if (resourceType == StringHash(""Material"") && type == RESOURCE_TYPE_MATERIAL) return true; else if (resourceType == StringHash(""Model"") && type == RESOURCE_TYPE_MODEL) return true; else if (resourceType == StringHash(""Animation"") && type == RESOURCE_TYPE_ANIMATION) return true; } } return true; } StringHash GetResourceTypeFromPickerLineEdit(UIElement@ lineEdit) { Array@ targets = GetAttributeEditorTargets(lineEdit); if (!targets.empty) { resourcePickIndex = lineEdit.vars[""Index""].GetUInt(); resourcePickSubIndex = lineEdit.vars[""SubIndex""].GetUInt(); AttributeInfo info = targets[0].attributeInfos[resourcePickIndex]; StringHash resourceType; if (info.type == VAR_RESOURCEREF) return targets[0].attributes[resourcePickIndex].GetResourceRef().type; else if (info.type == VAR_RESOURCEREFLIST) return targets[0].attributes[resourcePickIndex].GetResourceRefList().type; else if (info.type == VAR_VARIANTVECTOR) return targets[0].attributes[resourcePickIndex].GetVariantVector()[resourcePickSubIndex].GetResourceRef().type; } return StringHash(); } void FocusNode(Node@ node) { uint index = GetListIndex(node); hierarchyList.selection = index; } void FocusComponent(Component@ component) { uint index = GetComponentListIndex(component); hierarchyList.selection = index; } void FocusUIElement(UIElement@ element) { uint index = GetListIndex(element); hierarchyList.selection = index; } void CreateBuiltinObject(const String& name) { Node@ newNode = editorScene.CreateChild(name, REPLICATED); // Set the new node a certain distance from the camera newNode.position = GetNewNodePosition(); StaticModel@ object = newNode.CreateComponent(""StaticModel""); object.model = cache.GetResource(""Model"", ""Models/"" + name + "".mdl""); // Create an undo action for the create CreateNodeAction action; action.Define(newNode); SaveEditAction(action); SetSceneModified(); FocusNode(newNode); } bool CheckHierarchyWindowFocus() { // When we do edit operations based on key shortcuts, make sure the hierarchy list is focused return ui.focusElement is hierarchyList || ui.focusElement is null; } bool CheckForExistingGlobalComponent(Node@ node, const String&in typeName) { if (typeName != ""Octree"" && typeName != ""PhysicsWorld"" && typeName != ""DebugRenderer"") return false; else return node.HasComponent(typeName); } void HandleNodeAdded(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); if (showTemporaryObject || !node.temporary) UpdateHierarchyItem(node); } void HandleNodeRemoved(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); uint index = GetListIndex(node); UpdateHierarchyItem(index, null, null); } void HandleComponentAdded(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; // Insert the newly added component at last component position but before the first child node position of the parent node Node@ node = eventData[""Node""].GetPtr(); Component@ component = eventData[""Component""].GetPtr(); if (showTemporaryObject || !component.temporary) { uint nodeIndex = GetListIndex(node); if (nodeIndex != NO_ITEM) { uint index = node.numChildren > 0 ? GetListIndex(node.children[0]) : M_MAX_UNSIGNED; UpdateHierarchyItem(index, component, hierarchyList.items[nodeIndex]); } } } void HandleComponentRemoved(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Component@ component = eventData[""Component""].GetPtr(); uint index = GetComponentListIndex(component); if (index != NO_ITEM) hierarchyList.RemoveItem(index); } void HandleNodeNameChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); UpdateHierarchyItemText(GetListIndex(node), node.enabled, GetNodeTitle(node)); } void HandleNodeEnabledChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); UpdateHierarchyItemText(GetListIndex(node), node.enabled); attributesDirty = true; } void HandleComponentEnabledChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Component@ component = eventData[""Component""].GetPtr(); UpdateHierarchyItemText(GetComponentListIndex(component), component.enabledEffective); attributesDirty = true; } void HandleUIElementAdded(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); if ((showInternalUIElement || !element.internal) && (showTemporaryObject || !element.temporary)) UpdateHierarchyItem(element); } void HandleUIElementRemoved(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); UpdateHierarchyItem(GetListIndex(element), null, null); } void HandleElementNameChanged(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); UpdateHierarchyItemText(GetListIndex(element), element.visible, GetUIElementTitle(element)); } void HandleElementVisibilityChanged(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); UpdateHierarchyItemText(GetListIndex(element), element.visible); } void HandleElementAttributeChanged(StringHash eventType, VariantMap& eventData) { // Do not refresh the attribute inspector while the attribute is being edited via the attribute-editors if (suppressUIElementChanges || inEditAttribute) return; UIElement@ element = eventData[""Element""].GetPtr(); for (uint i = 0; i < editUIElements.length; ++i) { if (editUIElements[i] is element) attributesDirty = true; } } void HandleTemporaryChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges || suppressUIElementChanges) return; Serializable@ serializable = cast(GetEventSender()); Node@ node = cast(serializable); if (node !is null && node.scene is editorScene) { if (showTemporaryObject) UpdateHierarchyItemText(GetListIndex(node), node.enabled); else if (!node.temporary && GetListIndex(node) == NO_ITEM) UpdateHierarchyItem(node); else if (node.temporary) UpdateHierarchyItem(GetListIndex(node), null, null); return; } Component@ component = cast(serializable); if (component !is null && component.node !is null && component.node.scene is editorScene) { node = component.node; if (showTemporaryObject) UpdateHierarchyItemText(GetComponentListIndex(component), node.enabled); else if (!component.temporary && GetComponentListIndex(component) == NO_ITEM) { uint nodeIndex = GetListIndex(node); if (nodeIndex != NO_ITEM) { uint index = node.numChildren > 0 ? GetListIndex(node.children[0]) : M_MAX_UNSIGNED; UpdateHierarchyItem(index, component, hierarchyList.items[nodeIndex]); } } else if (component.temporary) { uint index = GetComponentListIndex(component); if (index != NO_ITEM) hierarchyList.RemoveItem(index); } return; } UIElement@ element = cast(serializable); if (element !is null) { if (showTemporaryObject) UpdateHierarchyItemText(GetListIndex(element), element.visible); else if (!element.temporary && GetListIndex(element) == NO_ITEM) UpdateHierarchyItem(element); else if (element.temporary) UpdateHierarchyItem(GetListIndex(element), null, null); return; } } // Hierarchy window edit functions bool Undo() { if (undoStackPos > 0) { --undoStackPos; // Undo commands in reverse order for (int i = int(undoStack[undoStackPos].actions.length - 1); i >= 0; --i) undoStack[undoStackPos].actions[i].Undo(); } return true; } bool Redo() { if (undoStackPos < undoStack.length) { // Redo commands in same order as stored for (uint i = 0; i < undoStack[undoStackPos].actions.length; ++i) undoStack[undoStackPos].actions[i].Redo(); ++undoStackPos; } return true; } bool Cut() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && SceneCut(); // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementCut(); return ret; } return false; } bool Duplicate() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && (selectedNodes.empty || selectedComponents.empty ? SceneDuplicate() : false); // Node and component is mutually exclusive for copy action // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementDuplicate(); return ret; } return false; } bool Copy() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && (selectedNodes.empty || selectedComponents.empty ? SceneCopy() : false); // Node and component is mutually exclusive for copy action // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementCopy(); return ret; } return false; } bool Paste() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (editNode !is null && !sceneCopyBuffer.empty) ret = ret && ScenePaste(); // Not mutually exclusive if (editUIElement !is null && !uiElementCopyBuffer.empty) ret = ret && UIElementPaste(); return ret; } return false; } bool BlenderModeDelete() { if (ui.focusElement is null) { Array actions; actions.Push(CreateContextMenuItem(""Delete?"", ""HandleBlenderModeDelete"")); actions.Push(CreateContextMenuItem(""Cancel"", ""HandleEmpty"")); if (actions.length > 0) { ActivateContextMenu(actions); return true; } } return false; } bool Delete() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && SceneDelete(); // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementDelete(); return ret; } return false; } bool SelectAll() { if (CheckHierarchyWindowFocus()) { if (!selectedNodes.empty || !selectedComponents.empty) return SceneSelectAll(); else if (!selectedUIElements.empty || hierarchyList.items[GetListIndex(editorUIElement)].selected) return UIElementSelectAll(); else return SceneSelectAll(); // If nothing is selected yet, fall back to scene select all } return false; } bool DeselectAll() { if (CheckHierarchyWindowFocus()) { BeginSelectionModify(); hierarchyList.ClearSelection(); EndSelectionModify(); return true; } return false; } bool ResetToDefault() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && (selectedNodes.empty || selectedComponents.empty ? SceneResetToDefault() : false); // Node and component is mutually exclusive for reset-to-default action // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementResetToDefault(); return ret; } return false; } void ClearEditActions() { undoStack.Clear(); undoStackPos = 0; } void SaveEditAction(EditAction@ action) { // Create a group with 1 action EditActionGroup group; group.actions.Push(action); SaveEditActionGroup(group); } void SaveEditActionGroup(EditActionGroup@ group) { if (group.actions.empty) return; // Truncate the stack first to current pos undoStack.Resize(undoStackPos); undoStack.Push(group); ++undoStackPos; // Limit maximum undo steps if (undoStack.length > MAX_UNDOSTACK_SIZE) { undoStack.Erase(0); --undoStackPos; } } void BeginSelectionModify() { // A large operation on selected nodes is about to begin. Disable intermediate selection updates inSelectionModify = true; // Cursor shape reverts back to normal automatically after the large operation is completed ui.cursor.shape = CS_BUSY; } void EndSelectionModify() { // The large operation on selected nodes has ended. Update node/component selection now inSelectionModify = false; HandleHierarchyListSelectionChange(); } void HandleHierarchyContextCreateReplicatedNode() { CreateNode(REPLICATED); } void HandleHierarchyContextCreateLocalNode() { CreateNode(LOCAL); } void HandleHierarchyContextDuplicate() { Duplicate(); } void HandleHierarchyContextCopy() { Copy(); } void HandleHierarchyContextCut() { Cut(); } void HandleHierarchyContextDelete() { Delete(); } void HandleBlenderModeDelete() { Delete(); } void HandleEmpty() { //just doing nothing } void HandleHierarchyContextPaste() { Paste(); } void HandleHierarchyContextResetToDefault() { ResetToDefault(); } void HandleHierarchyContextResetPosition() { SceneResetPosition(); } void HandleHierarchyContextResetRotation() { SceneResetRotation(); } void HandleHierarchyContextResetScale() { SceneResetScale(); } void HandleHierarchyContextEnableDisable() { SceneToggleEnable(); } void HandleHierarchyContextUnparent() { SceneUnparent(); } void HandleHierarchyContextUIElementCloseUILayout() { CloseUILayout(); } void HandleHierarchyContextUIElementCloseAllUILayouts() { CloseAllUILayouts(); } void CollapseHierarchy() { Array oldSelections = hierarchyList.selections; Array selections = {0}; hierarchyList.SetSelections(selections); for (uint i = 0; i < selections.length; ++i) hierarchyList.Expand(selections[i], false, true); // only scene's scope expand by default hierarchyList.Expand(0, true, false); hierarchyList.SetSelections(oldSelections); } void CollapseHierarchy(StringHash eventType, VariantMap& eventData) { CollapseHierarchy(); } void HandleShowID(StringHash eventType, VariantMap& eventData) { CheckBox@ checkBox = eventData[""Element""].GetPtr(); showID = checkBox.checked; UpdateHierarchyItem(editorScene, false); CollapseHierarchy(); } ",12244,False,2265.1292117274656,median "package com.arxterra.utils { import com.arxterra.controllers.CameraManager; import com.arxterra.controllers.SessionManager; import com.arxterra.controllers.WaypointsManager; import com.arxterra.icons.IconModeSmRobotCS; import com.arxterra.vo.CameraConfig; import com.arxterra.vo.CameraMove; import com.arxterra.vo.EmergencyFlags; import com.arxterra.vo.MessageByteArray; import com.arxterra.vo.MessageData; import com.arxterra.vo.MoveProps; import com.arxterra.vo.Ping; import com.arxterra.vo.SfsPreset; import com.arxterra.vo.ShortXY; import com.arxterra.vo.UserState; import com.arxterra.vo.WaypointCoordinates; import com.arxterra.vo.WaypointsList; import com.smartfoxserver.v2.SmartFox; import com.smartfoxserver.v2.core.SFSEvent; import com.smartfoxserver.v2.entities.Room; import com.smartfoxserver.v2.entities.User; import com.smartfoxserver.v2.entities.data.ISFSObject; import com.smartfoxserver.v2.entities.variables.SFSRoomVariable; import com.smartfoxserver.v2.entities.variables.SFSUserVariable; import com.smartfoxserver.v2.redbox.events.RedBoxConnectionEvent; import com.smartfoxserver.v2.requests.CreateRoomRequest; import com.smartfoxserver.v2.requests.JoinRoomRequest; import com.smartfoxserver.v2.requests.LoginRequest; import com.smartfoxserver.v2.requests.LogoutRequest; import com.smartfoxserver.v2.requests.PrivateMessageRequest; import com.smartfoxserver.v2.requests.RoomEvents; import com.smartfoxserver.v2.requests.RoomPermissions; import com.smartfoxserver.v2.requests.RoomSettings; import com.smartfoxserver.v2.requests.SetRoomVariablesRequest; import com.smartfoxserver.v2.requests.SetUserVariablesRequest; import flash.events.Event; import flash.events.TimerEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.geom.Matrix; import flash.media.Video; import flash.net.NetStream; import flash.system.Security; import flash.utils.Timer; import mx.collections.ArrayList; import away3d.core.math.MathConsts; /** * Pilot connector for the Client-Server operational * mode, which depends upon the SmartFoxServer. */ [Bindable] public class PilotConnectorCS extends PilotConnector { // CONSTANTS private const _ROOM_VAR_MSECS:int = 5000; private const _USER_VAR_MSECS:int = 250; // PUBLIC PROPERTIES AND GET/SET METHOD GROUPS public function get connectPresetsList ( ) : ArrayList { return new ArrayList ( _aPresets ); } [Bindable (event=""icon_changed"")] override public function get icon ( ) : Object { return IconModeSmRobotCS; } public var connectPresetTypical:SfsPreset; public var connectPrompt:String; public function get connectSettings():SfsPreset { return _connectSettings; } public function set connectSettings(value:SfsPreset):void { if ( value ) { _connectSettings = value.clone ( ); _sessionMgr.userState.sfsConfig = value; } else { _connectSettings = value; } } public var loginAssetsDir:String; public var loginPilotNames:String; public var loginPrompt:String; public var loginRobotName:String; // CONSTRUCTOR / DESTRUCTOR /** * @copy PilotConnectorCS */ public function PilotConnectorCS ( ) { super ( ); // NOTE: Do not call init() here, because it // is called in the superclass constructor. } override public function dismiss ( ) : void { _wpsMgr = null; _ConnectTimerDismiss ( ); _sessionMgr.removeEventListener ( SessionManager.APP_RESIZED, _AppResized ); _sessionMgr.removeEventListener ( SessionManager.AV_SENDER_METADATA_CHANGED, _AvSenderMetadataUpdate ); _WatchDogDismiss ( ); if ( _tmrRoomVars ) { _tmrRoomVars.stop ( ); _tmrRoomVars.removeEventListener ( TimerEvent.TIMER, _RoomVarsQueuedSend ); _tmrRoomVars = null; } if ( _tmrUserVars ) { _tmrUserVars.stop ( ); _tmrUserVars.removeEventListener ( TimerEvent.TIMER, _UserVarsQueuedSend ); _tmrUserVars = null; } if ( _camMgr ) { _camMgr.removeEventListener ( CameraManager.CAMERA_CHANGED, _AvSenderCameraChanged ); _camMgr.removeEventListener ( CameraManager.CAMERA_CONFIG_CHANGED, _AvSenderConfigChanged ); _camMgr.removeEventListener ( CameraManager.CAMERA_DIMENSIONS_READY, _AvSenderDimensionsReady ); _camMgr.removeEventListener ( CameraManager.CAMERA_INSET_ALIGN_H, _AvSenderMonitorUpdateQueue ); _camMgr.removeEventListener ( CameraManager.CAMERA_INSET_ALIGN_V, _AvSenderMonitorUpdateQueue ); _camMgr.removeEventListener ( CameraManager.CAMERA_INSET_SIZE, _AvSenderMonitorUpdateQueue ); _camMgr.removeEventListener ( CameraManager.CAMERA_MONITOR, _AvSenderMonitorUpdateQueue ); _camMgr.enabled = false; _camMgr = null; } if ( _sf ) { // SmartFox event listeners _sf.removeEventListener ( SFSEvent.CONNECTION, _Connection ); _sf.removeEventListener ( SFSEvent.CONNECTION_LOST, _ConnectionLost ); _sf.removeEventListener ( SFSEvent.PING_PONG, _LagMonitorUpdate ); _sf.removeEventListener ( SFSEvent.LOGIN_ERROR, _LoginFailed ); _sf.removeEventListener ( SFSEvent.LOGIN, _LoginSucceeded ); _sf.removeEventListener ( SFSEvent.LOGOUT, _LogoutDone ); _sf.removeEventListener ( SFSEvent.PRIVATE_MESSAGE, _PrivateMessageReceived ); _sf.removeEventListener ( SFSEvent.ROOM_CREATION_ERROR, _RoomCreationError ); _sf.removeEventListener ( SFSEvent.ROOM_JOIN, _JoinSuccess ); _sf.removeEventListener ( SFSEvent.ROOM_JOIN_ERROR, _JoinFailure ); _sf.removeEventListener ( SFSEvent.USER_COUNT_CHANGE, _UserCountChanged ); _sf.removeEventListener ( SFSEvent.USER_ENTER_ROOM, _UserEnteredRoom ); _sf.removeEventListener ( SFSEvent.USER_EXIT_ROOM, _UserExitedRoom ); if ( _sf.isConnected ) { if ( _sf.currentZone.length > 0 ) { _AvCastMgrDismiss ( ); _sf.send ( new LogoutRequest ( ) ); } _sf.disconnect ( ); } _sf = null; } super.dismiss ( ); } /** * Called automatically by superclass during instantiation, * but may also be called manually to reactivate * if object was previously dismissed. * Subclass overrides must call super.init(). */ override public function init ( ) : void { super.init ( ); var userState:UserState = _sessionMgr.userState; _connectSettings = userState.sfsConfig; loginAssetsDir = userState.assetsDir; loginPilotNames = userState.pilotNames; loginPrompt = ''; loginRobotName = userState.robotName; _tmrUserVars = new Timer ( _USER_VAR_MSECS, 0 ); _tmrUserVars.addEventListener ( TimerEvent.TIMER, _UserVarsQueuedSend ); _tmrRoomVars = new Timer ( _ROOM_VAR_MSECS, 0 ); _tmrRoomVars.addEventListener ( TimerEvent.TIMER, _RoomVarsQueuedSend ); _WatchDogInit ( ); _wpsMgr = WaypointsManager.instance; // instantiate SmartFox client class _sf = new SmartFox ( _sessionMgr.debugOn ); _debugOut ( 'status_sfs_api', true, [ _sf.version ] ); // SmartFox event listeners _sf.addEventListener ( SFSEvent.CONNECTION, _Connection ); _sf.addEventListener ( SFSEvent.CONNECTION_LOST, _ConnectionLost ); _sf.addEventListener ( SFSEvent.PING_PONG, _LagMonitorUpdate ); _sf.addEventListener ( SFSEvent.LOGIN_ERROR, _LoginFailed ); _sf.addEventListener ( SFSEvent.LOGIN, _LoginSucceeded ); _sf.addEventListener ( SFSEvent.LOGOUT, _LogoutDone ); _sf.addEventListener ( SFSEvent.PRIVATE_MESSAGE, _PrivateMessageReceived ); _sf.addEventListener ( SFSEvent.ROOM_CREATION_ERROR, _RoomCreationError ); _sf.addEventListener ( SFSEvent.ROOM_JOIN, _JoinSuccess ); _sf.addEventListener ( SFSEvent.ROOM_JOIN_ERROR, _JoinFailure ); _sf.addEventListener ( SFSEvent.USER_COUNT_CHANGE, _UserCountChanged ); _sf.addEventListener ( SFSEvent.USER_ENTER_ROOM, _UserEnteredRoom ); _sf.addEventListener ( SFSEvent.USER_EXIT_ROOM, _UserExitedRoom ); _camMgr = CameraManager.instance; _camMgr.addEventListener ( CameraManager.CAMERA_CHANGED, _AvSenderCameraChanged ); _camMgr.addEventListener ( CameraManager.CAMERA_CONFIG_CHANGED, _AvSenderConfigChanged ); _camMgr.addEventListener ( CameraManager.CAMERA_DIMENSIONS_READY, _AvSenderDimensionsReady ); _camMgr.addEventListener ( CameraManager.CAMERA_INSET_ALIGN_H, _AvSenderMonitorUpdateQueue ); _camMgr.addEventListener ( CameraManager.CAMERA_INSET_ALIGN_V, _AvSenderMonitorUpdateQueue ); _camMgr.addEventListener ( CameraManager.CAMERA_INSET_SIZE, _AvSenderMonitorUpdateQueue ); _camMgr.addEventListener ( CameraManager.CAMERA_MONITOR, _AvSenderMonitorUpdateQueue ); _camMgr.enabled = true; _sessionMgr.addEventListener ( SessionManager.AV_SENDER_METADATA_CHANGED, _AvSenderMetadataUpdate ); _sessionMgr.addEventListener ( SessionManager.APP_RESIZED, _AppResized ); _callLater ( _PresetsLoad ); } // OTHER PUBLIC METHODS /** * Stop the outbound AV stream * @return Boolean true if stream was on */ override public function avSenderClear ( ) : Boolean { var bWasOn:Boolean = false; _AvSenderMonitorClear ( ); if ( _nsSndr != null ) { bWasOn = true; _avCastMgr.unpublishLiveCast ( ); _nsSndr = null; } return bWasOn; } /** * Start the outbound AV stream */ override public function avSenderPublish ( ) : void { avSenderClear ( ); if ( !_sessionMgr.testCfgMediaStreamAllow ) return; // Publish my live cast if ( !_avCastMgr ) return; if ( !_avCastMgr.isConnected ) return; var bOk:Boolean = true; var aParams:Array; var sRsrc:String; var sStat:String; var bVidOk:Boolean = _camMgr.cameraEnabled; var bAudOk:Boolean = _camMgr.microphoneEnabled; if ( bVidOk || bAudOk ) { try { _nsSndr = _avCastMgr.publishLiveCast ( bVidOk, bAudOk ); if ( !_nsSndr ) { sRsrc = 'error_livecast_stream_null'; bOk = false; } } catch ( err:Error ) { sRsrc = 'error_livecast_publish'; aParams = [ err.message ]; bOk = false; } if ( bOk ) { // stream has initialized successfully sRsrc = 'status_livecast_publish'; _camMgr.dimensionsCheck ( ); } } else { sRsrc = 'status_livecast_no_permit'; } sStat = _resourceManager.getString ( 'default', sRsrc, aParams ); _debugOut ( sStat ); _sessionMgr.statusSet ( sStat ); } public function connectQueue ( preset:SfsPreset = null ) : void { if ( preset ) { // called from connect view connectSettings = preset; _sessionMgr.viewStatePop ( 'connect_prompt_cs' ); } Security.loadPolicyFile ( 'xmlsocket://' + connectSettings.host + ':' + connectSettings.port ); if ( _sf && _sf.isConnected ) { if ( !_sf.lastJoinedRoom ) { _sessionMgr.viewStatePush ( 'login_prompt_cs' ); } } else { _callLater ( _Connect ); } } public function connectToggle ( ) : void { if ( _sf ) { if ( _sf.isConnected ) { disconnectQueue ( ); } else { connectQueue ( ); } } } public function disconnectQueue ( ) : void { if ( _sf.isConnected ) { if ( _sf.currentZone.length > 0 ) { _AvCastMgrDismiss ( ); _sf.send ( new LogoutRequest ( ) ); } else { _sf.disconnect ( ); } } } public function lagMonitorAllowed ( value:Boolean ) : void { if ( !_sleeping && _sf && _sf.isConnected ) { _sf.enableLagMonitor ( value ); } } /** * @param verbose Boolean true if to report errors to user * @return Boolean true if validates okay, false if not */ public function loginRequestQueue ( robotName:String, pilotNames:String, assetsDir:String, verbose:Boolean = true ) : Boolean { if ( loginValidate ( robotName, pilotNames, assetsDir, verbose ) ) { // validated ok // for now no passwords needed _LoginAttempt ( loginRobotName ); return true; // return } return false; } public function loginValidate ( robotName:String, pilotNames:String, assetsDir:String, verbose:Boolean = true ) : Boolean { var reEnds:RegExp = /^\\s+|\\s+$/g; var reExcess:RegExp = /\\s{2,}/g; var sRobotName:String = robotName.replace ( reEnds, '' ); sRobotName = sRobotName.replace ( reExcess, ' ' ); var sRobotNameLc:String = sRobotName.toLowerCase ( ); var iLen:int = sRobotName.length; var bError:Boolean = false; var aLobbyNames:Array = [ 'lobby', 'lounge' ]; var aPilots:Array = []; if ( iLen < 3 || iLen > 32 || aLobbyNames.indexOf ( sRobotNameLc ) >= 0 ) { // invalid Robot name bError = true; } else { var sPilots:String = pilotNames.replace ( reEnds, '' ); sPilots = sPilots.replace ( reExcess, ' ' ); if ( sPilots.length < 3 ) { // invalid Pilot name bError = true; } else { aPilots = sPilots.split ( /\\s*,\\s*/ ); var iLim:int = aPilots.length; var i_sName:String; var i_sNameLc:String; for ( var i:int=0; i 32 || aLobbyNames.indexOf ( i_sNameLc ) >= 0 || i_sNameLc == sRobotNameLc ) { // invalid Pilot name bError = true; break; } } sPilots = aPilots.join ( ',' ); } } loginRobotName = sRobotName; loginPilotNames = sPilots; loginAssetsDir = assetsDir.replace ( reEnds, '' ); if ( bError ) { var sErr:String = _resourceManager.getString ( 'default', 'error_login_name' ); // _debugOut ( sErr ); if ( verbose ) { loginPrompt = sErr; // dispatchEvent ( new DialogEvent ( DialogEvent.ALERT, 'error_login_name', 'error_login_name_title' ) ); } _hasValidLoginSet ( false ); return false; // return } // if get here, have reasonable entries _vsPilots = Vector. ( aPilots ); loginPrompt = ''; var userState:UserState = _sessionMgr.userState; userState.robotName = loginRobotName; userState.pilotNames = loginPilotNames; userState.assetsDir = loginAssetsDir; _hasValidLoginSet ( true ); return true; } public function mediaStreamAllowed ( value:Boolean ) : void { if ( value ) { if ( !_sleeping ) { _AvCastMgrInit ( ); } } else { _AvCastMgrDismiss ( ); } } override public function roomVarsQueue ( vars:Vector., immediate:Boolean = false ) : void { // only keeping the latest value if any repeats var i:int; var iLim:int = vars.length; var i_md:MessageData; for ( i=0; i, immediate:Boolean = false ) : void { // only keeping the latest value if any repeats var i:int; var iLim:int = vars.length; var i_md:MessageData; for ( i=0; i [ new MessageData ( 'wdge', value ) ] ); if ( value ) { _WatchDogInit ( ); } else { _WatchDogDismiss ( ); } } // PROTECTED METHODS override protected function _debugChanged ( value:Boolean ) : void { super._debugChanged ( value ); if ( _sf ) { _sf.debug = value; } } // PRIVATE PROPERTIES private var _aPresets:Array; private var _avCastMgr:AVCastManagerArx; private var _bMonUpdtQueued:Boolean = false; private var _bSndrPubQueued:Boolean = false; private var _camMgr:CameraManager; private var _connectSettings:SfsPreset; private var _iPilotUserId:int = 0; // will update _iSfsLagRT to latest average from SmartFox's lag monitoring private var _iSfsLagRT:int = 200; private var _nsRcvr:NetStream; private var _nsSndr:NetStream; private var _sf:SmartFox; private var _tmrConnect:Timer; // connection timeout private var _tmrDog:Timer; // watch dog timer private var _tmrRoomVars:Timer; // send queued room variables private var _tmrUserVars:Timer; // send queued user variables private var _vidRcvr:Video; private var _vidSndr:Video; private var _vsPilots:Vector.; // private var _vsPilotsQueue:Vector. = new []; private var _wpsMgr:WaypointsManager; // PRIVATE METHODS private function _AppResized ( event:Event = null ) : void { _AvSenderPublishQueue ( ); } private function _AvCastMgrDismiss ( ) : void { if ( !_avCastMgr ) return; avSenderClear ( ); avReceiverClear ( ); _avCastMgr.removeEventListener ( RedBoxConnectionEvent.AV_CONNECTION_INITIALIZED, _AvConnectionInited ); _avCastMgr.removeEventListener ( RedBoxConnectionEvent.AV_CONNECTION_ERROR, _AvConnectionError ); _avCastMgr.destroy ( ); _avCastMgr = null; } private function _AvCastMgrInit ( ) : void { if ( !_sessionMgr.testCfgMediaStreamAllow ) return; _sessionMgr.statusSetResource ( 'status_sfs_livecast_wait' ); // instantiate AVCastManager _avCastMgr = new AVCastManagerArx ( _sf, _sf.currentIp, false, true ); _avCastMgr.addEventListener ( RedBoxConnectionEvent.AV_CONNECTION_INITIALIZED, _AvConnectionInited ); _avCastMgr.addEventListener ( RedBoxConnectionEvent.AV_CONNECTION_ERROR, _AvConnectionError ); } private function _AvConnectionError ( event:RedBoxConnectionEvent ) : void { var sStat:String = _resourceManager.getString ( 'default', 'error_av_connect', [ event.params.errorCode ] ); _debugOut ( sStat ); _sessionMgr.statusSet ( sStat ); } private function _AvConnectionInited ( event:RedBoxConnectionEvent ) : void { _AvSenderPublishQueue ( ); avReceiverSubscribe ( ); } private function _AvSenderCameraChanged ( event:Event = null ) : void { _AvSenderPublishQueue ( ); } private function _AvSenderConfigChanged ( event:Event = null ) : void { if ( _sleeping ) return; if ( !_nsSndr ) { _AvSenderPublishQueue ( ); } } private function _AvSenderDimensionsReady ( event:Event = null ) : void { _AvSenderMetadataUpdate ( ); } private function _AvSenderMetadataUpdate ( event:Event = null ) : void { // Send video transform factors to Control Panel userVarsQueue ( new [ new MessageData ( 'cvfh', _sessionMgr.userState.cameraFlipHorizontal ), new MessageData ( 'cvfv', _sessionMgr.userState.cameraFlipVertical ), new MessageData ( 'cvr', _sessionMgr.videoSenderRotation ) ] ); // if monitoring outbound video, update its dimensions _AvSenderMonitorUpdateQueue ( ); } private function _AvSenderMonitorClear ( ) : void { if ( !_vidSndr ) return; _vidSndr.attachCamera ( null ); _vidSndr.clear ( ); _sessionMgr.videoPod.removeChild ( _vidSndr ); _vidSndr = null; } private function _AvSenderMonitorUpdate ( event:TimerEvent ) : void { _bMonUpdtQueued = false; var tmr:Timer = event.target as Timer; tmr.stop ( ); tmr.removeEventListener ( TimerEvent.TIMER, _AvSenderMonitorUpdate ); tmr = null; _AvSenderMonitorClear ( ); if ( !_sessionMgr.testCfgMediaStreamAllow ) return; // return if ( !_camMgr.monitor ) return; // return if ( !_avCastMgr ) return; // return if ( !_avCastMgr.isConnected ) return; // return var iVidPodHt:int = _sessionMgr.videoPodHeight; var iVidPodWd:int = _sessionMgr.videoPodWidth; var iVidHt:int = _camMgr.cameraHeight; var iVidWd:int = _camMgr.cameraWidth; var nVidHtRot:Number; var nVidWdRot:Number; var nVidHtPost:Number; var nVidWdPost:Number; var nScale:Number; if ( _sessionMgr.orientedPortrait ) { nVidHtRot = iVidWd; nVidWdRot = iVidHt; } else { nVidHtRot = iVidHt; nVidWdRot = iVidWd; } if ( _sessionMgr.videoPodAspectRatio < ( nVidHtRot / nVidWdRot ) ) { // height is limiting nScale = _camMgr.insetSize * iVidPodHt / nVidHtRot; } else { // width is limiting nScale = _camMgr.insetSize * iVidPodWd / nVidWdRot; } // calculate post-transform dimensions nVidHtPost = nScale * nVidHtRot; nVidWdPost = nScale * nVidWdRot; // create transform matrix // to position the video in the videoPod var mat:Matrix = new Matrix ( ); // move center to origin mat.translate ( -iVidWd / 2, -iVidHt / 2 ); // apply rotation if necessary if ( _sessionMgr.orientedPortrait ) { mat.rotate ( _sessionMgr.videoSenderRotation * MathConsts.DEGREES_TO_RADIANS ); } // apply scale var userState:UserState = _sessionMgr.userState; mat.scale ( nScale * ( userState.cameraFlipHorizontal ? -1 : 1 ), nScale * ( userState.cameraFlipVertical ? -1 : 1 ) ); // translate as dictated by alignment settings var oAlignVals:Object = { 'left': -0.5, 'center': 0, 'right': 0.5, 'top': -0.5, 'middle': 0, 'bottom': 0.5 }; // X translated by 1/2 pod width will center video horizontally. // To align left or right edges respectively, subtract or add // 1/2 the difference between pod width and video width. // Y translated by 1/2 pod height will center video vertically. // To align top or bottom edges respectively, subtract or add // 1/2 the difference between pod height and video height. mat.translate ( iVidPodWd / 2 + ( iVidPodWd - nVidWdPost ) * ( oAlignVals [ _camMgr.insetAlignH ] as Number ), iVidPodHt / 2 + ( iVidPodHt - nVidHtPost ) * ( oAlignVals [ _camMgr.insetAlignV ] as Number ) ); // display video _vidSndr = new Video ( iVidWd, iVidHt ); _vidSndr.transform.matrix = mat; _sessionMgr.videoPod.addChild ( _vidSndr ); _vidSndr.attachCamera ( _camMgr.camera ); } private function _AvSenderMonitorUpdateQueue ( event:Event = null ) : void { if ( _bMonUpdtQueued ) return; // return _bMonUpdtQueued = true; var tmr:Timer = new Timer ( 20, 1 ); tmr.addEventListener ( TimerEvent.TIMER, _AvSenderMonitorUpdate ); tmr.start ( ); } private function _AvSenderPublish ( event:TimerEvent ) : void { _bSndrPubQueued = false; var tmr:Timer = event.target as Timer; tmr.stop ( ); tmr.removeEventListener ( TimerEvent.TIMER, _AvSenderPublish ); tmr = null; avSenderPublish ( ); } private function _AvSenderPublishQueue ( event:Event = null ) : void { if ( _bSndrPubQueued ) return; // return _bSndrPubQueued = true; var tmr:Timer = new Timer ( 20, 1 ); tmr.addEventListener ( TimerEvent.TIMER, _AvSenderPublish ); tmr.start ( ); } private function _CameraRestartRequest ( ) : void { /* if ( _sessionMgr.moveIgnore ) { _debugOut ( 'cameraRestartRequest discarded due to emergency flags: ' + _sessionMgr.emergencyFlagsGet() ); return; // return } */ _AvSenderPublishQueue ( ); } private function _Connect ( ) : void { if ( _sf.isConnected ) { return; // return } _sessionMgr.statusSetResource ( 'status_sfs_connect_wait', true ); _ConnectTimerInit ( ); _isPendingSet ( true ); _sf.connectWithConfig ( connectSettings.configData ); // _sessionMgr.viewStatePop ( 'connect_prompt_cs' ); } private function _Connection ( event:SFSEvent ) : void { _ConnectTimerDismiss ( ); var sStat:String; if ( event.params.success ) { _isConnectedSet ( true ); sStat = _resourceManager.getString ( 'default', 'status_sfs_connect' ); _sessionMgr.statusSet ( sStat ); _debugOut ( sStat ); // _sessionMgr.viewStatePush ( 'login_prompt_cs' ); _LoginAttempt ( loginRobotName ); } else { _isConnectedSet ( false ); _isPendingSet ( false ); connectPrompt = _resourceManager.getString ( 'default', 'error_sfs_connect', [ event.params.errorMessage ] ); _sessionMgr.statusSet ( connectPrompt ); _debugOut ( connectPrompt ); _sessionMgr.viewStatePush ( 'connect_config_cs' ); } } private function _ConnectionLost ( event:SFSEvent ) : void { _isConnectedSet ( false ); _isPendingSet ( false ); _isReadySet ( false ); _TimersCancelAll ( ); _AvCastMgrDismiss ( ); connectPrompt = _resourceManager.getString ( 'default', 'error_sfs_connect_lost', [ event.params.reason ] ); _sessionMgr.statusSet ( connectPrompt ); _debugOut (connectPrompt ); // _sessionMgr.viewStatePush ( 'connect_prompt_cs' ); } private function _ConnectTimeout ( event:TimerEvent ) : void { _ConnectTimerDismiss ( ); _sf.disconnect ( ); // just in case of a race condition _isConnectedSet ( false ); _isPendingSet ( false ); _isReadySet ( false ); connectPrompt = _resourceManager.getString ( 'default', 'error_sfs_connect_timeout' ); _sessionMgr.statusSet ( connectPrompt ); _debugOut ( connectPrompt ); // _sessionMgr.viewStatePush ( 'connect_prompt_cs' ); } private function _ConnectTimerDismiss ( ) : void { if ( !_tmrConnect ) return; _tmrConnect.stop ( ); _tmrConnect.removeEventListener ( TimerEvent.TIMER, _ConnectTimeout ); _tmrConnect = null; } private function _ConnectTimerInit ( ) : void { if ( !_tmrConnect ) { _tmrConnect = new Timer ( 10000, 1 ); _tmrConnect.addEventListener ( TimerEvent.TIMER, _ConnectTimeout ); } _tmrConnect.reset ( ); _tmrConnect.start ( ); } private function _HaveValidPilotId ( ) : Boolean { if ( _iPilotUserId < 1 ) return false; if ( _sf.lastJoinedRoom ) { if ( _sf.lastJoinedRoom.getUserById ( _iPilotUserId ) ) { return true; } } _iPilotUserId = 0; return false; } private function _JoinFailure ( event:SFSEvent ) : void { _debugOut ( 'error_sfs_join', true, [ event.params.errorMessage ], true ); // ##### TODO ##### _callLater ( _Logout ); } private function _JoinSuccess ( event:SFSEvent ) : void { var sStat:String = _resourceManager.getString ( 'default', 'status_sfs_join', [ event.params.room.name ] ); _debugOut ( sStat ); _sessionMgr.statusSet ( sStat ); _isPendingSet ( false ); _isReadySet ( true ); // prepare for av feeds _callLater ( _AvCastMgrInit ); // initialize user and room variables _sessionMgr.batchVarsReportQueue ( ); // start timers if ( _sessionMgr.testCfgLagMonSfAllow ) { _sf.enableLagMonitor ( true ); } _tmrUserVars.start ( ); _tmrRoomVars.start ( ); } private function _LagMonitorUpdate ( event:SFSEvent ) : void { _iSfsLagRT = event.params.lagValue; } private function _LoginAttempt ( userName:String = '', password:String = null, zoneName:String = null, params:ISFSObject = null ) : void { _sessionMgr.viewStatePop ( 'login_prompt_cs' ); _sessionMgr.statusSetResource ( 'status_sfs_login_wait', true ); _sf.send ( new LoginRequest ( userName, password, zoneName, params ) ); } private function _LoginFailed ( event:SFSEvent ) : void { var sErr:String = _resourceManager.getString ( 'default', 'error_sfs_login', [ event.params.errorMessage ] ); _debugOut ( sErr ); loginPrompt = sErr; if ( _sf.isConnected ) { _sessionMgr.viewStatePush ( 'login_prompt_cs' ); } } private function _LoginSucceeded ( event:SFSEvent ) : void { _sessionMgr.statusSetResource ( 'status_sfs_join_wait', true ); var sRobotName:String = _sessionMgr.userState.robotName; // debugOut ( 'status_sfs_login', true, [ event.params.user.name ] ); if ( _sf.roomManager.containsRoom ( sRobotName ) ) { // should not happen, but just in case... _sf.send ( new JoinRoomRequest ( sRobotName ) ); } else { // create room and auto-join var re:RoomEvents = new RoomEvents ( ); re.allowUserCountChange = true; re.allowUserEnter = true; re.allowUserExit = true; re.allowUserVariablesUpdate = true var rp:RoomPermissions = new RoomPermissions ( ); rp.allowPublicMessages = true; var rs:RoomSettings = new RoomSettings ( sRobotName ); rs.events = re; rs.permissions = rp; rs.maxUsers = 100; rs.maxVariables = 100; _sf.send ( new CreateRoomRequest ( rs, true ) ); } } private function _Logout ( ) : void { if ( _sf.isConnected ) { _sf.send ( new LogoutRequest ( ) ); } } private function _LogoutDone ( event:SFSEvent ) : void { _sf.disconnect ( ); } private function _PilotCheck ( room:Room, userLeaving:User = null ) : void { if ( room != _sf.lastJoinedRoom ) return; var bPiloted:Boolean = room.getVariable ( 'pib' ).getBoolValue ( ); var sPilot:String = room.getVariable ( 'pic' ).getStringValue ( ); if ( !bPiloted ) { _iPilotUserId = 0; _sessionMgr.emergencyFlagsClear ( EmergencyFlags.LATENCY ); } else if ( room.getUserByName ( sPilot ) == null || ( userLeaving != null && userLeaving.name == sPilot ) ) { // pilot exited room var aRoomVars:Array = [ new SFSRoomVariable ( 'pib', false ), new SFSRoomVariable ( 'pic', '' ) ]; _sf.send ( new SetRoomVariablesRequest ( aRoomVars ) ); _iPilotUserId = 0; _sessionMgr.emergencyFlagsClear ( EmergencyFlags.LATENCY ); } } private function _PingReceived ( sfso:ISFSObject ) : void { var ping:Ping = Ping.newFromSFSObject ( sfso ); ping.robotTimeStamp = new Date().getTime(); ping.robotLagSfs = _iSfsLagRT; _sf.send ( new PrivateMessageRequest ( 'pong', _iPilotUserId, ping.toSFSObject() ) ); if ( _sleeping ) { if ( _sessionMgr.batterySupported && _sessionMgr.testCfgBatteryAllow ) { userVarsQueue ( new [ new MessageData ( 'pbt', _sessionMgr.batteryPct ) ], true ); } } _WatchDogIntervalSet ( ping.intervalMsecs ); } private function _PresetsLoad ( ) : void { _callLater ( _PrevLoginValidate ); connectPrompt = _resourceManager.getString ( 'default', 'sfs_connect_config_prompt' ); var f:File = File.applicationDirectory.resolvePath ( 'config/sfs-presets.json' ); var sStat:String; if ( !f.exists ) { sStat = _resourceManager.getString ( 'default', 'error_sfs_presets' ); _debugOut ( sStat ); _sessionMgr.statusSet ( sStat ); _sessionMgr.viewStatePush ( 'connect_config_cs' ); return; // return } // build arrayList of presets, and pre-select the default one var sIdDef:String = ''; _aPresets = []; var uPresetsLen:uint = 0; var spDef:SfsPreset; var spTyp:SfsPreset; try { var fs:FileStream = new FileStream(); // open fs.open ( f, FileMode.READ ); // read var sJson:String = fs.readUTFBytes ( fs.bytesAvailable ); // close fs.close ( ); // debugOut ( sJson ); var oJson:Object = JSON.parse ( sJson ); if ( 'configs' in oJson ) { if ( 'default' in oJson ) { sIdDef = oJson [ 'default' ]; } var iLabelLen:int = 0; var oCfgs:Object = oJson [ 'configs' ]; var i_sId:String; var i_sLoc:String; var i_iLen:int; var i_sp:SfsPreset; for ( i_sId in oCfgs ) { i_sp = new SfsPreset ( i_sId, oCfgs [ i_sId ] ) _aPresets [ uPresetsLen++ ] = i_sp; if ( i_sId == sIdDef ) { spDef = i_sp; } i_sLoc = _resourceManager.getString ( 'default', 'sfs_connect_preset_' + i_sId ); if ( !i_sLoc ) { i_sLoc = i_sId; } i_iLen = i_sLoc.length; if ( i_iLen > iLabelLen ) { iLabelLen = i_iLen; spTyp = i_sp; } } } } catch ( err:Error ) { sStat = _resourceManager.getString ( 'default', 'error_sfs_presets_load', [ err.message ] ); _sessionMgr.statusSet ( sStat ); _debugOut ( sStat, false, null, true ); _sessionMgr.viewStatePush ( 'connect_config_cs' ); return; // return } _aPresets.sortOn ( 'id', Array.CASEINSENSITIVE ); connectPresetTypical = spTyp; if ( !_connectSettings ) { connectSettings = spDef.clone ( ); } /* if ( _sessionMgr.expertModeOn ) { _sessionMgr.viewStatePush ( 'connect_prompt_cs' ); } else { // if get here, can try autoconnect connectQueue ( ); } */ } /** * Validates login fields persisted from previous session, if any. * If validation fails, goes to the login configuration view. */ private function _PrevLoginValidate ( ) : void { if ( !loginValidate ( loginRobotName, loginPilotNames, loginAssetsDir, false ) ) { _sessionMgr.viewStatePush ( 'login_config_cs' ); } } private function _PrivateMessageReceived ( event:SFSEvent ) : void { var sender:User = event.params.sender; if ( sender == _sf.mySelf ) return; // validate sender so control messages are only accepted from pilot var sSenderName:String = sender.name; if ( _vsPilots.indexOf ( sSenderName ) < 0 ) return; _iPilotUserId = sender.id; if ( !_sleeping ) { _WatchDogReset ( ); } var sMsg:String = event.params.message; switch ( sMsg ) { case 'ping': { _PingReceived ( event.params.data as ISFSObject ); break; } case 'emsack': { _sessionMgr.emergencyAcknowledge ( ); break; } case 'mv': { _sessionMgr.motionRequest ( MoveProps.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'cu': { _sessionMgr.customRequest ( MessageByteArray.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'cm': { _sessionMgr.cameraMoveRequest ( CameraMove.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'ch': { _sessionMgr.cameraMoveHomeRequest ( ); break; } case 'cr': { _sessionMgr.cameraMoveResetRequest ( ); break; } case 'cvk': { _sessionMgr.cameraViewClickRequest ( ShortXY.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'mcl': { _sessionMgr.motorCurrentLimitRequest ( ( event.params.data as ISFSObject ).getUnsignedByte ( 's' ) ); break; } case 'stt': { _sessionMgr.steeringTrimRequest ( ( event.params.data as ISFSObject ).getDouble ( 't' ) ); break; } case 'wp': { _debugOut ( 'New Waypoint message received' ); _wpsMgr.waypointAdd ( WaypointCoordinates.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'wp0': { _debugOut ( 'Deactivate Autopilot message received' ); _wpsMgr.active = false; break; } case 'wp1': { _debugOut ( 'Activate Autopilot message received' ); _wpsMgr.active = true; break; } case 'wpca': { _debugOut ( 'Clear Waypoint List message received' ); _wpsMgr.listClear ( ); break; } case 'wpd': { _debugOut ( 'Delete Waypoint message received' ); _wpsMgr.waypointDelete ( MessageByteArray.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'wpm': { _debugOut ( 'Move Waypoint message received' ); _wpsMgr.waypointMove ( WaypointCoordinates.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'wpla': { _debugOut ( 'Append Waypoint List message received' ); _wpsMgr.listAppend ( WaypointsList.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'wplr': { _debugOut ( 'Replace Waypoint List message received' ); _wpsMgr.listReplace ( WaypointsList.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'fl': { _sessionMgr.light ( ( event.params.data as ISFSObject ).getBool ( 'b' ) ); break; } case 'camerarestart': { _CameraRestartRequest ( ); break; } case 'cameraconfig': { _camMgr.configRequest ( CameraConfig.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'cameraconfigadjust': { _camMgr.configAdjustRequest ( ( event.params.data as ISFSObject ).getBool ( 'b' ) ); break; } case 'cameraconfigdef': { _camMgr.configDefaultRequest ( CameraConfig.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'cameraconfigmotion': { _camMgr.configMotionRequest ( CameraConfig.NewFromSFSObject ( event.params.data as ISFSObject ) ); break; } case 'camerafpspollmsec': { _camMgr.fpsPollRequest ( ( event.params.data as ISFSObject ).getShort ( 'm' ) || 0 ); break; } case 'sleep': { _sessionMgr.sleepRequest ( ); break; } case 'wake': { _sessionMgr.wakeRequest ( ); break; } case 'exit': { _sessionMgr.exitConfirmed ( ); break; } default: { _debugOut ( 'error_control_message', true, [ sMsg ] ); break; } } } private function _RoomCreationError ( event:SFSEvent ) : void { _debugOut ( 'error_sfs_room_creation', true, [ event.params.errorMessage ] ); // now what? // ##### TODO } private function _RoomVarsQueuedSend ( event:TimerEvent = null ) : void { var vars:Array = []; var uLen:uint = 0; for each ( var i_md:MessageData in _roomVarsQueued ) { if ( i_md.typeIsComplex ) { vars [ uLen++ ] = new SFSRoomVariable ( i_md.message, i_md.data.toSFSObject() ); } else { vars [ uLen++ ] = new SFSRoomVariable ( i_md.message, i_md.data ); } } if ( uLen > 0 ) { // prepare for next batch _roomVarsQueued = {}; // send all the queued variables _sf.send ( new SetRoomVariablesRequest ( vars ) ); } } private function _TimersCancelAll ( ) : void { _ConnectTimerDismiss ( ); _WatchDogCancel ( ); _tmrRoomVars.stop ( ); _tmrUserVars.stop ( ); } private function _UserCountChanged ( event:SFSEvent ) : void { _PilotCheck ( event.params.room ); } private function _UserEnteredRoom ( event:SFSEvent ) : void { _PilotCheck ( event.params.room ); } private function _UserExitedRoom ( event:SFSEvent ) : void { var room:Room = event.params.room; var user:User = event.params.user; if ( room.name == _sessionMgr.userState.robotName && user == _sf.mySelf ) { if ( _sessionMgr.testCfgLagMonSfAllow ) { _sf.enableLagMonitor ( false ); } _TimersCancelAll ( ); _AvCastMgrDismiss ( ); } else { _PilotCheck ( event.params.room, event.params.user ); } } private function _UserVarsQueuedSend ( event:TimerEvent = null ) : void { var vars:Array = []; var uLen:uint = 0; for each ( var i_md:MessageData in _userVarsQueued ) { if ( i_md.typeIsComplex ) { vars [ uLen++ ] = new SFSUserVariable ( i_md.message, i_md.data.toSFSObject() ); } else { vars [ uLen++ ] = new SFSUserVariable ( i_md.message, i_md.data ); } } if ( uLen > 0 ) { // prepare for next batch _userVarsQueued = {}; // send all the queued variables _sf.send ( new SetUserVariablesRequest ( vars ) ); } } private function _WatchDogBark ( event:TimerEvent ) : void { // Watch dog timer lapsed. if ( _HaveValidPilotId ( ) ) { _debugOut ( 'status_watchdog', true, [ _tmrDog.delay ] ); _sessionMgr.emergencyFlagsSet ( EmergencyFlags.LATENCY ); } } private function _WatchDogCancel ( ) : void { if ( !_tmrDog ) return; _tmrDog.stop ( ); } private function _WatchDogDismiss ( ) : void { if ( !_tmrDog ) return; _tmrDog.stop ( ); _tmrDog.removeEventListener ( TimerEvent.TIMER, _WatchDogBark ); _tmrDog = null; } private function _WatchDogInit ( ) : void { if ( !_sessionMgr.testCfgWatchDogsAllow ) return; if ( !_tmrDog ) { // default watch dog to 2.1 secs, then adjust when get current value from ping _tmrDog = new Timer ( 2100, 1 ); _tmrDog.addEventListener ( TimerEvent.TIMER, _WatchDogBark ); } } private function _WatchDogIntervalSet ( pingIntervalMsecs:int ) : void { if ( !_tmrDog ) return; _tmrDog.reset ( ); // allow a cushion on top of time until next expected ping var iNew:int = pingIntervalMsecs * 1.5 + _iSfsLagRT; if ( _tmrDog.delay != iNew ) _tmrDog.delay = iNew; _tmrDog.start ( ); } private function _WatchDogReset ( ) : void { if ( !_tmrDog ) return; _tmrDog.reset ( ); _tmrDog.start ( ); } } }",12207,False,2457.747803485375,median "/* Japanese.ino Use the (Arduino compatible) u8g2 function ""print"" to draw a text. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7528_ERC16064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7528_ERC16064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { u8g2.begin(); u8g2.enableUTF8Print(); // enable UTF8 support for the Arduino print() function } void loop(void) { u8g2.setFont(u8g2_font_b10_t_japanese1); // all the glyphs of ""こんにちは世界"" are already included in japanese1: Lerning Level 1-6 u8g2.setFontDirection(0); u8g2.firstPage(); do { u8g2.setCursor(0, 15); u8g2.print(""Hello World!""); u8g2.setCursor(0, 40); u8g2.print(""こんにちは世界""); // Japanese ""Hello World"" } while ( u8g2.nextPage() ); delay(1000); } ",16175,True,5074.409541211351,median "/* Chinese.ino Use the (Arduino compatible) u8g2 function ""print"" to draw a text. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7528_ERC16064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7528_ERC16064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { u8g2.begin(); u8g2.enableUTF8Print(); // enable UTF8 support for the Arduino print() function } void loop(void) { u8g2.setFont(u8g2_font_unifont_t_chinese2); // use chinese2 for all the glyphs of ""你好世界"" //u8g2.setFont(u8g2_font_b10_t_japanese1); // all the glyphs of ""こんにちは世界"" are already included in japanese1: Lerning Level 1-6 u8g2.setFontDirection(0); u8g2.firstPage(); do { u8g2.setCursor(0, 15); u8g2.print(""Hello World!""); u8g2.setCursor(0, 40); u8g2.print(""你好世界""); // Chinese ""Hello World"" //u8g2.print(""こんにちは世界""); // Japanese ""Hello World"" } while ( u8g2.nextPage() ); delay(1000); } ",16229,True,5039.978118802544,median "// Import required libraries #include #include #include #include #include #include #include #include #include #define REV1 // PCB REV 1 #ifdef REV1 #define LED_BUILTIN 18 #define SENSOR1 4 // beer1 (J1) #define SENSOR2 13 // beer2 (J2) #define SENSOR3 14 // beer3 (J3) #define SENSOR4 15 // beer4 (J4) #define SENSOR5 25 // beer5 (J5) #define SENSOR6 16 // beer6 (J6) #define SENSOR7 17 // beer7 (J7) #define SENSOR8 27 // beer8 (J8) #define SENSOR9 32 // beer9 (J9) #define SENSOR10 26 // beer10 (J10) #endif // LED stuff int ledState = HIGH; int stopLED = 1; unsigned long previousMillisLED = 0; long blinkInterval = 1000; // ToDo: use STA_AP mode to allow initial setup over WiFi - done 18/09/21 // ToDo: create OTA upload page for .bin firmware updates - done 18/09/21 // ToDo: create OTA upload page for SPIFFS partition updates - done 18/09/21 // ToDo: create beer volume set from in settings - done 18/09/21 // ToDo: add a flow calibration/modifier in settings - done 20/09/21 // ToDo: save beer names from settings to flash so they are persitent - done 19/09/21 // ToDo: save beer volumes from settings to flash so they are persitent - done 19/09/21 // ToDo: save beer volumes from flow readings to flash so they are persitent - done 20/09/21 // ToDo: validate beer volumes and name input field data - done 19/09/21 // ToDo: configure consumption chart to dynamically update names and volumes - done 21/09/21 // ToDo: configure overview to dynamically update beer names and volumes - volumes done 21/09/21 // ToDo: add an fast LED blink to indicate there is an error (wifi not connected etc) - done 20/09/21 // ToDo: add visual feedback that form submitted correctly - done 20/09/21 // ToDo: consumption charts need to honour beer count and render the right amount of charts // ToDo: implement a mode press button to wipe WiFi creds and trigger WiFi AP for setup // ToDo: sync data colours between charts - done 21/09/21 // ToDo: create a way to backup and restore beer data before a firmware upgrade - done (not needed) 19/09/21 // ToDo: test/build CSS HTML layouts for different sized screens/mobile < this probably won't happen ;) // ToDo: write some tests... // Replace with your network credentials Preferences preferences; String pwifiSSID; String pwifiPassword; const char *wifiSSID = ""ShelveNET""; const char *wifiPassword = ""buttpiratry""; int wifiDisconnected = 0; void (*resetFunc)(void) = 0; // declare reset fuction at address 0 const char *PARAM_INPUT_0 = ""numberofbeers""; const char *PARAM_INPUT_1 = ""beer1name""; const char *PARAM_INPUT_2 = ""beer2name""; const char *PARAM_INPUT_3 = ""beer3name""; const char *PARAM_INPUT_4 = ""beer4name""; const char *PARAM_INPUT_5 = ""beer5name""; const char *PARAM_INPUT_6 = ""beer6name""; const char *PARAM_INPUT_7 = ""beer7name""; const char *PARAM_INPUT_8 = ""beer8name""; const char *PARAM_INPUT_9 = ""beer9name""; const char *PARAM_INPUT_10 = ""beer10name""; const char *PARAM_INPUT_11 = ""beer1volume""; const char *PARAM_INPUT_12 = ""beer2volume""; const char *PARAM_INPUT_13 = ""beer3volume""; const char *PARAM_INPUT_14 = ""beer4volume""; const char *PARAM_INPUT_15 = ""beer5volume""; const char *PARAM_INPUT_16 = ""beer6volume""; const char *PARAM_INPUT_17 = ""beer7volume""; const char *PARAM_INPUT_18 = ""beer8volume""; const char *PARAM_INPUT_19 = ""beer9volume""; const char *PARAM_INPUT_20 = ""beer10volume""; const char *PARAM_INPUT_21 = ""wifissid""; const char *PARAM_INPUT_22 = ""wifipassword""; const char *PARAM_INPUT_23 = ""reset""; const char *PARAM_INPUT_24 = ""flowmultiplier""; const char *PARAM_INPUT_25 = ""allbeernames""; const char *PARAM_INPUT_26 = ""overviewchartname""; String beer1Name; String beer2Name; String beer3Name; String beer4Name; String beer5Name; String beer6Name; String beer7Name; String beer8Name; String beer9Name; String beer10Name; String overviewChartName; String statsString = """"; String beerNameString = """"; String jsonBeerNamesString =""""; int numberOfBeers = 10; float beer1Volume; float beer2Volume; float beer3Volume; float beer4Volume; float beer5Volume; float beer6Volume; float beer7Volume; float beer8Volume; float beer9Volume; float beer10Volume; float tempBeer1Volume; float tempBeer2Volume; float tempBeer3Volume; float tempBeer4Volume; float tempBeer5Volume; float tempBeer6Volume; float tempBeer7Volume; float tempBeer8Volume; float tempBeer9Volume; float tempBeer10Volume; float calibrationFactor = 98; bool status; char promBytes[32]; int pulse1 = 0; long currentMillis1 = 0; long previousMillis1 = 0; int flowMilliLitres1; int totalMilliLitres1; byte pulseSec1 = 0; volatile byte pulseCount1; float beer1Litres = 0; char beer1LitresChar[6] = """"; float flowRate1; void IRAM_ATTR pulseCount1er() { pulseCount1++; } int pulse2 = 0; long currentMillis2 = 0; long previousMillis2 = 0; int flowMilliLitres2; int totalMilliLitres2; byte pulseSec2 = 0; volatile byte pulseCount2; float beer2Litres = 0; char beer2LitresChar[6] = """"; float flowRate2; void IRAM_ATTR pulseCount2er() { pulseCount2++; } int pulse3 = 0; long currentMillis3 = 0; long previousMillis3 = 0; int flowMilliLitres3; int totalMilliLitres3; byte pulseSec3 = 0; volatile byte pulseCount3; float beer3Litres = 0; char beer3LitresChar[6] = """"; float flowRate3; void IRAM_ATTR pulseCount3er() { pulseCount3++; } int pulse4 = 0; long currentMillis4 = 0; long previousMillis4 = 0; int flowMilliLitres4; int totalMilliLitres4; byte pulseSec4 = 0; volatile byte pulseCount4; float beer4Litres = 0; char beer4LitresChar[6] = """"; float flowRate4; void IRAM_ATTR pulseCount4er() { pulseCount4++; } int pulse5 = 0; long currentMillis5 = 0; long previousMillis5 = 0; int flowMilliLitres5; int totalMilliLitres5; byte pulseSec5 = 0; volatile byte pulseCount5; float beer5Litres = 0; char beer5LitresChar[6] = """"; float flowRate5; void IRAM_ATTR pulseCount5er() { pulseCount5++; } int pulse6 = 0; long currentMillis6 = 0; long previousMillis6 = 0; int flowMilliLitres6; int totalMilliLitres6; byte pulseSec6 = 0; volatile byte pulseCount6; float beer6Litres = 0; char beer6LitresChar[6] = """"; float flowRate6; void IRAM_ATTR pulseCount6er() { pulseCount6++; } int pulse7 = 0; long currentMillis7 = 0; long previousMillis7 = 0; int flowMilliLitres7; int totalMilliLitres7; byte pulseSec7 = 0; volatile byte pulseCount7; float beer7Litres = 0; char beer7LitresChar[6] = """"; float flowRate7; void IRAM_ATTR pulseCount7er() { pulseCount7++; } int pulse8 = 0; long currentMillis8 = 0; long previousMillis8 = 0; int flowMilliLitres8; int totalMilliLitres8; byte pulseSec8 = 0; volatile byte pulseCount8; float beer8Litres = 0; char beer8LitresChar[6] = """"; float flowRate8; void IRAM_ATTR pulseCount8er() { pulseCount8++; } int pulse9 = 0; long currentMillis9 = 0; long previousMillis9 = 0; int flowMilliLitres9; int totalMilliLitres9; byte pulseSec9 = 0; volatile byte pulseCount9; float beer9Litres = 0; char beer9LitresChar[6] = """"; float flowRate9; void IRAM_ATTR pulseCount9er() { pulseCount9++; } int pulse10 = 0; long currentMillis10 = 0; long previousMillis10 = 0; int flowMilliLitres10; int totalMilliLitres10; byte pulseSec10 = 0; volatile byte pulseCount10; float beer10Litres = 0; char beer10LitresChar[6] = """"; float flowRate10; void IRAM_ATTR pulseCount10er() { pulseCount10++; } SimpleTimer timer; int interval = 1000; // wait time before comparing flow data float stats[10] = {20.00, 18.00, 16.00, 14.00, 12.00, 10.00, 8.00, 6.00, 4.00, 0.00}; // Create AsyncWebServer object on port 80 AsyncWebServer server(80); AsyncWebSocket ws(""/ws""); void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { switch (type) { case WS_EVT_CONNECT: Serial.printf(""WebSocket client #%u connected from %s\\n"", client->id(), client->remoteIP().toString().c_str()); break; case WS_EVT_DISCONNECT: Serial.printf(""WebSocket client #%u disconnected\\n"", client->id()); break; case WS_EVT_PONG: case WS_EVT_ERROR: break; } } void initWebSocket() { ws.onEvent(onEvent); server.addHandler(&ws); } void notFound(AsyncWebServerRequest *request) { request->send(404, ""text/plain"", ""Not found""); } void setupFlowData() { pinMode(SENSOR1, INPUT_PULLUP); pinMode(SENSOR2, INPUT_PULLUP); pinMode(SENSOR3, INPUT_PULLUP); pinMode(SENSOR4, INPUT_PULLUP); pinMode(SENSOR5, INPUT_PULLUP); pinMode(SENSOR6, INPUT_PULLUP); pinMode(SENSOR7, INPUT_PULLUP); pinMode(SENSOR8, INPUT_PULLUP); pinMode(SENSOR9, INPUT_PULLUP); pinMode(SENSOR10, INPUT_PULLUP); pulseCount1 = 0; flowRate1 = 0.0; flowMilliLitres1 = 0; totalMilliLitres1 = 0; previousMillis1 = 0; pulseCount2 = 0; flowRate2 = 0.0; flowMilliLitres2 = 0; totalMilliLitres2 = 0; previousMillis2 = 0; pulseCount3 = 0; flowRate3 = 0.0; flowMilliLitres3 = 0; totalMilliLitres3 = 0; previousMillis3 = 0; pulseCount4 = 0; flowRate4 = 0.0; flowMilliLitres4 = 0; totalMilliLitres4 = 0; previousMillis4 = 0; pulseCount5 = 0; flowRate5 = 0.0; flowMilliLitres5 = 0; totalMilliLitres5 = 0; previousMillis5 = 0; pulseCount6 = 0; flowRate6 = 0.0; flowMilliLitres6 = 0; totalMilliLitres6 = 0; previousMillis6 = 0; pulseCount7 = 0; flowRate7 = 0.0; flowMilliLitres7 = 0; totalMilliLitres7 = 0; previousMillis7 = 0; pulseCount8 = 0; flowRate8 = 0.0; flowMilliLitres8 = 0; totalMilliLitres8 = 0; previousMillis8 = 0; pulseCount9 = 0; flowRate9 = 0.0; flowMilliLitres9 = 0; totalMilliLitres9 = 0; previousMillis9 = 0; pulseCount10 = 0; flowRate10 = 0.0; flowMilliLitres10 = 0; totalMilliLitres10 = 0; previousMillis10 = 0; attachInterrupt(digitalPinToInterrupt(SENSOR1), pulseCount1er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR2), pulseCount2er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR3), pulseCount3er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR4), pulseCount4er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR5), pulseCount5er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR6), pulseCount6er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR7), pulseCount7er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR8), pulseCount8er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR9), pulseCount9er, FALLING); attachInterrupt(digitalPinToInterrupt(SENSOR10), pulseCount10er, FALLING); } void setupServer() { // Route to load style.css file server.on(""/style.css"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(SPIFFS, ""/style.css"", ""text/css""); }); // Route to load style.css file server.on(""/css.css"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(SPIFFS, ""/css.css"", ""text/css""); }); // Route for root / web page server.on(""/"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(SPIFFS, ""/index.html""); }); server.on(""/stats"", HTTP_GET, [](AsyncWebServerRequest *request) { buildStatsString(); request->send_P(200, ""text/plain"", statsString.c_str()); statsString = """"; // clear it so it can be built again next time }); server.on(""/beer1volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", dtostrf(beer1Volume, 6, 2, beer1LitresChar)); }); server.on(""/beer2volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer2LitresChar); }); server.on(""/beer3volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer3LitresChar); }); server.on(""/beer4volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer4LitresChar); }); server.on(""/beer5volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer5LitresChar); }); server.on(""/beer6volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer6LitresChar); }); server.on(""/beer7volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer7LitresChar); }); server.on(""/beer8volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer8LitresChar); }); server.on(""/beer9volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer9LitresChar); }); server.on(""/beer10volume"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beer10LitresChar); }); server.on(""/beer1name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer1Name).c_str()); Serial.println(""/beer1name endpoint hit!""); beerNameString = """"; }); server.on(""/beer2name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer2Name).c_str()); Serial.println(""/beer2name endpoint hit!""); beerNameString = """"; }); server.on(""/beer3name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer3Name).c_str()); Serial.println(""/beer3name endpoint hit!""); beerNameString = """"; }); server.on(""/beer4name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer4Name).c_str()); Serial.println(""/beer4name endpoint hit!""); beerNameString = """"; }); server.on(""/beer5name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer5Name).c_str()); Serial.println(""/beer5name endpoint hit!""); beerNameString = """"; }); server.on(""/beer6name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer6Name).c_str()); Serial.println(""/beer6name endpoint hit!""); beerNameString = """"; }); server.on(""/beer7name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer7Name).c_str()); Serial.println(""/beer7name endpoint hit!""); beerNameString = """"; }); server.on(""/beer8name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer8Name).c_str()); Serial.println(""/beer8name endpoint hit!""); beerNameString = """"; }); server.on(""/beer9name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer9Name).c_str()); Serial.println(""/beer9name endpoint hit!""); beerNameString = """"; }); server.on(""/beer10name"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(beer10Name).c_str()); Serial.println(""/beer10name endpoint hit!""); beerNameString = """"; }); server.on(""/allbeernames"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", beerNameStringConcatenator().c_str()); Serial.println(""/allbeernames endpoint hit!""); jsonBeerNamesString = """"; }); server.on(""/overviewchartname"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send_P(200, ""text/plain"", createNames(overviewChartName).c_str()); Serial.println(""/overviewchartname endpoint hit!""); beerNameString = """"; }); // Beer naming form server.on(""/settings"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(SPIFFS, ""/settings.html""); }); // Beer consumption over time server.on(""/consumption"", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(SPIFFS, ""/consumption.html""); }); // Send a GET request to /get?beerxname= server.on(""/get"", HTTP_GET, [](AsyncWebServerRequest *request) { String inputMessage; String inputParam; // GET input1 value on /get?PARAM_INPUT_0= if (request->hasParam(PARAM_INPUT_0)) // number of beers to display { inputMessage = request->getParam(PARAM_INPUT_0)->value(); inputParam = PARAM_INPUT_0; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putInt(""beersNumber"", inputMessage.toInt()); numberOfBeers = inputMessage.toInt(); Serial.println(""Number of beers to display saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_1)) // beer 2 name { inputMessage = request->getParam(PARAM_INPUT_1)->value(); inputParam = PARAM_INPUT_1; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer1Name"", inputMessage); beer1Name = inputMessage; totalMilliLitres1 = 0; Serial.println(""Beer 1 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_2)) // beer 2 name { inputMessage = request->getParam(PARAM_INPUT_2)->value(); inputParam = PARAM_INPUT_2; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer2Name"", inputMessage); beer2Name = inputMessage; totalMilliLitres2 = 0; Serial.println(""Beer 2 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_3)) // beer 3 name { inputMessage = request->getParam(PARAM_INPUT_3)->value(); inputParam = PARAM_INPUT_3; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer3Name"", inputMessage); beer3Name = inputMessage; totalMilliLitres3 = 0; Serial.println(""Beer 3 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_4)) // beer 4 name { inputMessage = request->getParam(PARAM_INPUT_4)->value(); inputParam = PARAM_INPUT_4; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer4Name"", inputMessage); beer4Name = inputMessage; totalMilliLitres4 = 0; Serial.println(""Beer 4 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_5)) // beer 5 name { inputMessage = request->getParam(PARAM_INPUT_5)->value(); inputParam = PARAM_INPUT_5; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer5Name"", inputMessage); beer5Name = inputMessage; totalMilliLitres5 = 0; Serial.println(""Beer 5 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_6)) // beer 6 name { inputMessage = request->getParam(PARAM_INPUT_6)->value(); inputParam = PARAM_INPUT_6; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer6Name"", inputMessage); beer6Name = inputMessage; totalMilliLitres6 = 0; Serial.println(""Beer 6 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_7)) { inputMessage = request->getParam(PARAM_INPUT_7)->value(); inputParam = PARAM_INPUT_7; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer7Name"", inputMessage); beer7Name = inputMessage; totalMilliLitres7 = 0; Serial.println(""Beer 7 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_8)) // beer 8 name { inputMessage = request->getParam(PARAM_INPUT_8)->value(); inputParam = PARAM_INPUT_8; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer8Name"", inputMessage); beer8Name = inputMessage; totalMilliLitres8 = 0; Serial.println(""Beer 8 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_9)) // beer 9 name { inputMessage = request->getParam(PARAM_INPUT_9)->value(); inputParam = PARAM_INPUT_9; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer9Name"", inputMessage); beer9Name = inputMessage; totalMilliLitres9 = 0; Serial.println(""Beer 9 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_10)) // beer 10 name { inputMessage = request->getParam(PARAM_INPUT_10)->value(); inputParam = PARAM_INPUT_10; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""beer10Name"", inputMessage); beer10Name = inputMessage; totalMilliLitres10 = 0; Serial.println(""Beer 10 name saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_11)) // beer 1 volume { inputMessage = request->getParam(PARAM_INPUT_11)->value(); inputParam = PARAM_INPUT_11; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer1Volume"", inputMessage.toInt() * 1000); beer1Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 1 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_12)) // beer 2 volume { inputMessage = request->getParam(PARAM_INPUT_12)->value(); inputParam = PARAM_INPUT_10; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer2Volume"", inputMessage.toInt() * 1000); beer2Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 2 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_13)) // beer 3 volume { inputMessage = request->getParam(PARAM_INPUT_13)->value(); inputParam = PARAM_INPUT_13; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer3Volume"", inputMessage.toInt() * 1000); beer3Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 3 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_14)) // beer 4 volume { inputMessage = request->getParam(PARAM_INPUT_14)->value(); inputParam = PARAM_INPUT_14; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer4Volume"", inputMessage.toInt() * 1000); beer4Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 4 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_15)) // beer 5 volume { inputMessage = request->getParam(PARAM_INPUT_15)->value(); inputParam = PARAM_INPUT_15; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer5Volume"", inputMessage.toInt() * 1000); beer5Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 5 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_16)) // beer 6 volume { inputMessage = request->getParam(PARAM_INPUT_16)->value(); inputParam = PARAM_INPUT_16; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer6Volume"", inputMessage.toInt() * 1000); beer6Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 6 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_17)) // beer 7 volume { inputMessage = request->getParam(PARAM_INPUT_17)->value(); inputParam = PARAM_INPUT_17; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer7Volume"", inputMessage.toInt() * 1000); beer7Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 7 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_18)) // beer 8 volume { inputMessage = request->getParam(PARAM_INPUT_18)->value(); inputParam = PARAM_INPUT_18; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer8Volume"", inputMessage.toInt() * 1000); beer8Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 8 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_19)) // beer 9 volume { inputMessage = request->getParam(PARAM_INPUT_19)->value(); inputParam = PARAM_INPUT_19; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer9Volume"", inputMessage.toInt() * 1000); beer9Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 9 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_20)) // beer 10 volume { inputMessage = request->getParam(PARAM_INPUT_20)->value(); inputParam = PARAM_INPUT_20; if (inputMessage != """") { preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer10Volume"", inputMessage.toInt() * 1000); beer10Volume = inputMessage.toFloat() * 1000; Serial.println(""Beer 10 volume saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_21)) // wifi SSID { inputMessage = request->getParam(PARAM_INPUT_21)->value(); inputParam = PARAM_INPUT_21; if (inputMessage != """") { preferences.begin(""credentials"", false); // tell preferences there is data coming preferences.putString(""pwifiSSID"", inputMessage); Serial.println(""WiFi SSID saved""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_22)) // wifi password { inputMessage = request->getParam(PARAM_INPUT_22)->value(); inputParam = PARAM_INPUT_22; if (inputMessage != """") { preferences.begin(""credentials"", false); // tell preferences there is data coming preferences.putString(""pwifiPassword"", inputMessage); Serial.println(""WiFi pasword saved s""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_23)) // reset the board { inputMessage = request->getParam(PARAM_INPUT_23)->value(); inputParam = PARAM_INPUT_23; resetFunc(); } else if (request->hasParam(PARAM_INPUT_24)) // reset the board { inputMessage = request->getParam(PARAM_INPUT_24)->value(); inputParam = PARAM_INPUT_24; if (inputMessage != """") { calibrationFactor = calibrationFactor * inputMessage.toFloat(); preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""calibrationFactor"", calibrationFactor); Serial.println(""Calibration factor saved s""); preferences.end(); // stop preferences from accepting data } } else if (request->hasParam(PARAM_INPUT_25)) // overview chart title { inputMessage = request->getParam(PARAM_INPUT_25)->value(); inputParam = PARAM_INPUT_25; if (inputMessage != """") { preferences.begin(""beerNames"", false); // tell preferences there is data coming preferences.putString(""overviewChartName"", inputMessage); overviewChartName = inputMessage; Serial.println(""Overview Chart Title saved""); preferences.end(); // stop preferences from accepting data } } else { inputMessage = ""No message sent""; inputParam = ""none""; } Serial.print(""Web form input: ""); Serial.println(inputMessage); //request->send(SPIFFS, ""/settings.html""); request->send(200, ""text/html"", ""HTTP GET request sent to your ESP on input field ("" + inputParam + "") with value: "" + inputMessage); }); server.onNotFound(notFound); } void blinkLED() { if (stopLED != 1) { unsigned long currentMillisLED = millis(); if (currentMillisLED - previousMillisLED >= blinkInterval) { // save the last time you blinked the LED previousMillisLED = currentMillisLED; // if the LED is off turn it on and vice-versa: if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; } // set the LED with the ledState of the variable: digitalWrite(LED_BUILTIN, ledState); } } } void buildStatsString() { for (int i = 0; i < numberOfBeers; i++) { if (i == 0) { statsString.concat(""[""); } statsString.concat(stats[i]); if (i < numberOfBeers - 1) { statsString.concat("",""); } if (i == numberOfBeers - 1) { statsString.concat(""]""); } } } String createNames(String data) { //beerNameString.concat(""{text: \\""""); beerNameString.concat(data); //beerNameString.concat(""\\""}""); Serial.println(beerNameString); return beerNameString; } String beerNameStringConcatenator() { jsonBeerNamesString = """"; createBeerNames(); return jsonBeerNamesString; } void createBeerNames() { for (int i = 0; i < numberOfBeers; i++) { if (i == 0) { jsonBeerNamesString.concat(""[""); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer1Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 1) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer2Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 2) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer3Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 3) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer4Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 4) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer5Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 5) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer6Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 6) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer7Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 7) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer8Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 8) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer9Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat("",""); } if (i == 9) { jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(beer10Name); jsonBeerNamesString.concat(""\\""""); jsonBeerNamesString.concat(""]""); } } } void readFlows() { currentMillis1 = millis(); if (currentMillis1 - previousMillis1 > interval) { pulseSec1 = pulseCount1; pulseCount1 = 0; if (pulseSec1 == 48) // some weird AF bug with phantom pulses... { pulseSec1 = 0; } // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate1 = ((1000.0 / (millis() - previousMillis1)) * pulseSec1) / calibrationFactor; previousMillis1 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres1 = (flowRate1 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres1 += flowMilliLitres1; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer1Volume = beer1Volume - flowMilliLitres1; // need to divide by 1000 on the receiving side if (flowMilliLitres1 > 0) { Serial.print(""Beer 1 volume remaining: ""); Serial.println(beer1Volume); } } currentMillis2 = millis(); if (currentMillis2 - previousMillis2 > interval) { pulseSec2 = pulseCount2; pulseCount2 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate2 = ((1000.0 / (millis() - previousMillis2)) * pulseSec2) / calibrationFactor; previousMillis2 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres2 = (flowRate2 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres2 += flowMilliLitres2; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer2Litres = beer2Volume - totalMilliLitres2; // need to divide by 1000 on the receiving side dtostrf(beer2Litres, 6, 2, beer2LitresChar); if (flowMilliLitres2 > 0) { Serial.print(""Beer 2 millilitres: ""); Serial.println(beer2LitresChar); } } currentMillis3 = millis(); if (currentMillis3 - previousMillis3 > interval) { pulseSec3 = pulseCount3; pulseCount3 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate3 = ((1000.0 / (millis() - previousMillis3)) * pulseSec3) / calibrationFactor; previousMillis3 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres3 = (flowRate3 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres3 += flowMilliLitres3; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer3Litres = beer3Volume - totalMilliLitres3; // need to divide by 1000 on the receiving side dtostrf(beer3Litres, 6, 2, beer3LitresChar); if (flowMilliLitres3 > 0) { Serial.print(""Beer 3 millilitres: ""); Serial.println(beer3LitresChar); } } currentMillis4 = millis(); if (currentMillis4 - previousMillis4 > interval) { pulseSec4 = pulseCount4; pulseCount4 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate4 = ((1000.0 / (millis() - previousMillis4)) * pulseSec4) / calibrationFactor; previousMillis4 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres4 = (flowRate4 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres4 += flowMilliLitres4; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer4Litres = beer4Volume - totalMilliLitres4; // need to divide by 1000 on the receiving side dtostrf(beer4Litres, 6, 2, beer4LitresChar); if (flowMilliLitres4 > 0) { Serial.print(""Beer 4 millilitres: ""); Serial.println(beer4LitresChar); } } currentMillis5 = millis(); if (currentMillis5 - previousMillis5 > interval) { pulseSec5 = pulseCount5; pulseCount5 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate5 = ((1000.0 / (millis() - previousMillis5)) * pulseSec5) / calibrationFactor; previousMillis5 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres5 = (flowRate5 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres5 += flowMilliLitres5; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer5Litres = beer5Volume - totalMilliLitres5; // need to divide by 1000 on the receiving side dtostrf(beer5Litres, 6, 2, beer5LitresChar); if (flowMilliLitres5 > 0) { Serial.print(""Beer 5 millilitres: ""); Serial.println(beer5LitresChar); } } currentMillis6 = millis(); if (currentMillis6 - previousMillis6 > interval) { pulseSec6 = pulseCount6; pulseCount6 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate6 = ((1000.0 / (millis() - previousMillis6)) * pulseSec6) / calibrationFactor; previousMillis6 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres6 = (flowRate6 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres6 += flowMilliLitres6; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer6Litres = beer6Volume - totalMilliLitres6; // need to divide by 1000 on the receiving side dtostrf(beer6Litres, 6, 2, beer6LitresChar); if (flowMilliLitres6 > 0) { Serial.print(""Beer 6 millilitres: ""); Serial.println(beer6LitresChar); } } currentMillis7 = millis(); if (currentMillis7 - previousMillis7 > interval) { pulseSec7 = pulseCount7; pulseCount7 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate7 = ((1000.0 / (millis() - previousMillis7)) * pulseSec7) / calibrationFactor; previousMillis7 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres7 = (flowRate7 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres7 += flowMilliLitres7; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer7Litres = beer7Volume - totalMilliLitres7; // need to divide by 1000 on the receiving side dtostrf(beer7Litres, 6, 2, beer7LitresChar); if (flowMilliLitres7 > 0) { Serial.print(""Beer 7 millilitres: ""); Serial.println(beer7LitresChar); } } currentMillis8 = millis(); if (currentMillis8 - previousMillis8 > interval) { pulseSec8 = pulseCount8; pulseCount8 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate8 = ((1000.0 / (millis() - previousMillis8)) * pulseSec8) / calibrationFactor; previousMillis8 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres8 = (flowRate8 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres8 += flowMilliLitres8; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer8Litres = beer8Volume - totalMilliLitres8; // need to divide by 1000 on the receiving side dtostrf(beer8Litres, 6, 2, beer8LitresChar); if (flowMilliLitres8 > 0) { Serial.print(""Beer 8 millilitres: ""); Serial.println(beer8LitresChar); } } currentMillis9 = millis(); if (currentMillis9 - previousMillis9 > interval) { pulseSec9 = pulseCount9; pulseCount9 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate9 = ((1000.0 / (millis() - previousMillis9)) * pulseSec9) / calibrationFactor; previousMillis9 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres9 = (flowRate9 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres9 += flowMilliLitres9; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer9Litres = beer9Volume - totalMilliLitres9; // need to divide by 1000 on the receiving side dtostrf(beer9Litres, 6, 2, beer9LitresChar); if (flowMilliLitres9 > 0) { Serial.print(""Beer 9 millilitres: ""); Serial.println(beer9LitresChar); } } currentMillis10 = millis(); if (currentMillis10 - previousMillis10 > interval) { pulseSec10 = pulseCount10; pulseCount10 = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate10 = ((1000.0 / (millis() - previousMillis10)) * pulseSec10) / calibrationFactor; previousMillis10 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres10 = (flowRate10 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres10 += flowMilliLitres10; // Print the flow rate for this second in litres / minute //Serial.print(""Flow rate: ""); //Serial.print(int(flowRate1)); // Print the integer part of the variable //Serial.print(""L/min""); //Serial.print(""\\t""); // Print tab space // Print the cumulative total of litres flowed since starting //Serial.print(""Output Liquid Quantity: ""); //Serial.print(totalMilliLitres); //Serial.print(""mL / ""); beer10Litres = beer10Volume - totalMilliLitres10; // need to divide by 1000 on the receiving side dtostrf(beer10Litres, 6, 2, beer10LitresChar); if (flowMilliLitres10 > 0) { Serial.print(""Beer 10 millilitres: ""); Serial.println(beer10LitresChar); } } } void retrieveVolumes() { preferences.begin(""beerVolumes"", false); int tempNumberOfBeers = preferences.getFloat(""beersNumber"", 0); if (tempNumberOfBeers != 0) { numberOfBeers = tempNumberOfBeers; // protect against numberOfBeers not being set } beer1Volume = preferences.getFloat(""beer1Volume"", 0); tempBeer1Volume = beer1Volume; beer2Volume = preferences.getFloat(""beer2Volume"", 0); tempBeer2Volume = beer2Volume; beer3Volume = preferences.getFloat(""beer3Volume"", 0); tempBeer3Volume = beer3Volume; beer4Volume = preferences.getFloat(""beer4Volume"", 0); tempBeer4Volume = beer4Volume; beer5Volume = preferences.getFloat(""beer5Volume"", 0); tempBeer5Volume = beer5Volume; beer6Volume = preferences.getFloat(""beer6Volume"", 0); tempBeer6Volume = beer6Volume; beer7Volume = preferences.getFloat(""beer7Volume"", 0); tempBeer7Volume = beer7Volume; beer8Volume = preferences.getFloat(""beer8Volume"", 0); tempBeer8Volume = beer8Volume; beer9Volume = preferences.getFloat(""beer9Volume"", 0); tempBeer9Volume = beer9Volume; beer10Volume = preferences.getFloat(""beer10Volume"", 0); tempBeer10Volume = beer10Volume; float tempcalibrationFactor = preferences.getFloat(""calibrationFactor"", 0); Serial.print(""Stored calibration factor: ""); Serial.println(tempcalibrationFactor); if (tempcalibrationFactor != 0.00) { calibrationFactor = tempcalibrationFactor; } preferences.end(); // stop preferences from accepting data } void retrieveNames() { preferences.begin(""beerNames"", false); if (preferences.getString(""beer1Name"", """") != """") { beer1Name = preferences.getString(""beer1Name"", """"); } if (preferences.getString(""beer2Name"", """") != """") { beer2Name = preferences.getString(""beer2Name"", """"); } if (preferences.getString(""beer3Name"", """") != """") { beer3Name = preferences.getString(""beer3Name"", """"); } if (preferences.getString(""beer4Name"", """") != """") { beer4Name = preferences.getString(""beer4Name"", """"); } if (preferences.getString(""beer5Name"", """") != """") { beer5Name = preferences.getString(""beer5Name"", """"); } if (preferences.getString(""beer6Name"", """") != """") { beer6Name = preferences.getString(""beer6Name"", """"); } if (preferences.getString(""beer7Name"", """") != """") { beer7Name = preferences.getString(""beer7Name"", """"); } if (preferences.getString(""beer8Name"", """") != """") { beer8Name = preferences.getString(""beer8Name"", """"); } if (preferences.getString(""beer9Name"", """") != """") { beer9Name = preferences.getString(""beer9Name"", """"); } if (preferences.getString(""beer10Name"", """") != """") { beer10Name = preferences.getString(""beer10Name"", """"); } if (preferences.getString(""overviewChartName"", """") != """") { overviewChartName = preferences.getString(""overviewChartName"", """"); } else { overviewChartName = ""Beers on Tap""; } preferences.end(); // stop preferences from accepting data } void syncVolumes() { Serial.println(""Checking to see if beet volumes need syncing...""); if (tempBeer1Volume != beer1Volume) { tempBeer1Volume = beer1Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer1Volume"", tempBeer1Volume); Serial.println(""Beer 1 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer2Volume != beer2Volume) { tempBeer2Volume = beer2Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer2Volume"", tempBeer2Volume); Serial.println(""Beer 2 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer3Volume != beer3Volume) { tempBeer3Volume = beer3Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer3Volume"", tempBeer3Volume); Serial.println(""Beer 3 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer4Volume != beer4Volume) { tempBeer4Volume = beer4Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer4Volume"", tempBeer4Volume); Serial.println(""Beer 4 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer5Volume != beer5Volume) { tempBeer5Volume = beer5Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer5Volume"", tempBeer5Volume); Serial.println(""Beer 5 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer6Volume != beer6Volume) { tempBeer6Volume = beer6Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer6Volume"", tempBeer6Volume); Serial.println(""Beer 6 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer7Volume != beer7Volume) { tempBeer7Volume = beer7Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer7Volume"", tempBeer7Volume); Serial.println(""Beer 7 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer8Volume != beer8Volume) { tempBeer8Volume = beer8Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer8Volume"", tempBeer8Volume); Serial.println(""Beer 8 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer9Volume != beer9Volume) { tempBeer9Volume = beer9Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer9Volume"", tempBeer9Volume); Serial.println(""Beer 9 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } if (tempBeer10Volume != beer10Volume) { tempBeer10Volume = beer10Volume; preferences.begin(""beerVolumes"", false); // tell preferences there is data coming preferences.putFloat(""beer10Volume"", tempBeer10Volume); Serial.println(""Beer 10 volume synced due to change in volumes since last poll...""); preferences.end(); // stop preferences from accepting data } Serial.println(""Beer volume sync complet!""); } void createStats() { stats[0] = beer1Volume / 1000; stats[1] = beer2Volume / 1000; stats[2] = beer3Volume / 1000; stats[3] = beer4Volume / 1000; stats[4] = beer5Volume / 1000; stats[5] = beer6Volume / 1000; stats[6] = beer7Volume / 1000; stats[7] = beer8Volume / 1000; stats[8] = beer9Volume / 1000; stats[9] = beer10Volume / 1000; } void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, ledState); // signal error via SYS LED, forced on, no blink // Serial port for debugging purposes Serial.begin(115200); Serial.println(""""); timer.setInterval(300000L, syncVolumes); // Sync beer volumes every 5 minutes setupFlowData(); retrieveNames(); retrieveVolumes(); // Initialize SPIFFS if (!SPIFFS.begin()) { Serial.println(""An Error has occurred while mounting SPIFFS (webserver is broken!)""); Serial.println(""Please upload anew SPIFFS image""); return; } // Connect to Wi-Fi Serial.println(""Reading saved WiFi SSID and WiFi password""); preferences.begin(""credentials"", false); pwifiSSID = preferences.getString(""pwifiSSID"", """"); pwifiPassword = preferences.getString(""pwifiPassword"", """"); preferences.end(); // stop preferences from accepting data if (pwifiSSID == """" || pwifiPassword == """") { Serial.println(""No values saved for WiFi SSID or WiFi password""); WiFi.softAP(""KegTastic"", ""BeerTastic""); Serial.println(); Serial.print(""IP address: ""); Serial.println(WiFi.softAPIP()); Serial.print(""SSID: ""); Serial.println(""KegTastic""); Serial.print(""Password: ""); Serial.println(""BeerTastic""); blinkInterval = 100; stopLED = 0; } else { // Connect to Wi-Fi WiFi.mode(WIFI_STA); WiFi.begin(pwifiSSID.c_str(), pwifiPassword.c_str()); Serial.println(""Connecting to WiFi ...""); while (WiFi.status() != WL_CONNECTED) { wifiDisconnected++; Serial.print('.'); delay(1000); if (wifiDisconnected > 30) // if no wifi during boot for more than 30 seconds { Serial.println(""WiFi did not connect in time...""); Serial.println(""Forcing WiFi setup routine""); Serial.println(""Look for Beertastic AP and setup WiFi via http://192.168.4.1/settings""); Serial.println(""Cheers!""); preferences.begin(""credentials"", false); // tell preferences there is data coming preferences.putString(""pwifiPassword"", """"); preferences.putString(""pwifiSSID"", """"); Serial.println(""WiFi SSID and pasword cleared!""); preferences.end(); // stop preferences from accepting data Serial.println(""Rebooting...""); resetFunc(); } } blinkInterval = 1000; stopLED = 0; Serial.println(WiFi.localIP()); } initWebSocket(); setupServer(); // Start web server server.begin(); // Start ElegantOTA AsyncElegantOTA.begin(&server); } void loop() { timer.run(); blinkLED(); readFlows(); syncVolumes; createStats(); createBeerNames(); AsyncElegantOTA.loop(); ws.cleanupClients(); }",16284,True,3127.891139559918,median "#include /* TimeLapseAvi ESP32-CAM Video Recorder This program records an AVI video on the SD Card of an ESP32-CAM. by James Zahary July 20, 2019 TimeLapseAvi23x.ino jamzah.plc@gmail.com https://github.com/jameszah/ESP32-CAM-Video-Recorder jameszah/ESP32-CAM-Video-Recorder is licensed under the GNU General Public License v3.0 The is Arduino code, with standard setup for ESP32-CAM - Board ESP32 Wrover Module - Partition Scheme Huge APP (3MB No OTA) */ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // edit these parameters for your needs static const char vernum[] = ""v20061""; static const char devname[] = ""desklens""; // name of your camera for mDNS, Router, and filenames #define TIMEZONE ""CST-8"" // your timezone - this is GMT // 1 for blink red led with every sd card write, at your frame rate // 0 for blink only for skipping frames and SOS if camera or sd is broken #define BlinkWithWrite 0 // EDIT ssid and password const char ssid[] = ""LinkTest""; // your wireless network name (SSID) const char password[] = ""87654321""; // your Wi-Fi network password // startup defaults for first recording // here are the recording options from the ""retart web page"" // VGA 10 fps for 30 min, repeat, realtime http://192.168.0.117/start?framesize=VGA&length=1800&interval=100&quality=10&repeat=100&speed=1&gray=0 // VGA 2 fps, for 30 minutes repeat, 30x playback http://192.168.0.117/start?framesize=VGA&length=1800&interval=500&quality=10&repeat=300&speed=30&gray=0 // UXGA 1 sec per frame, for 30 minutes repeat, 30x playback http://192.168.0.117/start?framesize=UXGA&length=1800&interval=1000&quality=10&repeat=100&speed=30&gray=0 // UXGA 2 fps for 30 minutes repeat, 15x playback http://192.168.0.117/start?framesize=UXGA&length=1800&interval=500&quality=10&repeat=100&speed=30&gray=0 // CIF 20 fps second for 30 minutes repeat http://192.168.0.117/start?framesize=CIF&length=1800&interval=50&quality=10&repeat=100&speed=1&gray=0 // reboot startup parameters here int record_on_reboot = 0; // set to 1 to record, or 0 to NOT record on reboot int framesize = 7; // vga (10 UXGA, 7 SVGA, 6 VGA, 5 CIF) int repeat = 100; // 100 files int xspeed = 1; // 1x playback speed (realtime is 1) int gray = 0; // not gray int quality = 10; // 10 on the 0..64 scale, or 10..50 subscale - 10 is good, 20 is grainy and smaller files int capture_interval = 100; // 100 ms or 10 frames per second int total_frames = 18000; // 18000 frames = 10 fps * 60 seconds * 30 minutes = half hour int PIRpin = 12; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int new_config = 5; // this system abandoned ! int xlength = total_frames * capture_interval / 1000; int recording = 0; int PIRstatus = 0; int PIRrecording = 0; int ready = 0; //#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE #include ""esp_log.h"" #include ""esp_http_server.h"" #include ""esp_camera.h"" #include #include ""ESP32FtpServer.h"" #include FtpServer ftpSrv; //set #define FTP_DEBUG in ESP32FtpServer.h to see ftp verbose on serial // Time #include ""time.h"" // MicroSD #include ""driver/sdmmc_host.h"" #include ""driver/sdmmc_defs.h"" #include ""sdmmc_cmd.h"" #include ""esp_vfs_fat.h"" #include long current_millis; long last_capture_millis = 0; static esp_err_t cam_err; static esp_err_t card_err; char strftime_buf[64]; int file_number = 0; bool internet_connected = false; struct tm timeinfo; time_t now; char *filename ; char *stream ; int newfile = 0; int frames_so_far = 0; FILE *myfile; long bp; long ap; long bw; long aw; long totalp; long totalw; float avgp; float avgw; int overtime_count = 0; // CAMERA_MODEL_AI_THINKER #define PWDN_GPIO_NUM 32 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 0 #define SIOD_GPIO_NUM 26 #define SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #define Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 21 #define Y4_GPIO_NUM 19 #define Y3_GPIO_NUM 18 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22 // GLOBALS #define BUFFSIZE 512 // global variable used by these pieces char str[20]; uint16_t n; uint8_t buf[BUFFSIZE]; static int i = 0; uint8_t temp = 0, temp_last = 0; unsigned long fileposition = 0; uint16_t frame_cnt = 0; uint16_t remnant = 0; uint32_t length = 0; uint32_t startms; uint32_t elapsedms; uint32_t uVideoLen = 0; bool is_header = false; long bigdelta = 0; int other_cpu_active = 0; int skipping = 0; int skipped = 0; int fb_max = 12; camera_fb_t * fb_q[30]; int fb_in = 0; int fb_out = 0; camera_fb_t * fb = NULL; FILE *avifile = NULL; FILE *idxfile = NULL; #define AVIOFFSET 240 // AVI main header length unsigned long movi_size = 0; unsigned long jpeg_size = 0; unsigned long idx_offset = 0; uint8_t zero_buf[4] = {0x00, 0x00, 0x00, 0x00}; uint8_t dc_buf[4] = {0x30, 0x30, 0x64, 0x63}; // ""00dc"" uint8_t avi1_buf[4] = {0x41, 0x56, 0x49, 0x31}; // ""AVI1"" uint8_t idx1_buf[4] = {0x69, 0x64, 0x78, 0x31}; // ""idx1"" uint8_t vga_w[2] = {0x80, 0x02}; // 640 uint8_t vga_h[2] = {0xE0, 0x01}; // 480 uint8_t cif_w[2] = {0x90, 0x01}; // 400 uint8_t cif_h[2] = {0x28, 0x01}; // 296 uint8_t svga_w[2] = {0x20, 0x03}; // 800 uint8_t svga_h[2] = {0x58, 0x02}; // 600 uint8_t uxga_w[2] = {0x40, 0x06}; // 1600 uint8_t uxga_h[2] = {0xB0, 0x04}; // 1200 const int avi_header[AVIOFFSET] PROGMEM = { 0x52, 0x49, 0x46, 0x46, 0xD8, 0x01, 0x0E, 0x00, 0x41, 0x56, 0x49, 0x20, 0x4C, 0x49, 0x53, 0x54, 0xD0, 0x00, 0x00, 0x00, 0x68, 0x64, 0x72, 0x6C, 0x61, 0x76, 0x69, 0x68, 0x38, 0x00, 0x00, 0x00, 0xA0, 0x86, 0x01, 0x00, 0x80, 0x66, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4C, 0x49, 0x53, 0x54, 0x84, 0x00, 0x00, 0x00, 0x73, 0x74, 0x72, 0x6C, 0x73, 0x74, 0x72, 0x68, 0x30, 0x00, 0x00, 0x00, 0x76, 0x69, 0x64, 0x73, 0x4D, 0x4A, 0x50, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x74, 0x72, 0x66, 0x28, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x4D, 0x4A, 0x50, 0x47, 0x00, 0x84, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x4E, 0x46, 0x4F, 0x10, 0x00, 0x00, 0x00, 0x6A, 0x61, 0x6D, 0x65, 0x73, 0x7A, 0x61, 0x68, 0x61, 0x72, 0x79, 0x20, 0x76, 0x36, 0x30, 0x20, 0x4C, 0x49, 0x53, 0x54, 0x00, 0x01, 0x0E, 0x00, 0x6D, 0x6F, 0x76, 0x69, }; bool timeSet = 0;//未设置系统时间 暂停移动侦测 // Motion detection test - looks for diffs between camera images. #include ""motionDetect.h"" bool debug = true; uint8_t fsizePtr = FRAMESIZE_SVGA; // framesize selection uint8_t lightLevel; // Current ambient light level uint8_t nightSwitch = 10; // white level % for night/day switching uint8_t motionVal = 7; // motion sensitivity difference setting bool haveMotion = false; long lastDetection = 0;//上一次检测的时间 struct frameStruct { const char* frameSizeStr; const uint16_t frameWidth; const uint16_t frameHeight; const uint16_t defaultFPS; const uint8_t scaleFactor; const uint8_t sampleRate; }; // sample factors, 5th arg is scaling factor (1..N), 6th arg is sample factor (0..3) // indexed by frame size - needs to be consistent with sensor.h enum // #include ""sensor.h"" extern const frameStruct frameData[] = { {""QQVGA"", 160, 120, 25, 2, 1}, {""n/a"", 0, 0, 0, 0, 1}, {""n/a"", 0, 0, 0, 0, 1}, {""HQVGA"", 240, 176, 25, 3, 1}, {""QVGA"", 320, 240, 25, 3, 1}, {""CIF"", 400, 296, 25, 3, 1}, {""VGA"", 640, 480, 15, 3, 2}, {""SVGA"", 800, 600, 10, 3, 2}, {""XGA"", 1024, 768, 5, 3, 3}, {""SXGA"", 1280, 1024, 3, 3, 4}, {""UXGA"", 1600, 1200, 2, 6, 5} }; bool motionDetection(camera_fb_t* fb, bool motionStatus); bool isNight(uint8_t nightSwitch); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // AviWriterTask runs on cpu 1 to write the avi file // TaskHandle_t CameraTask, AviWriterTask; SemaphoreHandle_t baton; int counter = 0; void codeForAviWriterTask( void * parameter ) { for (;;) { if (ready) { make_avi(); } delay(1); } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // CameraTask runs on cpu 0 to take pictures and drop them in a queue // void codeForCameraTask( void * parameter ) { for (;;) { if (other_cpu_active == 1 ) { current_millis = millis(); if (current_millis - last_capture_millis > capture_interval) { last_capture_millis = millis(); xSemaphoreTake( baton, portMAX_DELAY ); if ( ( (fb_in + fb_max - fb_out) % fb_max) + 1 == fb_max ) { xSemaphoreGive( baton ); Serial.print("" Queue Full, Skipping ... ""); // the queue is full skipped++; skipping = 1; } if (skipping > 0 ) { if (!BlinkWithWrite) { digitalWrite(33, LOW); } if (skipping % 2 == 0) { // skip every other frame until queue is cleared frames_so_far = frames_so_far + 1; frame_cnt++; fb_in = (fb_in + 1) % fb_max; bp = millis(); fb_q[fb_in] = esp_camera_fb_get(); totalp = totalp - bp + millis(); } else { Serial.print(((fb_in + fb_max - fb_out) % fb_max)); // skip an extra frame to empty the queue skipped++; } skipping = skipping + 1; if (((fb_in + fb_max - fb_out) % fb_max) == 0 ) { skipping = 0; Serial.println("" Queue cleared. ""); } xSemaphoreGive( baton ); } else { skipping = 0; frames_so_far = frames_so_far + 1; frame_cnt++; fb_in = (fb_in + 1) % fb_max; bp = millis(); fb_q[fb_in] = esp_camera_fb_get(); totalp = totalp - bp + millis(); xSemaphoreGive( baton ); } } } delay(1); } } // // Writes an uint32_t in Big Endian at current file position // static void inline print_quartet(unsigned long i, FILE * fd) { uint8_t x[1]; x[0] = i % 0x100; size_t i1_err = fwrite(x , 1, 1, fd); i = i >> 8; x[0] = i % 0x100; size_t i2_err = fwrite(x , 1, 1, fd); i = i >> 8; x[0] = i % 0x100; size_t i3_err = fwrite(x , 1, 1, fd); i = i >> 8; x[0] = i % 0x100; size_t i4_err = fwrite(x , 1, 1, fd); } void startCameraServer(); httpd_handle_t camera_httpd = NULL; char the_page[3000]; char localip[20]; WiFiEventId_t eventID; #include ""soc/soc.h"" #include ""soc/rtc_cntl_reg.h"" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // setup() runs on cpu 1 // void setup() { WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector // creates other problems delay(1000);//电容充电 Serial.begin(115200); Serial.setDebugOutput(true); // zzz Serial.println("" ""); Serial.println(""-------------------------------------""); Serial.printf(""ESP-CAM Video Recorder %s\\n"", vernum); Serial.printf("" http://%s.local - to access the camera\\n"", devname); Serial.println(""-------------------------------------""); pinMode(33, OUTPUT); // little red led on back of chip digitalWrite(33, LOW); // turn on the red LED on the back of chip if (init_wifi()) { // Connected to WiFi internet_connected = true; } // init_time();//离线模式不需要设置时间 if (!psramFound()) { Serial.println(""paraFound wrong - major fail""); major_fail(); } // SD camera init card_err = init_sdcard(); if (card_err != ESP_OK) { Serial.printf(""SD Card init failed with error 0x%x"", card_err); major_fail(); return; } startCameraServer(); // zzz username and password for ftp server ftpSrv.begin(""esp"", ""esp""); Serial.printf(""Total space: %lluMB\\n"", SD_MMC.totalBytes() / (1024 * 1024)); Serial.printf(""Used space: %lluMB\\n"", SD_MMC.usedBytes() / (1024 * 1024)); digitalWrite(33, HIGH); // red light turns off when setup is complete baton = xSemaphoreCreateMutex(); xTaskCreatePinnedToCore( codeForCameraTask, ""CameraTask"", 10000, NULL, 1, &CameraTask, 0); delay(50); xTaskCreatePinnedToCore( codeForAviWriterTask, ""AviWriterTask"", 10000, NULL, 2, &AviWriterTask, 1); delay(50); recording = 0; // we are NOT recording config_camera(); pinMode(4, OUTPUT); // using 1 bit mode, shut off the Blinding Disk-Active Light digitalWrite(4, LOW); pinMode(PIRpin, INPUT_PULLDOWN); // or PULLDOWN for active high newfile = 0; // no file is open // don't fiddle with this! recording = record_on_reboot; ready = 1; Serial.print(""Camera Ready! Use 'http://""); Serial.print(WiFi.softAPIP()); Serial.println(""' to connect""); } // // if we have no camera, or sd card, then flash rear led on and off to warn the human SOS - SOS // void major_fail() { Serial.println("" ""); for (int i = 0; i < 10; i++) { // 10 loops or about 100 seconds then reboot digitalWrite(33, LOW); delay(150); digitalWrite(33, HIGH); delay(150); digitalWrite(33, LOW); delay(150); digitalWrite(33, HIGH); delay(150); digitalWrite(33, LOW); delay(150); digitalWrite(33, HIGH); delay(150); delay(1000); digitalWrite(33, LOW); delay(500); digitalWrite(33, HIGH); delay(500); digitalWrite(33, LOW); delay(500); digitalWrite(33, HIGH); delay(500); digitalWrite(33, LOW); delay(500); digitalWrite(33, HIGH); delay(500); delay(1000); Serial.print(""Major Fail ""); Serial.print(i); Serial.print("" / ""); Serial.println(10); } ESP.restart(); } void init_time(){ // configTime(0, 0, ""pool.ntp.org""); setenv(""TZ"", TIMEZONE, 1); // mountain time zone from #define at top tzset(); time_t now ; timeinfo = { 0 }; int retry = 0; const int retry_count = 10; delay(1000); time(&now); localtime_r(&now, &timeinfo); while (timeinfo.tm_year < (2016 - 1900) && ++retry < retry_count) { Serial.printf(""Waiting for system time to be set... (%d/%d) -- %d\\n"", retry, retry_count, timeinfo.tm_year); delay(1000); time(&now); localtime_r(&now, &timeinfo); } Serial.println(ctime(&now)); } bool init_wifi() { int connAttempts = 0; // WiFi.disconnect(true); WiFi.mode(WIFI_AP); // Set your Static IP address IPAddress local_IP(10, 10, 1, 1); // Set your Gateway IP address IPAddress gateway(10, 10, 1, 1); IPAddress subnet(255, 255, 255, 0); WiFi.setHostname(devname); //WiFi.printDiag(Serial); WiFi.softAP(ssid, password); delay(1000); // while (WiFi.status() != WL_CONNECTED ) { // delay(500); // Serial.print("".""); // if (connAttempts == 10) { // Serial.println(""Cannot connect - try again""); // WiFi.begin(ssid, password); // WiFi.printDiag(Serial); // } // if (connAttempts == 20) { // Serial.println(""Cannot connect - fail""); // WiFi.printDiag(Serial); // return false; // } // connAttempts++; // } Serial.println(""AP start""); sprintf(localip, ""%s"", WiFi.softAPIP().toString().c_str()); //WiFi.printDiag(Serial); if (!MDNS.begin(devname)) { Serial.println(""Error setting up MDNS responder!""); } else { Serial.printf(""mDNS responder started '%s'\\n"", devname); } return true; } static esp_err_t init_sdcard() { esp_err_t ret = ESP_FAIL; sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.flags = SDMMC_HOST_FLAG_1BIT; // using 1 bit mode host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); slot_config.width = 1; // using 1 bit mode //Serial.print(""Slot config width should be 4 width: ""); Serial.println(slot_config.width); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = false, .max_files = 5, }; //pinMode(4, OUTPUT); // using 1 bit mode, shut off the Blinding Disk-Active Light //digitalWrite(4, LOW); sdmmc_card_t *card; Serial.println(""Mounting SD card...""); ret = esp_vfs_fat_sdmmc_mount(""/sdcard"", &host, &slot_config, &mount_config, &card); if (ret == ESP_OK) { Serial.println(""SD card mount successfully!""); } else { Serial.printf(""Failed to mount SD card VFAT filesystem. Error: %s"", esp_err_to_name(ret)); major_fail(); } sdmmc_card_print_info(stdout, card); Serial.print(""SD_MMC Begin: ""); Serial.println(SD_MMC.begin()); // required by ftp system ?? } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Make the avi move in 4 pieces // // make_avi() called in every loop, which calls below, depending on conditions // start_avi() - open the file and write headers // another_pic_avi() - write one more frame of movie // end_avi() - write the final parameters and close the file void make_avi( ) { //摄像头移动侦测 if (timeSet == 1)//当时间设置完才开始移动侦测 { if (millis() - lastDetection > 200){ xSemaphoreTake( baton, portMAX_DELAY ); camera_fb_t* fb = esp_camera_fb_get(); lastDetection = millis(); if (fb) { // uint8_t nightSwitch = 10; // white level % for night/day switching // isNight(nightSwitch); haveMotion = motionDetection(fb, haveMotion); if (haveMotion == 1 && isNight(10)) { haveMotion = 0; } Serial.println(haveMotion); esp_camera_fb_return(fb); } else Serial.println(""detection:Failed to get frame""); xSemaphoreGive( baton ); if(millis() - lastDetection > 4000){ haveMotion = false; } } if (haveMotion == 1) { if (PIRrecording == 1) { // keep recording for 15 more seconds if ( (millis() - startms) > (total_frames * capture_interval - 5000) ) { total_frames = total_frames + 10000 / capture_interval ; Serial.println(""Add another 10 seconds""); } } else { if ( recording == 0 && newfile == 0) { //start a pir recording with current parameters, except no repeat and 15 seconds Serial.println(""Start a PIR(by cam)""); PIRrecording = 1; repeat = 0; total_frames = 15000 / capture_interval; xlength = total_frames * capture_interval / 1000; recording = 1; } } } } // 红外热释电移动侦测 PIRstatus = digitalRead(PIRpin); if (PIRstatus == 1) { if (PIRrecording == 1) { // keep recording for 15 more seconds if ( (millis() - startms) > (total_frames * capture_interval - 5000) ) { // total_frames = total_frames + 10 * 1000 / capture_interval ; total_frames = total_frames + 10000 / capture_interval ; Serial.println(""Add another 10 seconds""); } } else { if ( recording == 0 && newfile == 0) { //start a pir recording with current parameters, except no repeat and 15 seconds Serial.println(""Start a PIR""); PIRrecording = 1; repeat = 0; total_frames = 15000 / capture_interval; xlength = total_frames * capture_interval / 1000; recording = 1; } } } // we are recording, but no file is open if (newfile == 0 && recording == 1) { // open the file digitalWrite(33, HIGH); newfile = 1; start_avi(); } else { // we have a file open, but not recording if (newfile == 1 && recording == 0) { // got command to close file digitalWrite(33, LOW); end_avi(); Serial.println(""Done capture due to command""); frames_so_far = total_frames; newfile = 0; // file is closed recording = 0; // DO NOT start another recording PIRrecording = 0; } else { if (newfile == 1 && recording == 1) { // regular recording if (frames_so_far >= total_frames) { // we are done the recording Serial.println(""Done capture for total frames!""); digitalWrite(33, LOW); // close the file end_avi(); frames_so_far = 0; newfile = 0; // file is closed if (repeat > 0) { recording = 1; // start another recording repeat = repeat - 1; } else { recording = 0; PIRrecording = 0; } } else if ((millis() - startms) > (total_frames * capture_interval)) { // time is up, even though we have not done all the frames Serial.println ("" ""); Serial.println(""Done capture for time""); Serial.print(""Time Elapsed: ""); Serial.print(millis() - startms); Serial.print("" Frames: ""); Serial.println(frame_cnt); Serial.print(""Config: ""); Serial.print(total_frames * capture_interval ) ; Serial.print("" (""); Serial.print(total_frames); Serial.print("" x ""); Serial.print(capture_interval); Serial.println("")""); digitalWrite(33, LOW); // close the file end_avi(); frames_so_far = 0; newfile = 0; // file is closed if (repeat > 0) { recording = 1; // start another recording repeat = repeat - 1; } else { recording = 0; PIRrecording = 0; } } else { // regular another_save_avi(); } } } } } static esp_err_t config_camera() { camera_config_t config; //Serial.println(""config camera""); if (new_config == 5) { config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; config.frame_size = FRAMESIZE_UXGA; fb_max = 7; // for vga and uxga config.jpeg_quality = 8; config.fb_count = fb_max + 1; // camera init cam_err = esp_camera_init(&config); if (cam_err != ESP_OK) { Serial.printf(""Camera init failed with error 0x%x"", cam_err); major_fail(); } new_config = 2; } delay(100); sensor_t * ss = esp_camera_sensor_get(); ss->set_quality(ss, quality); ss->set_framesize(ss, (framesize_t)framesize); if (gray == 1) { ss->set_special_effect(ss, 2); // 0 regular, 2 grayscale } else { ss->set_special_effect(ss, 0); // 0 regular, 2 grayscale } for (int j = 0; j < 3; j++) { do_fb(); // start the camera ... warm it up delay(1); } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // start_avi - open the files and write in headers // static esp_err_t start_avi() { Serial.println(""Starting an avi ""); config_camera(); time(&now); localtime_r(&now, &timeinfo); strftime(strftime_buf, sizeof(strftime_buf), ""%F_%H.%M.%S"", &timeinfo); char fname[100]; if (framesize == 6) { sprintf(fname, ""/sdcard/%s_%s_vga_Q%d_I%d_L%d_S%d.avi"", devname, strftime_buf, quality, capture_interval, xlength, xspeed); } else if (framesize == 7) { sprintf(fname, ""/sdcard/%s_%s_svga_Q%d_I%d_L%d_S%d.avi"", devname, strftime_buf, quality, capture_interval, xlength, xspeed); } else if (framesize == 10) { sprintf(fname, ""/sdcard/%s_%s_uxga_Q%d_I%d_L%d_S%d.avi"", devname, strftime_buf, quality, capture_interval, xlength, xspeed); } else if (framesize == 5) { sprintf(fname, ""/sdcard/%s_%s_cif_Q%d_I%d_L%d_S%d.avi"", devname, strftime_buf, quality, capture_interval, xlength, xspeed); } else { Serial.println(""Wrong framesize""); sprintf(fname, ""/sdcard/%s_%s_xxx_Q%d_I%d_L%d_S%d.avi"", devname, strftime_buf, quality, capture_interval, xlength, xspeed); } Serial.print(""\\nFile name will be >""); Serial.print(fname); Serial.println(""<""); avifile = fopen(fname, ""w""); idxfile = fopen(""/sdcard/idx.tmp"", ""w""); if (avifile != NULL) { //Serial.printf(""File open: %s\\n"", fname); } else { Serial.println(""Could not open file""); major_fail(); } if (idxfile != NULL) { //Serial.printf(""File open: %s\\n"", ""/sdcard/idx.tmp""); } else { Serial.println(""Could not open file""); major_fail(); } for ( i = 0; i < AVIOFFSET; i++) { char ch = pgm_read_byte(&avi_header[i]); buf[i] = ch; } size_t err = fwrite(buf, 1, AVIOFFSET, avifile); if (framesize == 6) { fseek(avifile, 0x40, SEEK_SET); err = fwrite(vga_w, 1, 2, avifile); fseek(avifile, 0xA8, SEEK_SET); err = fwrite(vga_w, 1, 2, avifile); fseek(avifile, 0x44, SEEK_SET); err = fwrite(vga_h, 1, 2, avifile); fseek(avifile, 0xAC, SEEK_SET); err = fwrite(vga_h, 1, 2, avifile); } else if (framesize == 10) { fseek(avifile, 0x40, SEEK_SET); err = fwrite(uxga_w, 1, 2, avifile); fseek(avifile, 0xA8, SEEK_SET); err = fwrite(uxga_w, 1, 2, avifile); fseek(avifile, 0x44, SEEK_SET); err = fwrite(uxga_h, 1, 2, avifile); fseek(avifile, 0xAC, SEEK_SET); err = fwrite(uxga_h, 1, 2, avifile); } else if (framesize == 7) { fseek(avifile, 0x40, SEEK_SET); err = fwrite(svga_w, 1, 2, avifile); fseek(avifile, 0xA8, SEEK_SET); err = fwrite(svga_w, 1, 2, avifile); fseek(avifile, 0x44, SEEK_SET); err = fwrite(svga_h, 1, 2, avifile); fseek(avifile, 0xAC, SEEK_SET); err = fwrite(svga_h, 1, 2, avifile); } else if (framesize == 5) { fseek(avifile, 0x40, SEEK_SET); err = fwrite(cif_w, 1, 2, avifile); fseek(avifile, 0xA8, SEEK_SET); err = fwrite(cif_w, 1, 2, avifile); fseek(avifile, 0x44, SEEK_SET); err = fwrite(cif_h, 1, 2, avifile); fseek(avifile, 0xAC, SEEK_SET); err = fwrite(cif_h, 1, 2, avifile); } fseek(avifile, AVIOFFSET, SEEK_SET); Serial.print(F(""\\nRecording "")); Serial.print(total_frames); Serial.println(F("" video frames ...\\n"")); startms = millis(); bigdelta = millis(); totalp = 0; totalw = 0; overtime_count = 0; jpeg_size = 0; movi_size = 0; uVideoLen = 0; idx_offset = 4; frame_cnt = 0; frames_so_far = 0; skipping = 0; skipped = 0; newfile = 1; other_cpu_active = 1; } // end of start avi //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // another_save_avi runs on cpu 1, saves another frame to the avi file // // the ""baton"" semaphore makes sure that only one cpu is using the camera subsystem at a time // static esp_err_t another_save_avi() { xSemaphoreTake( baton, portMAX_DELAY ); if (fb_in == fb_out) { // nothing to do xSemaphoreGive( baton ); } else { fb_out = (fb_out + 1) % fb_max; int fblen; fblen = fb_q[fb_out]->len; //xSemaphoreGive( baton ); if (BlinkWithWrite) { digitalWrite(33, LOW); } jpeg_size = fblen; movi_size += jpeg_size; uVideoLen += jpeg_size; bw = millis(); size_t dc_err = fwrite(dc_buf, 1, 4, avifile); size_t ze_err = fwrite(zero_buf, 1, 4, avifile); bw = millis(); size_t err = fwrite(fb_q[fb_out]->buf, 1, fb_q[fb_out]->len, avifile); if (err == 0 ) { Serial.println(""Error on avi write""); major_fail(); } totalw = totalw + millis() - bw; //xSemaphoreTake( baton, portMAX_DELAY ); esp_camera_fb_return(fb_q[fb_out]); // release that buffer back to the camera system xSemaphoreGive( baton ); remnant = (4 - (jpeg_size & 0x00000003)) & 0x00000003; print_quartet(idx_offset, idxfile); print_quartet(jpeg_size, idxfile); idx_offset = idx_offset + jpeg_size + remnant + 8; jpeg_size = jpeg_size + remnant; movi_size = movi_size + remnant; if (remnant > 0) { size_t rem_err = fwrite(zero_buf, 1, remnant, avifile); } fileposition = ftell (avifile); // Here, we are at end of chunk (after padding) fseek(avifile, fileposition - jpeg_size - 4, SEEK_SET); // Here we are the the 4-bytes blank placeholder print_quartet(jpeg_size, avifile); // Overwrite placeholder with actual frame size (without padding) fileposition = ftell (avifile); fseek(avifile, fileposition + 6, SEEK_SET); // Here is the FOURCC ""JFIF"" (JPEG header) // Overwrite ""JFIF"" (still images) with more appropriate ""AVI1"" size_t av_err = fwrite(avi1_buf, 1, 4, avifile); fileposition = ftell (avifile); fseek(avifile, fileposition + jpeg_size - 10 , SEEK_SET); //Serial.println(""Write done""); //41 totalw = totalw + millis() - bw; //if (((fb_in + fb_max - fb_out) % fb_max) > 0 ) { // Serial.print(((fb_in + fb_max - fb_out) % fb_max)); Serial.print("" ""); //} digitalWrite(33, HIGH); } } // end of another_pic_avi //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // end_avi runs on cpu 1, empties the queue of frames, writes the index, and closes the files // static esp_err_t end_avi() { unsigned long current_end = 0; other_cpu_active = 0 ; // shuts down the picture taking program //Serial.print("" Write Q: ""); Serial.print((fb_in + fb_max - fb_out) % fb_max); Serial.print("" in/out ""); Serial.print(fb_in); Serial.print("" / ""); Serial.println(fb_out); for (int i = 0; i < fb_max; i++) { // clear the queue another_save_avi(); } //Serial.print("" Write Q: ""); Serial.print((fb_in + fb_max - fb_out) % fb_max); Serial.print("" in/out ""); Serial.print(fb_in); Serial.print("" / ""); Serial.println(fb_out); current_end = ftell (avifile); Serial.println(""End of avi - closing the files""); elapsedms = millis() - startms; float fRealFPS = (1000.0f * (float)frame_cnt) / ((float)elapsedms) * xspeed; float fmicroseconds_per_frame = 1000000.0f / fRealFPS; uint8_t iAttainedFPS = round(fRealFPS); uint32_t us_per_frame = round(fmicroseconds_per_frame); //Modify the MJPEG header from the beginning of the file, overwriting various placeholders fseek(avifile, 4 , SEEK_SET); print_quartet(movi_size + 240 + 16 * frame_cnt + 8 * frame_cnt, avifile); fseek(avifile, 0x20 , SEEK_SET); print_quartet(us_per_frame, avifile); unsigned long max_bytes_per_sec = movi_size * iAttainedFPS / frame_cnt; fseek(avifile, 0x24 , SEEK_SET); print_quartet(max_bytes_per_sec, avifile); fseek(avifile, 0x30 , SEEK_SET); print_quartet(frame_cnt, avifile); fseek(avifile, 0x8c , SEEK_SET); print_quartet(frame_cnt, avifile); fseek(avifile, 0x84 , SEEK_SET); print_quartet((int)iAttainedFPS, avifile); fseek(avifile, 0xe8 , SEEK_SET); print_quartet(movi_size + frame_cnt * 8 + 4, avifile); Serial.println(F(""\\n*** Video recorded and saved ***\\n"")); Serial.print(F(""Recorded "")); Serial.print(elapsedms / 1000); Serial.print(F(""s in "")); Serial.print(frame_cnt); Serial.print(F("" frames\\nFile size is "")); Serial.print(movi_size + 12 * frame_cnt + 4); Serial.print(F("" bytes\\nActual FPS is "")); Serial.print(fRealFPS, 2); Serial.print(F(""\\nMax data rate is "")); Serial.print(max_bytes_per_sec); Serial.print(F("" byte/s\\nFrame duration is "")); Serial.print(us_per_frame); Serial.println(F("" us"")); Serial.print(F(""Average frame length is "")); Serial.print(uVideoLen / frame_cnt); Serial.println(F("" bytes"")); Serial.print(""Average picture time (ms) ""); Serial.println( totalp / frame_cnt ); Serial.print(""Average write time (ms) ""); Serial.println( totalw / frame_cnt ); Serial.print(""Frames Skipped % ""); Serial.println( 100.0 * skipped / total_frames, 1 ); Serial.println(""Writing the index""); fseek(avifile, current_end, SEEK_SET); fclose(idxfile); size_t i1_err = fwrite(idx1_buf, 1, 4, avifile); print_quartet(frame_cnt * 16, avifile); idxfile = fopen(""/sdcard/idx.tmp"", ""r""); if (idxfile != NULL) { //Serial.printf(""File open: %s\\n"", ""/sdcard/idx.tmp""); } else { Serial.println(""Could not open file""); //major_fail(); } char * AteBytes; AteBytes = (char*) malloc (8); for (int i = 0; i < frame_cnt; i++) { size_t res = fread ( AteBytes, 1, 8, idxfile); size_t i1_err = fwrite(dc_buf, 1, 4, avifile); size_t i2_err = fwrite(zero_buf, 1, 4, avifile); size_t i3_err = fwrite(AteBytes, 1, 8, avifile); } free(AteBytes); fclose(idxfile); fclose(avifile); int xx = remove(""/sdcard/idx.tmp""); Serial.println(""---""); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // do_fb - just takes a picture and discards it // static esp_err_t do_fb() { xSemaphoreTake( baton, portMAX_DELAY ); camera_fb_t * fb = esp_camera_fb_get(); Serial.print(""Pic, len=""); Serial.println(fb->len); esp_camera_fb_return(fb); xSemaphoreGive( baton ); } //////////////////////////////////////////////////////////////////////////////////// // // some globals for the loop() // long wakeup; long last_wakeup = 0; void loop() { wakeup = millis(); if (wakeup - last_wakeup > (14 * 60 * 1000) ) { // 14 minutes last_wakeup = millis(); // do_time(); } ftpSrv.handleFTP(); //delay(1); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // static esp_err_t capture_handler(httpd_req_t *req) { camera_fb_t * fb = NULL; esp_err_t res = ESP_OK; char fname[100]; //xSemaphoreTake( baton, portMAX_DELAY ); fb = esp_camera_fb_get(); if (!fb) { Serial.println(""Camera capture failed""); httpd_resp_send_500(req); xSemaphoreGive( baton ); return ESP_FAIL; } file_number++; sprintf(fname, ""inline; filename=capture_%d.jpg"", file_number); httpd_resp_set_type(req, ""image/jpeg""); httpd_resp_set_hdr(req, ""Content-Disposition"", fname); size_t out_len, out_width, out_height; size_t fb_len = 0; fb_len = fb->len; res = httpd_resp_send(req, (const char *)fb->buf, fb->len); esp_camera_fb_return(fb); //xSemaphoreGive( baton ); return res; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // static esp_err_t stop_handler(httpd_req_t *req) { esp_err_t res = ESP_OK; recording = 0; Serial.println(""stopping recording""); do_stop(""Stopping previous recording""); httpd_resp_send(req, the_page, strlen(the_page)); return ESP_OK; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // static esp_err_t start_handler(httpd_req_t *req) { esp_err_t res = ESP_OK; char buf[80]; size_t buf_len; char new_res[20]; if (recording == 1) { const char* resp = ""You must Stop recording, before starting a new one. Start over ...""; httpd_resp_send(req, resp, strlen(resp)); return ESP_OK; return res; } else { //recording = 1; Serial.println(""starting recording""); sensor_t * s = esp_camera_sensor_get(); int new_interval = capture_interval; int new_length = capture_interval * total_frames; int new_framesize = s->status.framesize; int new_quality = s->status.quality; int new_repeat = 0; int new_xspeed = 1; int new_xlength = 3; int new_gray = 0; /* Serial.println(""""); Serial.println(""Current Parameters :""); Serial.print("" Capture Interval = ""); Serial.print(capture_interval); Serial.println("" ms""); Serial.print("" Length = ""); Serial.print(capture_interval * total_frames / 1000); Serial.println("" s""); Serial.print("" Quality = ""); Serial.println(new_quality); Serial.print("" Framesize = ""); Serial.println(new_framesize); Serial.print("" Repeat = ""); Serial.println(repeat); Serial.print("" Speed = ""); Serial.println(xspeed); */ buf_len = httpd_req_get_url_query_len(req) + 1; if (buf_len > 1) { if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { ESP_LOGI(TAG, ""Found URL query => %s"", buf); char param[32]; /* Get value of expected key from query string */ //Serial.println("" ... parameters""); if (httpd_query_key_value(buf, ""length"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); if (x >= 5 && x <= 3600 * 24 ) { // 5 sec to 24 hours new_length = x; } ESP_LOGI(TAG, ""Found URL query parameter => length=%s"", param); } if (httpd_query_key_value(buf, ""repeat"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); if (x >= 0 ) { new_repeat = x; } ESP_LOGI(TAG, ""Found URL query parameter => repeat=%s"", param); } if (httpd_query_key_value(buf, ""framesize"", new_res, sizeof(new_res)) == ESP_OK) { if (strcmp(new_res, ""UXGA"") == 0) { new_framesize = 10; } else if (strcmp(new_res, ""SVGA"") == 0) { new_framesize = 7; } else if (strcmp(new_res, ""VGA"") == 0) { new_framesize = 6; } else if (strcmp(new_res, ""CIF"") == 0) { new_framesize = 5; } else { Serial.println(""Only UXGA, SVGA, VGA, and CIF are valid!""); } ESP_LOGI(TAG, ""Found URL query parameter => framesize=%s"", new_res); } if (httpd_query_key_value(buf, ""quality"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); if (x >= 10 && x <= 50) { // MINIMUM QUALITY 10 to save memory new_quality = x; } ESP_LOGI(TAG, ""Found URL query parameter => quality=%s"", param); } if (httpd_query_key_value(buf, ""speed"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); if (x >= 1 && x <= 100) { new_xspeed = x; } ESP_LOGI(TAG, ""Found URL query parameter => speed=%s"", param); } if (httpd_query_key_value(buf, ""gray"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); if (x == 1 ) { new_gray = x; } ESP_LOGI(TAG, ""Found URL query parameter => gray=%s"", param); } if (httpd_query_key_value(buf, ""interval"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); if (x >= 1 && x <= 180000) { // 180,000 ms = 3 min new_interval = x; } ESP_LOGI(TAG, ""Found URL query parameter => interval=%s"", param); } } } framesize = new_framesize; capture_interval = new_interval; xlength = new_length; total_frames = new_length * 1000 / capture_interval; repeat = new_repeat; quality = new_quality; xspeed = new_xspeed; gray = new_gray; do_start(""Starting a new AVI""); httpd_resp_send(req, the_page, strlen(the_page)); recording = 1; return ESP_OK; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // void do_start(char *the_message) { Serial.print(""do_start ""); Serial.println(the_message); const char msg[] PROGMEM = R""rawliteral( %s ESP32-CAM Video Recorder

%s
ESP32-CAM Video Recorder %s


Message is %s


Recording = %d (1 is active)
Capture Interval = %d ms
Length = %d seconds
Quality = %d (10 best to 50 worst)
Framesize = %d (10 UXGA, 7 SVGA, 6 VGA, 5 CIF)
Repeat = %d
Speed = %d
Gray = %d



)rawliteral""; sprintf(the_page, msg, devname, devname, vernum, the_message, recording, capture_interval, capture_interval * total_frames / 1000, quality, framesize, repeat, xspeed, gray); //Serial.println(strlen(msg)); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // void do_stop(char *the_message) { Serial.print(""do_stop ""); Serial.println(the_message); const char msg[] PROGMEM = R""rawliteral( %s ESP32-CAM Video Recorder

%s
ESP32-CAM Video Recorder %s


Message is %s


http://%s/

http://%s/start?framesize=VGA&length=1800&interval=100&quality=10&repeat=100&speed=1&gray=0

VGA 2 fps, for 30 minutes repeat, 30x playback

UXGA 1 sec per frame, for 30 minutes repeat, 30x playback

UXGA 2 fps for 30 minutes repeat, 15x playback

CIF 20 fps second for 30 minutes repeat


)rawliteral""; sprintf(the_page, msg, devname, devname, vernum, the_message, localip, localip, localip, localip, localip, localip, localip, localip); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // void do_status(char *the_message) { Serial.print(""do_status ""); Serial.println(the_message); const char msg[] PROGMEM = R""rawliteral( %s ESP32-CAM Video Recorder

%s
ESP32-CAM Video Recorder %s
%s


Message is %s


Total SD Space is %d MB, Used SD Space is %d MB
Recording = %d (1 is active)
Frame %d of %d, Skipped %d

Capture Interval = %d ms
Length = %d seconds
Quality = %d (10 best to 50 worst)
Framesize = %d (10 UXGA, 7 SVGA, 6 VGA, 5 CIF)
Repeat = %d
Playback Speed = %d
Gray = %d

Commands as follows for your ESP's ip address:

http://%s/

http://%s/stop ... and restart
You must be stopped before restart or PIR

ftp://%s/

Username: esp, Password: esp ... to download the files

Red LED on back of ESP will flash with every frame (or skipped frames), and flash SOS if camera or sd card not working.

Check camera position with the frame below
Refresh page for more.


)rawliteral""; time(&now); const char *strdate = ctime(&now); //Serial.printf(""Total space: %lluMB\\n"", SD_MMC.totalBytes() / (1024 * 1024)); //Serial.printf(""Used space: %lluMB\\n"", SD_MMC.usedBytes() / (1024 * 1024)); int tot = SD_MMC.totalBytes() / (1024 * 1024); int use = SD_MMC.usedBytes() / (1024 * 1024); //Serial.print(strlen(msg)); Serial.print("" ""); sprintf(the_page, msg, devname, devname, vernum, strdate, the_message, tot, use, recording, frames_so_far, total_frames, skipped, capture_interval, capture_interval * total_frames / 1000, quality, framesize, repeat, xspeed, gray, localip, localip, localip, localip, localip, localip); //Serial.println(strlen(the_page)); } static esp_err_t time_handler(httpd_req_t *req) { char buf[80]; size_t buf_len = httpd_req_get_url_query_len(req) + 1; if (buf_len > 1) { if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { ESP_LOGI(TAG, ""Found URL query => %s"", buf); char param[32]; /* Get value of expected key from query string */ //Serial.println("" ... parameters""); int year = 0; int mon = 0; int day = 0; int hour = 0; int min = 0; int sec = 0; bool err = 0; if (httpd_query_key_value(buf, ""year"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 1900 && x <= 2100 ) { year = x; err = 0; Serial.println(year); }else{ err = 1; } } if (httpd_query_key_value(buf, ""mon"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 1 && x <= 12 ) { mon = x; err = 0; Serial.println(mon); }else{ err = 1; } } if (httpd_query_key_value(buf, ""day"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 1 && x <= 31 ) { day = x; err = 0; Serial.println(day); }else{ err = 1; } } if (httpd_query_key_value(buf, ""hour"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 0 && x <= 24 ) { hour = x; err = 0; Serial.println(hour); }else{ err = 1; } } if (httpd_query_key_value(buf, ""min"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 0 && x <= 60 ) { min = x; err = 0; Serial.println(min); }else{ err = 1; } } if (httpd_query_key_value(buf, ""sec"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 0 && x <= 60 ) { sec = x; err = 0; Serial.println(sec); }else{ err = 1; } } if (err != 1) { struct tm tmGet; tmGet.tm_year = year - 1900; tmGet.tm_mon = mon; tmGet.tm_mday = day; tmGet.tm_hour = hour; tmGet.tm_min = min; tmGet.tm_sec = sec; time_t t = mktime(&tmGet); printf(""Setting time: %s"", asctime(&tmGet)); timeval tmSet = { .tv_sec = t }; settimeofday(&tmSet, NULL); timeSet = 1;//时间设置完了 } } } const char msg[] PROGMEM = R""rawliteral(Time:%s )rawliteral""; struct tm timeinfo; getLocalTime(&timeinfo); sprintf(the_page, msg, asctime(&timeinfo) ); httpd_resp_send(req, the_page, strlen(the_page)); return ESP_OK; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // static esp_err_t index_handler(httpd_req_t *req) { do_status(""Refresh Status""); httpd_resp_send(req, the_page, strlen(the_page)); return ESP_OK; } void startCameraServer() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); httpd_uri_t index_uri = { .uri = ""/"", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL }; httpd_uri_t capture_uri = { .uri = ""/capture"", .method = HTTP_GET, .handler = capture_handler, .user_ctx = NULL }; httpd_uri_t file_stop = { .uri = ""/stop"", .method = HTTP_GET, .handler = stop_handler, .user_ctx = NULL }; httpd_uri_t file_start = { .uri = ""/start"", .method = HTTP_GET, .handler = start_handler, .user_ctx = NULL }; httpd_uri_t time_set = { .uri = ""/time"", .method = HTTP_GET, .handler = time_handler, .user_ctx = NULL }; if (httpd_start(&camera_httpd, &config) == ESP_OK) { httpd_register_uri_handler(camera_httpd, &index_uri); httpd_register_uri_handler(camera_httpd, &capture_uri); httpd_register_uri_handler(camera_httpd, &file_start); httpd_register_uri_handler(camera_httpd, &file_stop); httpd_register_uri_handler(camera_httpd, &time_set); } Serial.println(""Camera http started""); } ",16339,True,2680.156873784162,median "const String FirmwareVersion = ""018400""; #define HardwareVersion ""NCS314 for HW 3.x"" //Format _X.XXX_ //NIXIE CLOCK SHIELD NCS314 v 2.x by GRA & AFCH (fominalec@gmail.com) //1.84 08.04.2018 //LEDs functions moved to external file //LEDs freezing while music (or sound) played. //SPI Setup moved driver's file //1.83 02.08.2018 (Driver v 1.1 is required) //Fixed: Temp. reading speed fixed //Fixed: Dots mixed up (driver was updated to v. 1.1) //Fixed: RGB LEDs reading from EEPROM //Fixed: Check for entering data from GPS in range //1.82 18.07.2018 Dual Date Format //1.81 18.02.2018 Temp. sensor present analyze //1.80 06.08.2017 //Added: Date and Time GPS synchronization //1.70 30.07.2017 //Added IR remote control support (Sony RM-X151) (""MODE"", ""UP"", ""DOWN"") //1.60 24_07_2017 //Added: Temperature reading mode in menu and slot machine transaction //1.0.31 27_04_2017 //Added: antipoisoning effect - slot machine //1.021 31.01.2017 //Added: time synchronizing each 10 seconds //Fixed: not correct time reading from RTC while start up //1.02 17.10.2016 //Fixed: RGB color controls //Update to Arduino IDE 1.6.12 (Time.h replaced to TimeLib.h) //1.01 //Added RGB LEDs lock(by UP and Down Buttons) //Added Down and Up buttons pause and resume self testing //25.09.2016 update to HW ver 1.1 //25.05.2016 //#define tubes8 #define tubes6 //#define tubes4 #include #include #include #include #include #include #include ""doIndication314_HW3.x.h"" #include //IR remote control /////////// START ///////////////////////////// #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #include int RECV_PIN = 4; IRrecv irrecv(RECV_PIN); decode_results IRresults; // buttons codes for remote controller Sony RM-X151 #define IR_BUTTON_UP_CODE 0x6621 #define IR_BUTTON_DOWN_CODE 0x2621 #define IR_BUTTON_MODE_CODE 0x7121 class IRButtonState { public: int PAUSE_BETWEEN_PACKETS = 50; int PACKETS_QTY_IN_LONG_PRESS = 18; private: bool Flag = 0; byte CNT_packets = 0; unsigned long lastPacketTime = 0; bool START_TIMER = false; int _buttonCode; public: IRButtonState::IRButtonState(int buttonCode) { _buttonCode = buttonCode; } public: int IRButtonState::checkButtonState(int receivedCode) { if (((millis() - lastPacketTime) > PAUSE_BETWEEN_PACKETS) && (START_TIMER == true)) { START_TIMER = false; if (CNT_packets >= 2) { Flag = 0; CNT_packets = 0; START_TIMER = false; return 1; } else { Flag = 0; CNT_packets = 0; return 0; } } else { if (receivedCode == _buttonCode) { Flag = 1;} else { if (!(Flag == 1)) {return 0;} else { if (!(receivedCode == 0xFFFFFFFF)) {return 0;} } } CNT_packets++; lastPacketTime = millis(); START_TIMER = true; if (CNT_packets >= PACKETS_QTY_IN_LONG_PRESS) { Flag = 0; CNT_packets = 0; START_TIMER = false; return -1; } else {return 0;} } } }; IRButtonState IRModeButton(IR_BUTTON_MODE_CODE); IRButtonState IRUpButton(IR_BUTTON_UP_CODE); IRButtonState IRDownButton(IR_BUTTON_DOWN_CODE); #endif int ModeButtonState = 0; int UpButtonState = 0; int DownButtonState = 0; //IR remote control /////////// START ///////////////////////////// #define GPS_BUFFER_LENGTH 83 char GPS_Package[GPS_BUFFER_LENGTH]; byte GPS_position=0; struct GPS_DATE_TIME { byte GPS_hours; byte GPS_minutes; byte GPS_seconds; byte GPS_day; byte GPS_mounth; int GPS_year; bool GPS_Valid_Data=false; unsigned long GPS_Data_Parsed_time; }; GPS_DATE_TIME GPS_Date_Time; boolean UD, LD; // DOTS control; byte data[12]; byte addr[8]; int celsius, fahrenheit; /*#define RedLedPin 9 //MCU WDM output for red LEDs 9-g #define GreenLedPin 6 //MCU WDM output for green LEDs 6-b #define BlueLedPin 3 //MCU WDM output for blue LEDs 3-r*/ #define pinSet A0 #define pinUp A2 #define pinDown A1 //#define pinBuzzer 2 const byte pinBuzzer = 2; // pomenyal #define pinUpperDots 12 //HIGH value light a dots #define pinLowerDots 8 //HIGH value light a dots #define pinTemp 7 #define pinSHDN 5 bool RTC_present; #define US_DateFormat 1 #define EU_DateFormat 0 //bool DateFormat=EU_DateFormat; OneWire ds(pinTemp); bool TempPresent = false; #define CELSIUS 0 #define FAHRENHEIT 1 String stringToDisplay = ""000000""; // Conten of this string will be displayed on tubes (must be 6 chars length) int menuPosition = 0; // 0 - time // 1 - date // 2 - alarm // 3 - 12/24 hours mode // 4 - Temperature byte blinkMask = B00000000; //bit mask for blinkin digits (1 - blink, 0 - constant light) int blankMask = B00000000; //bit mask for digits (1 - off, 0 - on) byte dotPattern = B00000000; //bit mask for separeting dots (1 - on, 0 - off) //B10000000 - upper dots //B01000000 - lower dots #define DS1307_ADDRESS 0x68 byte zero = 0x00; //workaround for issue #527 int RTC_hours, RTC_minutes, RTC_seconds, RTC_day, RTC_month, RTC_year, RTC_day_of_week; #define TimeIndex 0 #define DateIndex 1 #define AlarmIndex 2 #define hModeIndex 3 #define TemperatureIndex 4 #define TimeZoneIndex 5 #define TimeHoursIndex 6 #define TimeMintuesIndex 7 #define TimeSecondsIndex 8 #define DateFormatIndex 9 #define DateDayIndex 10 #define DateMonthIndex 11 #define DateYearIndex 12 #define AlarmHourIndex 13 #define AlarmMinuteIndex 14 #define AlarmSecondIndex 15 #define Alarm01 16 #define hModeValueIndex 17 #define DegreesFormatIndex 18 #define HoursOffsetIndex 19 #define FirstParent TimeIndex #define LastParent TimeZoneIndex #define SettingsCount (HoursOffsetIndex+1) #define NoParent 0 #define NoChild 0 //-------------------------------0--------1--------2-------3--------4--------5--------6--------7--------8--------9----------10-------11---------12---------13-------14-------15---------16---------17--------18----------19 // names: Time, Date, Alarm, 12/24, Temperature,TimeZone,hours, mintues, seconds, DateFormat, day, month, year, hour, minute, second alarm01 hour_format Deg.FormIndex HoursOffset // 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 int parent[SettingsCount] = {NoParent, NoParent, NoParent, NoParent,NoParent,NoParent,1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 5, 6}; int firstChild[SettingsCount] = {6, 9, 13, 17, 18, 19, 0, 0, 0, NoChild, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int lastChild[SettingsCount] = { 8, 12, 16, 17, 18, 19, 0, 0, 0, NoChild, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int value[SettingsCount] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, EU_DateFormat, 0, 0, 0, 0, 0, 0, 0, 24, 0, 2}; int maxValue[SettingsCount] = { 0, 0, 0, 0, 0, 0, 23, 59, 59, US_DateFormat, 31, 12, 99, 23, 59, 59, 1, 24, FAHRENHEIT, 14}; int minValue[SettingsCount] = { 0, 0, 0, 12, 0, 0, 00, 00, 00, EU_DateFormat, 1, 1, 00, 00, 00, 00, 0, 12, CELSIUS, -12}; int blinkPattern[SettingsCount] = { B00000000, //0 B00000000, //1 B00000000, //2 B00000000, //3 B00000000, //4 B00000000, //5 B00000011, //6 B00001100, //7 B00110000, //8 B00111111, //9 B00000011, //10 B00001100, //11 B00110000, //12 B00000011, //13 B00001100, //14 B00110000, //15 B11000000, //16 B00001100, //17 B00111111, //18 B00000011, //19 }; bool editMode = false; long downTime = 0; long upTime = 0; const long settingDelay = 150; bool BlinkUp = false; bool BlinkDown = false; unsigned long enteringEditModeTime = 0; bool RGBLedsOn = true; #define RGBLEDsEEPROMAddress 0 #define HourFormatEEPROMAddress 1 #define AlarmTimeEEPROMAddress 2 //3,4,5 #define AlarmArmedEEPROMAddress 6 #define LEDsLockEEPROMAddress 7 #define LEDsRedValueEEPROMAddress 8 #define LEDsGreenValueEEPROMAddress 9 #define LEDsBlueValueEEPROMAddress 10 #define DegreesFormatEEPROMAddress 11 #define HoursOffsetEEPROMAddress 12 #define DateFormatEEPROMAddress 13 //buttons pins declarations ClickButton setButton(pinSet, LOW, CLICKBTN_PULLUP); ClickButton upButton(pinUp, LOW, CLICKBTN_PULLUP); ClickButton downButton(pinDown, LOW, CLICKBTN_PULLUP); /////////////////// Tone tone1; #define isdigit(n) (n >= '0' && n <= '9') //char *song = ""MissionImp:d=16,o=6,b=95:32d,32d#,32d,32d#,32d,32d#,32d,32d#,32d,32d,32d#,32e,32f,32f#,32g,g,8p,g,8p,a#,p,c7,p,g,8p,g,8p,f,p,f#,p,g,8p,g,8p,a#,p,c7,p,g,8p,g,8p,f,p,f#,p,a#,g,2d,32p,a#,g,2c#,32p,a#,g,2c,a#5,8c,2p,32p,a#5,g5,2f#,32p,a#5,g5,2f,32p,a#5,g5,2e,d#,8d""; char *song = ""PinkPanther:d=4,o=5,b=160:8d#,8e,2p,8f#,8g,2p,8d#,8e,16p,8f#,8g,16p,8c6,8b,16p,8d#,8e,16p,8b,2a#,2p,16a,16g,16e,16d,2e""; //char *song=""VanessaMae:d=4,o=6,b=70:32c7,32b,16c7,32g,32p,32g,32p,32d#,32p,32d#,32p,32c,32p,32c,32p,32c7,32b,16c7,32g#,32p,32g#,32p,32f,32p,16f,32c,32p,32c,32p,32c7,32b,16c7,32g,32p,32g,32p,32d#,32p,32d#,32p,32c,32p,32c,32p,32g,32f,32d#,32d,32c,32d,32d#,32c,32d#,32f,16g,8p,16d7,32c7,32d7,32a#,32d7,32a,32d7,32g,32d7,32d7,32p,32d7,32p,32d7,32p,16d7,32c7,32d7,32a#,32d7,32a,32d7,32g,32d7,32d7,32p,32d7,32p,32d7,32p,32g,32f,32d#,32d,32c,32d,32d#,32c,32d#,32f,16c""; //char *song=""DasBoot:d=4,o=5,b=100:d#.4,8d4,8c4,8d4,8d#4,8g4,a#.4,8a4,8g4,8a4,8a#4,8d,2f.,p,f.4,8e4,8d4,8e4,8f4,8a4,c.,8b4,8a4,8b4,8c,8e,2g.,2p""; //char *song=""Scatman:d=4,o=5,b=200:8b,16b,32p,8b,16b,32p,8b,2d6,16p,16c#.6,16p.,8d6,16p,16c#6,8b,16p,8f#,2p.,16c#6,8p,16d.6,16p.,16c#6,16b,8p,8f#,2p,32p,2d6,16p,16c#6,8p,16d.6,16p.,16c#6,16a.,16p.,8e,2p.,16c#6,8p,16d.6,16p.,16c#6,16b,8p,8b,16b,32p,8b,16b,32p,8b,2d6,16p,16c#.6,16p.,8d6,16p,16c#6,8b,16p,8f#,2p.,16c#6,8p,16d.6,16p.,16c#6,16b,8p,8f#,2p,32p,2d6,16p,16c#6,8p,16d.6,16p.,16c#6,16a.,16p.,8e,2p.,16c#6,8p,16d.6,16p.,16c#6,16a,8p,8e,2p,32p,16f#.6,16p.,16b.,16p.""; //char *song=""Popcorn:d=4,o=5,b=160:8c6,8a#,8c6,8g,8d#,8g,c,8c6,8a#,8c6,8g,8d#,8g,c,8c6,8d6,8d#6,16c6,8d#6,16c6,8d#6,8d6,16a#,8d6,16a#,8d6,8c6,8a#,8g,8a#,c6""; //char *song=""WeWishYou:d=4,o=5,b=200:d,g,8g,8a,8g,8f#,e,e,e,a,8a,8b,8a,8g,f#,d,d,b,8b,8c6,8b,8a,g,e,d,e,a,f#,2g,d,g,8g,8a,8g,8f#,e,e,e,a,8a,8b,8a,8g,f#,d,d,b,8b,8c6,8b,8a,g,e,d,e,a,f#,1g,d,g,g,g,2f#,f#,g,f#,e,2d,a,b,8a,8a,8g,8g,d6,d,d,e,a,f#,2g""; #define OCTAVE_OFFSET 0 char *p; int notes[] = { 0, NOTE_C4, NOTE_CS4, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_GS4, NOTE_A4, NOTE_AS4, NOTE_B4, NOTE_C5, NOTE_CS5, NOTE_D5, NOTE_DS5, NOTE_E5, NOTE_F5, NOTE_FS5, NOTE_G5, NOTE_GS5, NOTE_A5, NOTE_AS5, NOTE_B5, NOTE_C6, NOTE_CS6, NOTE_D6, NOTE_DS6, NOTE_E6, NOTE_F6, NOTE_FS6, NOTE_G6, NOTE_GS6, NOTE_A6, NOTE_AS6, NOTE_B6, NOTE_C7, NOTE_CS7, NOTE_D7, NOTE_DS7, NOTE_E7, NOTE_F7, NOTE_FS7, NOTE_G7, NOTE_GS7, NOTE_A7, NOTE_AS7, NOTE_B7 }; int fireforks[] = {0, 0, 1, //1 -1, 0, 0, //2 0, 1, 0, //3 0, 0, -1, //4 1, 0, 0, //5 0, -1, 0 }; //array with RGB rules (0 - do nothing, -1 - decrese, +1 - increse void setRTCDateTime(byte h, byte m, byte s, byte d, byte mon, byte y, byte w = 1); int functionDownButton = 0; int functionUpButton = 0; bool LEDsLock = false; //antipoisoning transaction bool modeChangedByUser = false; bool transactionInProgress = false; //antipoisoning transaction #define timeModePeriod 60000 #define dateModePeriod 5000 long modesChangePeriod = timeModePeriod; //end of antipoisoning transaction bool GPS_sync_flag=false; extern const int LEDsDelay; /******************************************************************************************************* Init Programm *******************************************************************************************************/ void setup() { Wire.begin(); //setRTCDateTime(23,40,00,25,7,15,1); Serial.begin(115200); #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) Serial1.begin(9600); #endif if (EEPROM.read(HourFormatEEPROMAddress) != 12) value[hModeValueIndex] = 24; else value[hModeValueIndex] = 12; if (EEPROM.read(RGBLEDsEEPROMAddress) != 0) RGBLedsOn = true; else RGBLedsOn = false; if (EEPROM.read(AlarmTimeEEPROMAddress) == 255) value[AlarmHourIndex] = 0; else value[AlarmHourIndex] = EEPROM.read(AlarmTimeEEPROMAddress); if (EEPROM.read(AlarmTimeEEPROMAddress + 1) == 255) value[AlarmMinuteIndex] = 0; else value[AlarmMinuteIndex] = EEPROM.read(AlarmTimeEEPROMAddress + 1); if (EEPROM.read(AlarmTimeEEPROMAddress + 2) == 255) value[AlarmSecondIndex] = 0; else value[AlarmSecondIndex] = EEPROM.read(AlarmTimeEEPROMAddress + 2); if (EEPROM.read(AlarmArmedEEPROMAddress) == 255) value[Alarm01] = 0; else value[Alarm01] = EEPROM.read(AlarmArmedEEPROMAddress); if (EEPROM.read(LEDsLockEEPROMAddress) == 255) LEDsLock = false; else LEDsLock = EEPROM.read(LEDsLockEEPROMAddress); if (EEPROM.read(DegreesFormatEEPROMAddress) == 255) value[DegreesFormatIndex] = CELSIUS; else value[DegreesFormatIndex] = EEPROM.read(DegreesFormatEEPROMAddress); if (EEPROM.read(HoursOffsetEEPROMAddress) == 255) value[HoursOffsetIndex] = value[HoursOffsetIndex]; else value[HoursOffsetIndex] = EEPROM.read(HoursOffsetEEPROMAddress) + minValue[HoursOffsetIndex]; if (EEPROM.read(DateFormatEEPROMAddress) == 255) value[DateFormatIndex] = value[DateFormatIndex]; else value[DateFormatIndex] = EEPROM.read(DateFormatEEPROMAddress); //Serial.print(F(""led lock="")); //Serial.println(LEDsLock); /* pinMode(RedLedPin, OUTPUT); pinMode(GreenLedPin, OUTPUT); pinMode(BlueLedPin, OUTPUT);*/ tone1.begin(pinBuzzer); song = parseSong(song); pinMode(LEpin, OUTPUT); pinMode(pinSHDN, OUTPUT); digitalWrite(pinSHDN, HIGH); //HIGH = ON // SPI setup SPISetup(); LEDsSetup(); //buttons pins inits pinMode(pinSet, INPUT_PULLUP); pinMode(pinUp, INPUT_PULLUP); pinMode(pinDown, INPUT_PULLUP); //////////////////////////// pinMode(pinBuzzer, OUTPUT); //buttons objects inits setButton.debounceTime = 20; // Debounce timer in ms setButton.multiclickTime = 30; // Time limit for multi clicks setButton.longClickTime = 2000; // time until ""held-down clicks"" register upButton.debounceTime = 20; // Debounce timer in ms upButton.multiclickTime = 30; // Time limit for multi clicks upButton.longClickTime = 2000; // time until ""held-down clicks"" register downButton.debounceTime = 20; // Debounce timer in ms downButton.multiclickTime = 30; // Time limit for multi clicks downButton.longClickTime = 2000; // time until ""held-down clicks"" register //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! doTest(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (LEDsLock == 1) { setLEDsFromEEPROM(); } getRTCTime(); byte prevSeconds = RTC_seconds; unsigned long RTC_ReadingStartTime = millis(); RTC_present = true; while (prevSeconds == RTC_seconds) { getRTCTime(); //Serial.println(RTC_seconds); if ((millis() - RTC_ReadingStartTime) > 3000) { Serial.println(F(""Warning! RTC DON'T RESPOND!"")); RTC_present = false; break; } } setTime(RTC_hours, RTC_minutes, RTC_seconds, RTC_day, RTC_month, RTC_year); #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) irrecv.blink13(false); irrecv.enableIRIn(); // Start the receiver #endif } int rotator = 0; //index in array with RGB ""rules"" (increse by one on each 255 cycles) int cycle = 0; //cycles counter int RedLight = 255; int GreenLight = 0; int BlueLight = 0; unsigned long prevTime = 0; // time of lase tube was lit unsigned long prevTime4FireWorks = 0; //time of last RGB changed //int minuteL=0; //младшая цифра минут /*************************************************************************************************************** MAIN Programm ***************************************************************************************************************/ void loop() { if (((millis() % 10000) == 0) && (RTC_present)) //synchronize with RTC every 10 seconds { getRTCTime(); setTime(RTC_hours, RTC_minutes, RTC_seconds, RTC_day, RTC_month, RTC_year); //Serial.println(F(""Sync"")); } #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) GetDataFromSerial1(); if ((millis() % 10001) == 0) //synchronize with GPS every 10 seconds { SyncWithGPS(); Serial.println(F(""Sync from GPS"")); } IRresults.value = 0; if (irrecv.decode(&IRresults)) { Serial.println(IRresults.value, HEX); irrecv.resume(); // Receive the next value } ModeButtonState = IRModeButton.checkButtonState(IRresults.value); if (ModeButtonState == 1) Serial.println(F(""Mode short"")); if (ModeButtonState == -1) Serial.println(F(""Mode long...."")); UpButtonState = IRUpButton.checkButtonState(IRresults.value); if (UpButtonState == 1) Serial.println(F(""Up short"")); if (UpButtonState == -1) Serial.println(F(""Up long...."")); DownButtonState = IRDownButton.checkButtonState(IRresults.value); if (DownButtonState == 1) Serial.println(F(""Down short"")); if (DownButtonState == -1) Serial.println(F(""Down long...."")); #else ModeButtonState=0; UpButtonState=0; DownButtonState=0; #endif p = playmusic(p); if ((millis() - prevTime4FireWorks) > LEDsDelay) { rotateFireWorks(); //change color (by 1 step) prevTime4FireWorks = millis(); } if ((menuPosition == TimeIndex) || (modeChangedByUser == false) ) modesChanger(); doIndication(); setButton.Update(); upButton.Update(); downButton.Update(); if (editMode == false) { blinkMask = B00000000; } else if ((millis() - enteringEditModeTime) > 60000) { editMode = false; menuPosition = firstChild[menuPosition]; blinkMask = blinkPattern[menuPosition]; } if ((setButton.clicks > 0) || (ModeButtonState == 1)) //short click { modeChangedByUser = true; p = 0; //shut off music ))) tone1.play(1000, 100); enteringEditModeTime = millis(); /*if (value[DateFormatIndex] == US_DateFormat) { //if (menuPosition == ) } else */ menuPosition = menuPosition + 1; #if defined (__AVR_ATmega328P__) if (menuPosition == TimeZoneIndex) menuPosition++;// skip TimeZone for Arduino Uno #endif if (menuPosition == LastParent + 1) menuPosition = TimeIndex; /*Serial.print(F(""menuPosition="")); Serial.println(menuPosition); Serial.print(F(""value="")); Serial.println(value[menuPosition]);*/ blinkMask = blinkPattern[menuPosition]; if ((parent[menuPosition - 1] != 0) and (lastChild[parent[menuPosition - 1] - 1] == (menuPosition - 1))) //exit from edit mode { if ((parent[menuPosition - 1] - 1 == 1) && (!isValidDate())) { menuPosition = DateDayIndex; return; } editMode = false; menuPosition = parent[menuPosition - 1] - 1; if (menuPosition == TimeIndex) setTime(value[TimeHoursIndex], value[TimeMintuesIndex], value[TimeSecondsIndex], day(), month(), year()); if (menuPosition == DateIndex) { Serial.print(F(""Day:"")); Serial.println(value[DateDayIndex]); Serial.print(F(""Month:"")); Serial.println(value[DateMonthIndex]); setTime(hour(), minute(), second(), value[DateDayIndex], value[DateMonthIndex], 2000 + value[DateYearIndex]); EEPROM.write(DateFormatEEPROMAddress, value[DateFormatIndex]); } if (menuPosition == AlarmIndex) { EEPROM.write(AlarmTimeEEPROMAddress, value[AlarmHourIndex]); EEPROM.write(AlarmTimeEEPROMAddress + 1, value[AlarmMinuteIndex]); EEPROM.write(AlarmTimeEEPROMAddress + 2, value[AlarmSecondIndex]); EEPROM.write(AlarmArmedEEPROMAddress, value[Alarm01]); }; if (menuPosition == hModeIndex) EEPROM.write(HourFormatEEPROMAddress, value[hModeValueIndex]); if (menuPosition == TemperatureIndex) { EEPROM.write(DegreesFormatEEPROMAddress, value[DegreesFormatIndex]); } if (menuPosition == TimeZoneIndex) EEPROM.write(HoursOffsetEEPROMAddress, value[HoursOffsetIndex] - minValue[HoursOffsetIndex]); //if (menuPosition == hModeIndex) EEPROM.write(HourFormatEEPROMAddress, value[hModeValueIndex]); setRTCDateTime(hour(), minute(), second(), day(), month(), year() % 1000, 1); return; } //end exit from edit mode /*Serial.print(""menu pos=""); Serial.println(menuPosition); Serial.print(""DateFormat""); Serial.println(value[DateFormatIndex]);*/ if ((menuPosition != HoursOffsetIndex) && (menuPosition != DateFormatIndex) && (menuPosition != DateDayIndex)) value[menuPosition] = extractDigits(blinkMask); } if ((setButton.clicks < 0) || (ModeButtonState == -1)) //long click { tone1.play(1000, 100); if (!editMode) { enteringEditModeTime = millis(); if (menuPosition == TimeIndex) stringToDisplay = PreZero(hour()) + PreZero(minute()) + PreZero(second()); //temporary enabled 24 hour format while settings } if (menuPosition == DateIndex) { // Serial.println(""DateEdit""); value[DateDayIndex] = day(); value[DateMonthIndex] = month(); value[DateYearIndex] = year() % 1000; if (value[DateFormatIndex] == EU_DateFormat) stringToDisplay=PreZero(value[DateDayIndex])+PreZero(value[DateMonthIndex])+PreZero(value[DateYearIndex]); else stringToDisplay=PreZero(value[DateMonthIndex])+PreZero(value[DateDayIndex])+PreZero(value[DateYearIndex]); //Serial.print(""str=""); // Serial.println(stringToDisplay); } menuPosition = firstChild[menuPosition]; if (menuPosition == AlarmHourIndex) { value[Alarm01] = 1; /*digitalWrite(pinUpperDots, HIGH);*/dotPattern = B10000000; } editMode = !editMode; blinkMask = blinkPattern[menuPosition]; if ((menuPosition != DegreesFormatIndex) && (menuPosition != HoursOffsetIndex) && (menuPosition != DateFormatIndex)) value[menuPosition] = extractDigits(blinkMask); /*Serial.print(F(""menuPosition="")); Serial.println(menuPosition); Serial.print(F(""value="")); Serial.println(value[menuPosition]); */ } if (upButton.clicks != 0) functionUpButton = upButton.clicks; if ((upButton.clicks > 0) || (UpButtonState == 1)) { modeChangedByUser = true; p = 0; //shut off music ))) tone1.play(1000, 100); incrementValue(); if (!editMode) { LEDsLock = false; EEPROM.write(LEDsLockEEPROMAddress, 0); } } if (functionUpButton == -1 && upButton.depressed == true) { BlinkUp = false; if (editMode == true) { if ( (millis() - upTime) > settingDelay) { upTime = millis();// + settingDelay; incrementValue(); } } } else BlinkUp = true; if (downButton.clicks != 0) functionDownButton = downButton.clicks; if ((downButton.clicks > 0) || (DownButtonState == 1)) { modeChangedByUser = true; p = 0; //shut off music ))) tone1.play(1000, 100); dicrementValue(); if (!editMode) { LEDsLock = true; EEPROM.write(LEDsLockEEPROMAddress, 1); EEPROM.write(LEDsRedValueEEPROMAddress, RedLight); EEPROM.write(LEDsGreenValueEEPROMAddress, GreenLight); EEPROM.write(LEDsBlueValueEEPROMAddress, BlueLight); /*Serial.println(F(""Store to EEPROM:"")); Serial.print(F(""RED="")); Serial.println(RedLight); Serial.print(F(""GREEN="")); Serial.println(GreenLight); Serial.print(F(""Blue="")); Serial.println(BlueLight);*/ } } if (functionDownButton == -1 && downButton.depressed == true) { BlinkDown = false; if (editMode == true) { if ( (millis() - downTime) > settingDelay) { downTime = millis();// + settingDelay; dicrementValue(); } } } else BlinkDown = true; if (!editMode) { if ((upButton.clicks < 0) || (UpButtonState == -1)) { tone1.play(1000, 100); RGBLedsOn = true; EEPROM.write(RGBLEDsEEPROMAddress, 1); Serial.println(F(""RGB=on"")); setLEDsFromEEPROM(); } if ((downButton.clicks < 0) || (DownButtonState == -1)) { tone1.play(1000, 100); RGBLedsOn = false; EEPROM.write(RGBLEDsEEPROMAddress, 0); Serial.println(F(""RGB=off"")); } } static bool updateDateTime = false; switch (menuPosition) { case TimeIndex: //time mode if (!transactionInProgress) stringToDisplay = updateDisplayString(); //Below is the edited code to turn off the tubes //this is untested if(Hour()>=11 || Hour()<=7){ //turn off tubes stringToDisplay="" ""; /* if that doesn't work, maybe try the SPI code below SPI.end();*/ }else { //start communication again /* SPI.begin(); // SPI.setDataMode (SPI_MODE3); // Mode 3 SPI SPI.setClockDivider(SPI_CLOCK_DIV128); // SCK = 16MHz/128= 125kHz */ } //end of edit doDotBlink(); checkAlarmTime(); blankMask = B00000000; break; case DateIndex: //date mode if (!transactionInProgress) stringToDisplay = updateDateString(); dotPattern = B01000000; //turn on lower dots checkAlarmTime(); blankMask = B00000000; break; case AlarmIndex: //alarm mode stringToDisplay = PreZero(value[AlarmHourIndex]) + PreZero(value[AlarmMinuteIndex]) + PreZero(value[AlarmSecondIndex]); blankMask = B00000000; if (value[Alarm01] == 1) /*digitalWrite(pinUpperDots, HIGH);*/ dotPattern = B10000000; //turn on upper dots else { /*digitalWrite(pinUpperDots, LOW); digitalWrite(pinLowerDots, LOW);*/ dotPattern = B00000000; //turn off upper dots } checkAlarmTime(); break; case hModeIndex: //12/24 hours mode stringToDisplay = ""00"" + String(value[hModeValueIndex]) + ""00""; blankMask = B00110011; dotPattern = B00000000; //turn off all dots checkAlarmTime(); break; case TemperatureIndex: //missed break case DegreesFormatIndex: if (!transactionInProgress) { stringToDisplay = updateTemperatureString(getTemperature(value[DegreesFormatIndex])); if (value[DegreesFormatIndex] == CELSIUS) { blankMask = B00110001; dotPattern = B01000000; } else { blankMask = B00100011; dotPattern = B00000000; } } if (getTemperature(value[DegreesFormatIndex]) < 0) dotPattern |= B10000000; else dotPattern &= B01111111; break; case TimeZoneIndex: case HoursOffsetIndex: stringToDisplay = String(PreZero(value[HoursOffsetIndex])) + ""0000""; blankMask = B00001111; if (value[HoursOffsetIndex]>=0) dotPattern = B00000000; //turn off all dots else dotPattern = B10000000; //turn on upper dots break; case DateFormatIndex: if (value[DateFormatIndex] == EU_DateFormat) { stringToDisplay=""311299""; blinkPattern[DateDayIndex]=B00000011; blinkPattern[DateMonthIndex]=B00001100; } else { stringToDisplay=""123199""; blinkPattern[DateDayIndex]=B00001100; blinkPattern[DateMonthIndex]=B00000011; } break; case DateDayIndex: case DateMonthIndex: case DateYearIndex: if (value[DateFormatIndex] == EU_DateFormat) stringToDisplay=PreZero(value[DateDayIndex])+PreZero(value[DateMonthIndex])+PreZero(value[DateYearIndex]); else stringToDisplay=PreZero(value[DateMonthIndex])+PreZero(value[DateDayIndex])+PreZero(value[DateYearIndex]); break; } // IRresults.value=0; } String PreZero(int digit) { digit=abs(digit); if (digit < 10) return String(""0"") + String(digit); else return String(digit); } String updateDisplayString() { static unsigned long lastTimeStringWasUpdated; if ((millis() - lastTimeStringWasUpdated) > 1000) { lastTimeStringWasUpdated = millis(); return getTimeNow(); } return stringToDisplay; } String getTimeNow() { if (value[hModeValueIndex] == 24) return PreZero(hour()) + PreZero(minute()) + PreZero(second()); else return PreZero(hourFormat12()) + PreZero(minute()) + PreZero(second()); } void doTest() { Serial.print(F(""Firmware version: "")); Serial.println(FirmwareVersion.substring(1,2)+"".""+FirmwareVersion.substring(2,5)); Serial.println(HardwareVersion); Serial.println(F(""Start Test"")); p=song; parseSong(p); //p=0; //need to be deleted LEDsTest(); #ifdef tubes8 String testStringArray[11]={""00000000"",""11111111"",""22222222"",""33333333"",""44444444"",""55555555"",""66666666"",""77777777"",""88888888"",""99999999"",""""}; testStringArray[10]=FirmwareVersion+""00""; #endif #ifdef tubes6 String testStringArray[11]={""000000"",""111111"",""222222"",""333333"",""444444"",""555555"",""666666"",""777777"",""888888"",""999999"",""""}; testStringArray[10]=FirmwareVersion; #endif int dlay=500; bool test=1; byte strIndex=-1; unsigned long startOfTest=millis()+1000; //disable delaying in first iteration bool digitsLock=false; while (test) { if (digitalRead(pinDown)==0) digitsLock=true; if (digitalRead(pinUp)==0) digitsLock=false; if ((millis()-startOfTest)>dlay) { startOfTest=millis(); if (!digitsLock) strIndex=strIndex+1; if (strIndex==10) dlay=2000; if (strIndex>10) { test=false; strIndex=10;} stringToDisplay=testStringArray[strIndex]; Serial.println(stringToDisplay); doIndication(); } delayMicroseconds(2000); }; if ( !ds.search(addr)) { Serial.println(F(""Temp. sensor not found."")); } else TempPresent=true; Serial.println(F(""Stop Test"")); // while(1); } void doDotBlink() { static unsigned long lastTimeBlink = millis(); static bool dotState = 0; if ((millis() - lastTimeBlink) > 1000) { lastTimeBlink = millis(); dotState = !dotState; if (dotState) { dotPattern = B11000000; /*digitalWrite(pinUpperDots, HIGH); digitalWrite(pinLowerDots, HIGH);*/ } else { dotPattern = B00000000; /*digitalWrite(pinUpperDots, LOW); digitalWrite(pinLowerDots, LOW);*/ } } } void setRTCDateTime(byte h, byte m, byte s, byte d, byte mon, byte y, byte w) { Wire.beginTransmission(DS1307_ADDRESS); Wire.write(zero); //stop Oscillator Wire.write(decToBcd(s)); Wire.write(decToBcd(m)); Wire.write(decToBcd(h)); Wire.write(decToBcd(w)); Wire.write(decToBcd(d)); Wire.write(decToBcd(mon)); Wire.write(decToBcd(y)); Wire.write(zero); //start Wire.endTransmission(); } byte decToBcd(byte val) { // Convert normal decimal numbers to binary coded decimal return ( (val / 10 * 16) + (val % 10) ); } byte bcdToDec(byte val) { // Convert binary coded decimal to normal decimal numbers return ( (val / 16 * 10) + (val % 16) ); } void getRTCTime() { Wire.beginTransmission(DS1307_ADDRESS); Wire.write(zero); Wire.endTransmission(); Wire.requestFrom(DS1307_ADDRESS, 7); RTC_seconds = bcdToDec(Wire.read()); RTC_minutes = bcdToDec(Wire.read()); RTC_hours = bcdToDec(Wire.read() & 0b111111); //24 hour time RTC_day_of_week = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday RTC_day = bcdToDec(Wire.read()); RTC_month = bcdToDec(Wire.read()); RTC_year = bcdToDec(Wire.read()); } int extractDigits(byte b) { String tmp = ""1""; if (b == B00000011) { tmp = stringToDisplay.substring(0, 2); } if (b == B00001100) { tmp = stringToDisplay.substring(2, 4); } if (b == B00110000) { tmp = stringToDisplay.substring(4); } return tmp.toInt(); } void injectDigits(byte b, int value) { if (b == B00000011) stringToDisplay = PreZero(value) + stringToDisplay.substring(2); if (b == B00001100) stringToDisplay = stringToDisplay.substring(0, 2) + PreZero(value) + stringToDisplay.substring(4); if (b == B00110000) stringToDisplay = stringToDisplay.substring(0, 4) + PreZero(value); } bool isValidDate() { int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (value[DateYearIndex] % 4 == 0) days[1] = 29; if (value[DateDayIndex] > days[value[DateMonthIndex] - 1]) return false; else return true; } byte default_dur = 4; byte default_oct = 6; int bpm = 63; int num; long wholenote; long duration; byte note; byte scale; char* parseSong(char *p) { // Absolutely no error checking in here // format: d=N,o=N,b=NNN: // find the start (skip name, etc) while (*p != ':') p++; // ignore name p++; // skip ':' // get default duration if (*p == 'd') { p++; p++; // skip ""d="" num = 0; while (isdigit(*p)) { num = (num * 10) + (*p++ - '0'); } if (num > 0) default_dur = num; p++; // skip comma } // get default octave if (*p == 'o') { p++; p++; // skip ""o="" num = *p++ - '0'; if (num >= 3 && num <= 7) default_oct = num; p++; // skip comma } // get BPM if (*p == 'b') { p++; p++; // skip ""b="" num = 0; while (isdigit(*p)) { num = (num * 10) + (*p++ - '0'); } bpm = num; p++; // skip colon } // BPM usually expresses the number of quarter notes per minute wholenote = (60 * 1000L / bpm) * 4; // this is the time for whole note (in milliseconds) return p; } // now begin note loop static unsigned long lastTimeNotePlaying = 0; char* playmusic(char *p) { if (*p == 0) { return p; } if (millis() - lastTimeNotePlaying > duration) lastTimeNotePlaying = millis(); else return p; // first, get note duration, if available num = 0; while (isdigit(*p)) { num = (num * 10) + (*p++ - '0'); } if (num) duration = wholenote / num; else duration = wholenote / default_dur; // we will need to check if we are a dotted note after // now get the note note = 0; switch (*p) { case 'c': note = 1; break; case 'd': note = 3; break; case 'e': note = 5; break; case 'f': note = 6; break; case 'g': note = 8; break; case 'a': note = 10; break; case 'b': note = 12; break; case 'p': default: note = 0; } p++; // now, get optional '#' sharp if (*p == '#') { note++; p++; } // now, get optional '.' dotted note if (*p == '.') { duration += duration / 2; p++; } // now, get scale if (isdigit(*p)) { scale = *p - '0'; p++; } else { scale = default_oct; } scale += OCTAVE_OFFSET; if (*p == ',') p++; // skip comma for next note (or we may be at the end) // now play the note if (note) { tone1.play(notes[(scale - 4) * 12 + note], duration); if (millis() - lastTimeNotePlaying > duration) lastTimeNotePlaying = millis(); else return p; tone1.stop(); } else { return p; } Serial.println(F(""Incorrect Song Format!"")); return 0; //error } void incrementValue() { enteringEditModeTime = millis(); if (editMode == true) { if (menuPosition != hModeValueIndex) // 12/24 hour mode menu position value[menuPosition] = value[menuPosition] + 1; else value[menuPosition] = value[menuPosition] + 12; if (value[menuPosition] > maxValue[menuPosition]) value[menuPosition] = minValue[menuPosition]; if (menuPosition == Alarm01) { if (value[menuPosition] == 1) /*digitalWrite(pinUpperDots, HIGH);*/dotPattern = B10000000; //turn on upper dots /*else digitalWrite(pinUpperDots, LOW); */ dotPattern = B00000000; //turn off all dots } if (menuPosition!=DateFormatIndex) injectDigits(blinkMask, value[menuPosition]); /*Serial.print(""value=""); Serial.println(value[menuPosition]);*/ } } void dicrementValue() { enteringEditModeTime = millis(); if (editMode == true) { if (menuPosition != hModeValueIndex) value[menuPosition] = value[menuPosition] - 1; else value[menuPosition] = value[menuPosition] - 12; if (value[menuPosition] < minValue[menuPosition]) value[menuPosition] = maxValue[menuPosition]; if (menuPosition == Alarm01) { if (value[menuPosition] == 1) /*digitalWrite(pinUpperDots, HIGH);*/ dotPattern = B10000000; //turn on upper dots else /*digitalWrite(pinUpperDots, LOW);*/ dotPattern = B00000000; //turn off all dots } if (menuPosition!=DateFormatIndex) injectDigits(blinkMask, value[menuPosition]); /*Serial.print(""value=""); Serial.println(value[menuPosition]);*/ } } bool Alarm1SecondBlock = false; unsigned long lastTimeAlarmTriggired = 0; void checkAlarmTime() { if (value[Alarm01] == 0) return; if ((Alarm1SecondBlock == true) && ((millis() - lastTimeAlarmTriggired) > 1000)) Alarm1SecondBlock = false; if (Alarm1SecondBlock == true) return; if ((hour() == value[AlarmHourIndex]) && (minute() == value[AlarmMinuteIndex]) && (second() == value[AlarmSecondIndex])) { lastTimeAlarmTriggired = millis(); Alarm1SecondBlock = true; Serial.println(F(""Wake up, Neo!"")); p = song; } } void modesChanger() { if (editMode == true) return; static unsigned long lastTimeModeChanged = millis(); static unsigned long lastTimeAntiPoisoningIterate = millis(); static int transnumber = 0; if ((millis() - lastTimeModeChanged) > modesChangePeriod) { lastTimeModeChanged = millis(); if (transnumber == 0) { menuPosition = DateIndex; modesChangePeriod = dateModePeriod; } if (transnumber == 1) { menuPosition = TemperatureIndex; modesChangePeriod = dateModePeriod; if (!TempPresent) transnumber = 2; } if (transnumber == 2) { menuPosition = TimeIndex; modesChangePeriod = timeModePeriod; } transnumber++; if (transnumber > 2) transnumber = 0; if (modeChangedByUser == true) { menuPosition = TimeIndex; } modeChangedByUser = false; } if ((millis() - lastTimeModeChanged) < 2000) { if ((millis() - lastTimeAntiPoisoningIterate) > 100) { lastTimeAntiPoisoningIterate = millis(); if (TempPresent) { if (menuPosition == TimeIndex) stringToDisplay = antiPoisoning2(updateTemperatureString(getTemperature(value[DegreesFormatIndex])), getTimeNow()); if (menuPosition == DateIndex) stringToDisplay = antiPoisoning2(getTimeNow(), PreZero(day()) + PreZero(month()) + PreZero(year() % 1000) ); if (menuPosition == TemperatureIndex) stringToDisplay = antiPoisoning2(PreZero(day()) + PreZero(month()) + PreZero(year() % 1000), updateTemperatureString(getTemperature(value[DegreesFormatIndex]))); } else { if (menuPosition == TimeIndex) stringToDisplay = antiPoisoning2(PreZero(day()) + PreZero(month()) + PreZero(year() % 1000), getTimeNow()); if (menuPosition == DateIndex) stringToDisplay = antiPoisoning2(getTimeNow(), PreZero(day()) + PreZero(month()) + PreZero(year() % 1000) ); } // Serial.println(""StrTDInToModeChng=""+stringToDisplay); } } else { transactionInProgress = false; } } String antiPoisoning2(String fromStr, String toStr) { //static bool transactionInProgress=false; //byte fromDigits[6]; static byte toDigits[6]; static byte currentDigits[6]; static byte iterationCounter = 0; if (!transactionInProgress) { transactionInProgress = true; blankMask = B00000000; for (int i = 0; i < 6; i++) { currentDigits[i] = fromStr.substring(i, i + 1).toInt(); toDigits[i] = toStr.substring(i, i + 1).toInt(); } } for (int i = 0; i < 6; i++) { if (iterationCounter < 10) currentDigits[i]++; else if (currentDigits[i] != toDigits[i]) currentDigits[i]++; if (currentDigits[i] == 10) currentDigits[i] = 0; } iterationCounter++; if (iterationCounter == 20) { iterationCounter = 0; transactionInProgress = false; } String tmpStr; for (int i = 0; i < 6; i++) tmpStr += currentDigits[i]; return tmpStr; } String updateDateString() { static unsigned long lastTimeDateUpdate = millis()+1001; static String DateString = PreZero(day()) + PreZero(month()) + PreZero(year() % 1000); static byte prevoiusDateFormatWas=value[DateFormatIndex]; if (((millis() - lastTimeDateUpdate) > 1000) || (prevoiusDateFormatWas != value[DateFormatIndex])) { lastTimeDateUpdate = millis(); if (value[DateFormatIndex]==EU_DateFormat) DateString = PreZero(day()) + PreZero(month()) + PreZero(year() % 1000); else DateString = PreZero(month()) + PreZero(day()) + PreZero(year() % 1000); } return DateString; } float getTemperature (boolean bTempFormat) { byte TempRawData[2]; ds.reset(); ds.write(0xCC); //skip ROM command ds.write(0x44); //send make convert to all devices ds.reset(); ds.write(0xCC); //skip ROM command ds.write(0xBE); //send request to all devices TempRawData[0] = ds.read(); TempRawData[1] = ds.read(); int16_t raw = (TempRawData[1] << 8) | TempRawData[0]; if (raw == -1) raw = 0; float celsius = (float)raw / 16.0; float fDegrees; if (!bTempFormat) fDegrees = celsius * 10; else fDegrees = (celsius * 1.8 + 32.0) * 10; //Serial.println(fDegrees); return fDegrees; } #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) void SyncWithGPS() { static unsigned long Last_Time_GPS_Sync=0; static bool GPS_Sync_Flag=0; //byte HoursOffset=2; if (GPS_Sync_Flag == 0) { if ((millis()-GPS_Date_Time.GPS_Data_Parsed_time)>3000) {Serial.println(""Parsed data to old""); return;} Serial.println(F(""Updating time..."")); Serial.println(GPS_Date_Time.GPS_hours); Serial.println(GPS_Date_Time.GPS_minutes); Serial.println(GPS_Date_Time.GPS_seconds); setTime(GPS_Date_Time.GPS_hours, GPS_Date_Time.GPS_minutes, GPS_Date_Time.GPS_seconds, GPS_Date_Time.GPS_day, GPS_Date_Time.GPS_mounth, GPS_Date_Time.GPS_year % 1000); adjustTime(value[HoursOffsetIndex] * 3600); setRTCDateTime(hour(), minute(), second(), day(), month(), year() % 1000, 1); GPS_Sync_Flag = 1; Last_Time_GPS_Sync=millis(); } else { if (((millis())-Last_Time_GPS_Sync) > 1800000) GPS_Sync_Flag=0; else GPS_Sync_Flag=1; } } void GetDataFromSerial1() { if (Serial1.available()) { // If anything comes in Serial1 (pins 0 & 1) byte GPS_incoming_byte; GPS_incoming_byte=Serial1.read(); //Serial.write(GPS_incoming_byte); GPS_Package[GPS_position]=GPS_incoming_byte; GPS_position++; if (GPS_position == GPS_BUFFER_LENGTH-1) { GPS_position=0; // Serial.println(""more then BUFFER_LENGTH!!!!""); } if (GPS_incoming_byte == 0x0A) { GPS_Package[GPS_position]=0; GPS_position=0; if (ControlCheckSum()) {/*Serial.println(""Call parse"");*/ GPS_Parse_DateTime();} } } } bool GPS_Parse_DateTime() { bool GPSsignal=false; if (!((GPS_Package[0] == '$') &&(GPS_Package[3] == 'R') &&(GPS_Package[4] == 'M') &&(GPS_Package[5] == 'C'))) {return false;} else { // Serial.println(""RMC!!!""); } //Serial.print(""hh: ""); int hh=(GPS_Package[7]-48)*10+GPS_Package[8]-48; //Serial.println(hh); int mm=(GPS_Package[9]-48)*10+GPS_Package[10]-48; //Serial.print(""mm: ""); //Serial.println(mm); int ss=(GPS_Package[11]-48)*10+GPS_Package[12]-48; //Serial.print(""ss: ""); //Serial.println(ss); byte GPSDatePos=0; int CommasCounter=0; for (int i = 12; i < GPS_BUFFER_LENGTH ; i++) { if (GPS_Package[i] == ',') { CommasCounter++; if (CommasCounter==8) { GPSDatePos=i+1; break; } } } //Serial.print(""dd: ""); int dd=(GPS_Package[GPSDatePos]-48)*10+GPS_Package[GPSDatePos+1]-48; //Serial.println(dd); int MM=(GPS_Package[GPSDatePos+2]-48)*10+GPS_Package[GPSDatePos+3]-48; //Serial.print(""MM: ""); //Serial.println(MM); int yyyy=2000+(GPS_Package[GPSDatePos+4]-48)*10+GPS_Package[GPSDatePos+5]-48; //Serial.print(""yyyy: ""); //Serial.println(yyyy); //if ((hh<0) || (mm<0) || (ss<0) || (dd<0) || (MM<0) || (yyyy<0)) return false; if ( !inRange( yyyy, 2018, 2038 ) || !inRange( MM, 1, 12 ) || !inRange( dd, 1, 31 ) || !inRange( hh, 0, 23 ) || !inRange( mm, 0, 59 ) || !inRange( ss, 0, 59 ) ) return false; else { GPS_Date_Time.GPS_hours=hh; GPS_Date_Time.GPS_minutes=mm; GPS_Date_Time.GPS_seconds=ss; GPS_Date_Time.GPS_day=dd; GPS_Date_Time.GPS_mounth=MM; GPS_Date_Time.GPS_year=yyyy; GPS_Date_Time.GPS_Data_Parsed_time=millis(); //Serial.println(""Precision TIME HAS BEEN ACCURED!!!!!!!!!""); //GPS_Package[0]=0x0A; return 1; } } uint8_t ControlCheckSum() { uint8_t CheckSum = 0, MessageCheckSum = 0; // check sum uint16_t i = 1; // 1 sybol left from '$' while (GPS_Package[i]!='*') { CheckSum^=GPS_Package[i]; if (++i == GPS_BUFFER_LENGTH) {Serial.println(""End of the line""); return 0;} // end of line not found } if (GPS_Package[++i]>0x40) MessageCheckSum=(GPS_Package[i]-0x37)<<4; // ASCII codes to DEC convertation else MessageCheckSum=(GPS_Package[i]-0x30)<<4; if (GPS_Package[++i]>0x40) MessageCheckSum+=(GPS_Package[i]-0x37); else MessageCheckSum+=(GPS_Package[i]-0x30); if (MessageCheckSum != CheckSum) {Serial.println(""wrong checksum""); return 0;} // wrong checksum //Serial.println(""Checksum is ok""); return 1; // all ok! } #endif /*String updateTemperatureString(float fDegrees) { int iDegrees = round(fDegrees); String strTemp; strTemp = ""0"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 1000) strTemp = ""00"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 100) strTemp = ""000"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 10) strTemp = ""0000"" + String(abs(iDegrees)) + ""0""; return strTemp; }*/ String updateTemperatureString(float fDegrees) { static unsigned long lastTimeTemperatureString=millis()+1100; static String strTemp =""000000""; /*int delayTempUpdate; if (displayNow) delayTempUpdate=0; else delayTempUpdate = 1000;*/ if ((millis() - lastTimeTemperatureString) > 1000) { //Serial.println(""F(Updating temp. str.)""); lastTimeTemperatureString = millis(); int iDegrees = round(fDegrees); if (value[DegreesFormatIndex] == CELSIUS) { strTemp = ""0"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 1000) strTemp = ""00"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 100) strTemp = ""000"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 10) strTemp = ""0000"" + String(abs(iDegrees)) + ""0""; }else { strTemp = ""0"" + String(abs(iDegrees)) + ""0""; if (abs(iDegrees) < 1000) strTemp = ""00"" + String(abs(iDegrees)/10) + ""00""; if (abs(iDegrees) < 100) strTemp = ""000"" + String(abs(iDegrees)/10) + ""00""; if (abs(iDegrees) < 10) strTemp = ""0000"" + String(abs(iDegrees)/10) + ""00""; } #ifdef tubes8 strTemp= """"+strTemp+""00""; #endif return strTemp; } return strTemp; } boolean inRange( int no, int low, int high ) { if ( no < low || no > high ) { Serial.println(F(""Not in range"")); Serial.println(String(no) + "":"" + String (low) + ""-"" + String(high)); return false; } return true; } ",16139,True,2519.9263402395086,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2010 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package spark.components.gridClasses { import flash.geom.Rectangle; import mx.collections.ICollectionView; import mx.collections.IList; import mx.core.mx_internal; import mx.events.CollectionEvent; import mx.events.CollectionEventKind; import spark.components.Grid; import spark.components.gridClasses.CellPosition; use namespace mx_internal; [ExcludeClass] /** * Use the GridSelection class to track a Grid control's * selectionMode property and its set of selected rows, columns, or cells. * The selected elements are defined by integer indices. * * @see spark.components.Grid * @see spark.components.Grid#columns * @see spark.components.Grid#dataProvider * @see spark.components.gridClasses.GridSelectionMode * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class GridSelection { include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private * List of ordered selected/de-selected cell regions used to represent * either row or cell selections depending on the selection mode. * (For row selection, a row region will be in column 0 and column count * will be 1.) * * This is the list of cell regions that have * been added (isAdd==true) and removed (isAdd==false). * * Internally, regionsContainCell should be used to determine if a cell/row * is in the selection. */ private var cellRegions:Vector. = new Vector.(); /** * @private * If preserveSelection, and selectionMode is ""singleRow"" or ""singleCell"", * cache the dataItem that goes with the selection so we can find the * index of the selection after a collection refresh event. */ private var selectedItem:Object; /** * @private * True if in a collection handler. If this is the case, there is no * need to validate the index/indices. In the case of * CollectionEventKind.REMOVE, when the last item selected and it is * removed from the collection, the validate would fail since the index is * now out of range and the item would incorrectly remain in the selection. */ private var inCollectionHandler:Boolean; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function GridSelection() { super(); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // grid //---------------------------------- private var _grid:Grid; /** * The grid control associated with this object. * This property should only be set once. * *

For the Spark DataGrid, this value is initialized by * the DataGrid.partAdded() method.

* * @default null * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get grid():Grid { return _grid; } /** * @private */ public function set grid(value:Grid):void { _grid = value; } //---------------------------------- // preserveSelection //---------------------------------- private var _preserveSelection:Boolean = true; /** * If true, and selectionMode is * GridSelectionMode.SINGLE_ROW or * GridSelectionMode.SINGLE_CELL, then selection is * preserved when the dataProvider refreshes its collection, * and the selected item is contained in the collection after * the refresh. * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get preserveSelection():Boolean { return _preserveSelection; } /** * @private */ public function set preserveSelection(value:Boolean):void { if (_preserveSelection == value) return; _preserveSelection = value; selectedItem = null; // If preserving the selection and there is currently a selection, // save the corresponding data item. if (_preserveSelection && (selectionMode == GridSelectionMode.SINGLE_ROW || selectionMode == GridSelectionMode.SINGLE_CELL) && selectionLength > 0) { if (selectionMode == GridSelectionMode.SINGLE_ROW) selectedItem = grid.dataProvider.getItemAt(allRows()[0]); else // SINGLE_CELL selectedItem = grid.dataProvider.getItemAt(allCells()[0].rowIndex); } } //---------------------------------- // requireSelection //---------------------------------- private var _requireSelection:Boolean = false; /** * If true, a data item must always be selected in the * control as long as there is at least one item in * dataProvider and one column in columns. * * @default false * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get requireSelection():Boolean { return _requireSelection; } /** * @private */ public function set requireSelection(value:Boolean):void { if (_requireSelection == value) return; _requireSelection = value; if (_requireSelection) ensureRequiredSelection(); } //---------------------------------- // selectionLength //---------------------------------- /** * @private * Cache the selectionLength. Only recalculate if selectionLength is -1. */ private var _selectionLength:int = 0; /** * The length of the selection. * *

If the selectionMode is either * GridSelectionMode.SINGLE_ROW or * GridSelectionMode.MULTIPLE_ROWS, contains the number of * selected rows. If a selected row has no columns whose * visible property is set to true it is still * included in the number of selected rows.

* *

If the selectionMode is either * GridSelectionMode.SINGLE_CELL or * GridSelectionMode.MULTIPLE_CELLS, contains the number of * selected cells. * If a selected cell is in a column which has its visible * property set to false after it is selected, the cell is included in * the number of selected cells.

* *

If the selectionMode is GridSelectionMode.NONE, * contains 0.

* * @default 0 * * @return Number of selected rows or cells. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectionLength():int { // Note: this assumes there are no duplicate cells in cellRegions - ie // 2 adds of the same cell without an intermediate delete. const isRows:Boolean = isRowSelectionMode(); if (_selectionLength < 0) { _selectionLength = 0; const cellRegionsLength:int = cellRegions.length; for (var i:int = 0; i < cellRegionsLength; i++) { var cr:CellRect = cellRegions[i]; const numSelected:int = isRows ? cr.height : cr.height * cr.width; if (cr.isAdd) _selectionLength += numSelected; else _selectionLength -= numSelected; } } return _selectionLength; } //---------------------------------- // selectionMode //---------------------------------- private var _selectionMode:String = GridSelectionMode.SINGLE_ROW; /** * The selection mode of the control. Possible values are: * GridSelectionMode.MULTIPLE_CELLS, * GridSelectionMode.MULTIPLE_ROWS, * GridSelectionMode.NONE, * GridSelectionMode.SINGLE_CELL, and * GridSelectionMode.SINGLE_ROW. * *

Changing the selectionMode causes the * current selection to be cleared.

* * @default GridSelectionMode.SINGLE_ROW * * @see spark.components.gridClasses.GridSelectionMode * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectionMode():String { return _selectionMode; } /** * @private */ public function set selectionMode(value:String):void { if (value == _selectionMode) return; switch (value) { case GridSelectionMode.SINGLE_ROW: case GridSelectionMode.MULTIPLE_ROWS: case GridSelectionMode.SINGLE_CELL: case GridSelectionMode.MULTIPLE_CELLS: case GridSelectionMode.NONE: _selectionMode = value; removeAll(); break; } } /** * If the selectionMode is either GridSelectionMode.SINGLE_CELL or * GridSelectionMode.MULTIPLE_CELLS, returns a list of all the * selected cells. * * @return Vector of selected cell locations as row and column indices or, * if none are selected, a Vector of length 0. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function allCells():Vector. { var cells:Vector. = new Vector.; if (!isCellSelectionMode()) return cells; // Iterate over the selected cells region. const bounds:Rectangle = getCellRegionsBounds(); const left:int = bounds.left; const right:int = bounds.right; const bottom:int = bounds.bottom; for (var rowIndex:int = bounds.top; rowIndex < bottom; rowIndex++) { for (var columnIndex:int = left; columnIndex < right; columnIndex++) { if (regionsContainCell(rowIndex, columnIndex)) cells.push(new CellPosition(rowIndex, columnIndex)); } } return cells; } /** * If the selectionMode is either GridSelectionMode.SINGLE_ROW or * GridSelectionMode.MULTIPLE_ROWS, returns a list of all the * selected rows. * * @return Vector of selected rows as row indices or, if none, a Vector * of length 0. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function allRows():Vector. { if (!isRowSelectionMode()) return new Vector.(0, true); var rows:Vector. = new Vector.(); const bounds:Rectangle = getCellRegionsBounds(); const bottom:int = bounds.bottom; for (var rowIndex:int = bounds.top; rowIndex < bottom; rowIndex++) { // row is represented as cell in column 0 of the row if (regionsContainCell(rowIndex, 0)) rows.push(rowIndex); } return rows; } /** * If the selectionMode is GridSelectionMode.MULTIPLE_ROWS * selects all the rows in the grid and if selectionMode is * GridSelectionMode.MULTIPLE_CELLS, selects all the cells in * columns with visible set to true. * * @return true if the selection changed. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function selectAll():Boolean { const maxRows:int = getGridDataProviderLength(); if (selectionMode == GridSelectionMode.MULTIPLE_ROWS) { return setRows(0, maxRows); } else if (selectionMode == GridSelectionMode.MULTIPLE_CELLS) { const maxColumns:int = getGridColumnsLength(); return setCellRegion(0, 0, maxRows, maxColumns); } return false; } /** * Remove the current selection. * If requireSelection is true, * and the selectionMode is row-based, then row 0 * is selected. * If the selectionMode is cell-based, * then cell 0,0 is selected. * * @return true if the list of selected items has changed from the last call. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeAll():Boolean { var selectionChanged:Boolean = selectionLength > 0; removeSelection(); selectionChanged = ensureRequiredSelection() || selectionChanged; return selectionChanged; } //---------------------------------- // Rows //---------------------------------- /** * If the selectionMode is either GridSelectionMode.SINGLE_ROW or * GridSelectionMode.MULTIPLE_ROWS, determines if the row is in * the current selection. * * @param rowIndex The 0-based row index. * * @return true if the row is in the selection * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function containsRow(rowIndex:int):Boolean { if (!validateIndex(rowIndex)) return false; return regionsContainCell(rowIndex, 0); } /** * If the selectionMode is GridSelectionMode.MULTIPLE_ROWS, * determines if the rows are in the current selection. * * @param rowIndex The 0-based row index. * * @return true if the rows are in the selection * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function containsRows(rowsIndices:Vector.):Boolean { if (!validateIndices(rowsIndices)) return false; for each (var rowIndex:int in rowsIndices) { if (!regionsContainCell(rowIndex, 0)) return false; } return true; } /** * If the selectionMode is either GridSelectionMode.SINGLE_ROW * or GridSelectionMode.MULTIPLE_ROWS, replaces the current * selection with the specified row. * * @param rowIndex The 0-based row index. * * @return true if no errors, or false if the * rowIndex is not a valid index in the control's dataProvider, * or if the selectionMode is not valid. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setRow(rowIndex:int):Boolean { if (!validateIndex(rowIndex)) return false; internalSetCellRegion(rowIndex); return true; } /** * If the selectionMode is GridSelectionMode.MULTIPLE_ROWS, * adds the row to the selection. * * @param rowIndex The 0-based row index. * * @return true if no errors, or false if the * rowIndex is not a valid index in the * control's dataProvider, or the selectionMode is not valid. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addRow(rowIndex:int):Boolean { if (!validateIndex(rowIndex)) return false; if (selectionMode != GridSelectionMode.MULTIPLE_ROWS) return false; internalAddCell(rowIndex); return true; } /** * If the selectionMode is either GridSelectionMode.SINGLE_ROW * or GridSelectionMode.MULTIPLE_ROWS, removes the row from * the selection. * * @param rowIndex The 0-based row index. * * @return true if no errors. * Returns false if the * rowIndex is not a valid index in the * control's dataProvider, * or if the selectionMode is not valid. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeRow(rowIndex:int):Boolean { if (!validateIndex(rowIndex) ) return false; if (requireSelection && containsRow(rowIndex) && selectionLength == 1) return false; internalRemoveCell(rowIndex); return true; } /** * If the selectionMode is GridSelectionMode.MULTIPLE_ROWS, * replaces the current selection with the rows starting at * startRowIndex and ending with endRowIndex. * * @param rowIndex 0-based row index of the first row in the selection. * @param rowCount Number of rows in the selection. * * @return true if no errors. * Returns false if any of the indices are invalid, * if startRowIndex is not less than or equal to endRowIndex, * or if the selectionMode is not valid. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setRows(rowIndex:int, rowCount:int):Boolean { if (!validateRowRegion(rowIndex, rowCount)) return false; internalSetCellRegion(rowIndex, 0, rowCount, 1); return true; } //---------------------------------- // Cells //---------------------------------- /** * If the selectionMode is either * GridSelectionMode.SINGLE_CELLS * or GridSelectionMode.MULTIPLE_CELLS, determines if the cell * is in the current selection. * * @param rowIndex The 0-based row index. * * @param columnsIndex The 0-based column index. * * @return true if the cell is in the selection. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function containsCell(rowIndex:int, columnIndex:int):Boolean { if (!validateCell(rowIndex, columnIndex)) return false; return regionsContainCell(rowIndex, columnIndex); } /** * If the selectionMode is * GridSelectionMode.MULTIPLE_CELLS, determines if all the * cells in the cell region are in the current selection. * * @param rowIndex The 0-based row index. * * @param columnsIndex The 0-based column index. * * @param rowCount The row height of the region. * * @param columnsCount The width of the cell region, in columns. * * @return true if the cells are in the selection. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function containsCellRegion(rowIndex:int, columnIndex:int, rowCount:int, columnCount:int):Boolean { if (!validateCellRegion(rowIndex, columnIndex, rowCount, columnCount)) return false; if (rowCount * columnCount > selectionLength) return false; const cellRegionsLength:int = cellRegions.length; if (cellRegionsLength == 0) return false; // Simple selection. if (cellRegionsLength == 1) { const cr:CellRect = cellRegions[0]; return (rowIndex >= cr.top && columnIndex >= cr.left && rowIndex + rowCount <= cr.bottom && columnIndex + columnCount <= cr.right); } // Not a simple selection so we're going to have to check each cell. const bottom:int = rowIndex + rowCount; const right:int = columnIndex + columnCount; for (var r:int = rowIndex; r < bottom; r++) { for (var c:int = columnIndex; c < right; c++) { if (!containsCell(r, c)) return false; } } return true; } /** * If the selectionMode is either GridSelectionMode.SINGLE_CELLS * or GridSelectionMode.MULTIPLE_CELLS, replaces the current * selection with the cell at the given location. The cell must be in * a visible column. * * @param rowIndex The 0-based row index. * * @param columnsIndex The 0-based column index. * * @return true no errors. * Returns false if * rowIndex is not a valid index in dataProvider, * if columnIndex is not a valid index in columns, * if the selectionMode is invalid or the column is not visible. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setCell(rowIndex:int, columnIndex:int):Boolean { if (!validateCell(rowIndex, columnIndex)) return false; // columns and indexes validated above. const columnVisible:Boolean = isColumnVisible(columnIndex); if (columnVisible) internalSetCellRegion(rowIndex, columnIndex, 1, 1); return columnVisible; } /** * If the selectionMode is GridSelectionMode.MULTIPLE_CELLS, * adds the cell at the given location to the cell selection. The cell * must be in a visible column. * * @param rowIndex The 0-based row index. * * @param columnsIndex The 0-based column index. * * @return true no errors. * Returns false if * rowIndex is not a valid index in dataProvider, * if columnIndex is not a valid index in columns, * if the selectionMode is invalid or the column is not visible. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addCell(rowIndex:int, columnIndex:int):Boolean { if (!validateCellRegion(rowIndex, columnIndex, 1, 1)) return false; // columns and indexes validated above. const columnVisible:Boolean = isColumnVisible(columnIndex); if (columnVisible) internalAddCell(rowIndex, columnIndex); return columnVisible; } /** * If the selectionMode is either GridSelectionMode.SINGLE_CELL * or GridSelectionMode.MULTIPLE_CELLS, removes the cell at the * given position from the cell selection. * * @param rowIndex The 0-based row index. * * @param columnsIndex The 0-based column index. * * @return true if no errors. * Returns false if rowIndex * is not a valid index in dataProvider, or if * columnIndex is not a valid index in columns, * or if the selectionMode is invalid. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeCell(rowIndex:int, columnIndex:int):Boolean { if (!validateCell(rowIndex, columnIndex)) return false; if (requireSelection && containsCell(rowIndex, columnIndex) && selectionLength == 1) return false; internalRemoveCell(rowIndex, columnIndex); return true; } /** * If the selectionMode is GridSelectionMode.MULTIPLE_CELLS, * replaces the current selection with the cells in the given cell region. * The origin of the cell region is the cell location specified by * rowIndex and columnIndex, the width is * columnCount and the height is rowCound. * *

Only cells in columns which are visible at the time of selection are * included in the selection.

* * @param rowIndex The 0-based row index of the origin. * * @param columnsIndex The 0-based column index of the origin. * * @param rowCount The row height of the cell region. * * @param columnsCount The column width of the cell region. * * @return true if no errors. * Returns false if * rowIndex is not a valid index in dataProvider, * if columnIndex is not a valid index in columns, * or if the selectionMode is invalid. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setCellRegion(rowIndex:int, columnIndex:int, rowCount:uint, columnCount:uint):Boolean { if (!validateCellRegion(rowIndex, columnIndex, rowCount, columnCount)) return false; removeSelection(); var startColumnIndex:int = columnIndex; var curColumnCount:int = 0; const endColumnIndex:int = columnIndex + columnCount - 1; for (var i:int = columnIndex; i <= endColumnIndex; i++) { // columns and indexes validated above. const columnVisible:Boolean = isColumnVisible(i); if (columnVisible) { curColumnCount++; continue; } // This column isn't visible so commit the cell region. internalAddCellRegion(rowIndex, startColumnIndex, rowCount, curColumnCount); curColumnCount = 0; startColumnIndex = i + 1; } // If the last column(s) are not visible, need to commit the last // cell region. if (curColumnCount > 0) internalAddCellRegion(rowIndex, startColumnIndex, rowCount, curColumnCount); return true; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private */ private function isRowSelectionMode():Boolean { const mode:String = selectionMode; return mode == GridSelectionMode.SINGLE_ROW || mode == GridSelectionMode.MULTIPLE_ROWS; } /** * @private */ private function isCellSelectionMode():Boolean { const mode:String = selectionMode; return mode == GridSelectionMode.SINGLE_CELL || mode == GridSelectionMode.MULTIPLE_CELLS; } /** * @private * Assumes columns is set and index is valid. */ private function isColumnVisible(columnIndex:int):Boolean { return GridColumn(grid.columns.getItemAt(columnIndex)).visible; } /** * @private */ private function getGridColumnsLength():uint { if (grid == null) return 0; const columns:IList = grid.columns; return (columns) ? columns.length : 0; } /** * @private */ private function getGridDataProviderLength():uint { if (grid == null) return 0; const dataProvider:IList = grid.dataProvider; return (dataProvider) ? dataProvider.length : 0; } /** * @private * True if the given cell is contained in the list of cell regions. */ private function regionsContainCell(rowIndex:int, columnIndex:int):Boolean { // Find the index of the last isAdd=true cell region that contains // row,columnIndex. const cellRegionsLength:int = cellRegions.length; var index:int = -1; for (var i:int = 0; i < cellRegionsLength; i++) { var cr:CellRect = cellRegions[i]; if (cr.isAdd && cr.containsCell(rowIndex, columnIndex)) index = i; } // Is there an isAdd=true CellRegion that contains the cell? if (index == -1) return false; // Starting with index, if any subsequent isAdd=false cell region // contains row,columnIndex return false. for (i = index + 1; i < cellRegionsLength; i++) { cr = cellRegions[i]; if (!cr.isAdd && cr.containsCell(rowIndex, columnIndex)) return false; } return true; } /** * @private * If requiredSelection, then there must always be at least one row/cell * selected. If the selection is changed, the caret is changed to match. * * @return true if the selection has changed. */ private function ensureRequiredSelection():Boolean { var selectionChanged:Boolean; if (!requireSelection) return false; if (getGridDataProviderLength() == 0 || getGridColumnsLength() == 0) return false; // If there isn't a selection, set one, using the grid method rather // than the internal one, so that the caretPosition will be updated too. if (isRowSelectionMode()) { if (selectionLength == 0) selectionChanged = grid.setSelectedIndex(0); } else if (isCellSelectionMode()) { if (selectionLength == 0) selectionChanged = grid.setSelectedCell(0, 0); } return selectionChanged; } /** * @private * Remove any currently selected rows, cells and cached items. This * disregards the requireSelection flag. */ private function removeSelection():void { cellRegions.length = 0; _selectionLength = 0; selectedItem = null; } /** * @private * True if the selection mode is row-based and the 0-based index is * valid index in the dataProvider. */ protected function validateIndex(index:int):Boolean { // Don't validate. if (inCollectionHandler) return true; return isRowSelectionMode() && index >= 0 && index < getGridDataProviderLength(); } /** * @private * True if the selection mode is GridSelectionMode.MULTIPLE_ROWS * and each index in indices is a valid index into the * dataProvider. */ protected function validateIndices(indices:Vector.):Boolean { if (selectionMode == GridSelectionMode.MULTIPLE_ROWS) { // Don't validate. if (inCollectionHandler) return true; for each (var index:int in indices) { if (index < 0 || index >= getGridDataProviderLength()) return false; } return true; } return false; } /** * @private * True if the selection mode is GridSelectionMode.SINGLE_CELL * or code>GridSelectionMode.MULTIPLE_CELLS * and the 0-based index is valid index in columns. */ protected function validateCell(rowIndex:int, columnIndex:int):Boolean { // Don't validate. if (inCollectionHandler) return true; return isCellSelectionMode() && rowIndex >= 0 && rowIndex < getGridDataProviderLength() && columnIndex >= 0 && columnIndex < getGridColumnsLength(); } /** * @private * True if the selection mode is * GridSelectionMode.MULTIPLE_CELLS and the entire cell region * is contained within the grid. */ protected function validateCellRegion(rowIndex:int, columnIndex:int, rowCount:int, columnCount:int):Boolean { if (selectionMode == GridSelectionMode.MULTIPLE_CELLS) { // Don't validate. if (inCollectionHandler) return true; const maxRows:int = getGridDataProviderLength(); const maxColumns:int = getGridColumnsLength(); return (rowIndex >= 0 && rowCount >= 0 && rowIndex + rowCount <= maxRows && columnIndex >= 0 && columnCount >= 0 && columnIndex + columnCount <= maxColumns); } return false; } /** * @private * True if the selection mode is * GridSelectionMode.MULTIPLE_ROW and the entire row region * is contained within the grid. */ protected function validateRowRegion(rowIndex:int, rowCount:int):Boolean { if (selectionMode == GridSelectionMode.MULTIPLE_ROWS) { // Don't validate. if (inCollectionHandler) return true; const maxRows:int = getGridDataProviderLength(); return (rowIndex >= 0 && rowCount >= 0 && rowIndex + rowCount <= maxRows); } return false; } /** * @private * Initalize the list of cellRegions with this one. */ private function internalSetCellRegion(rowIndex:int, columnIndex:int=0, rowCount:uint=1, columnCount:uint=1):void { const cr:CellRect = new CellRect(rowIndex, columnIndex, rowCount, columnCount, true); removeSelection(); cellRegions.push(cr); _selectionLength = rowCount * columnCount; if (preserveSelection && (selectionMode == GridSelectionMode.SINGLE_ROW || selectionMode == GridSelectionMode.SINGLE_CELL)) { selectedItem = grid.dataProvider.getItemAt(rowIndex); } } /** * @private * This should only be used for setCellRegion. The selection should * be cleared first. This will add a cellRegion to the list of cellRegions. * This allows the special-handling needed for setting a cell region * which has one of more columns which are not visible and not to be * included in the selection. * * The code is not equipped to handle the general case of overlapping * cell regions. */ private function internalAddCellRegion(rowIndex:int, columnIndex:int=0, rowCount:uint=1, columnCount:uint=1):void { const cr:CellRect = new CellRect(rowIndex, columnIndex, rowCount, columnCount, true); cellRegions.push(cr); _selectionLength += rowCount * columnCount; } /** * @private * Add the given row/cell to the list of cellRegions. */ private function internalAddCell(rowIndex:int, columnIndex:int=0):void { if (!regionsContainCell(rowIndex, columnIndex)) { const cr:CellRect = new CellRect(rowIndex, columnIndex, 1, 1, true); cellRegions.push(cr); // If the length is current before this add, just increment the // length. if (_selectionLength >= 0) _selectionLength++; } } /** * @private * Remove the given row/cell from the list of cellRegions. */ private function internalRemoveCell(rowIndex:int, columnIndex:int=0):void { if (regionsContainCell(rowIndex, columnIndex)) { const cr:CellRect = new CellRect(rowIndex, columnIndex, 1, 1, false); cellRegions.push(cr); // If the length is current before this remove, just decrement the // length. if (_selectionLength >= 0) _selectionLength--; selectedItem = null; } } /** * @private * Find the bounding box for all the added cell regions. It could be * larger than the current selection region if cell regions have been * removed. */ private function getCellRegionsBounds():Rectangle { var bounds:Rectangle = new Rectangle(); const cellRegionsLength:int = cellRegions.length; for (var i:int = 0; i < cellRegionsLength; i++) { var cr:CellRect = cellRegions[i]; if (!cr.isAdd) continue; bounds = bounds.union(cr); } return bounds; } //-------------------------------------------------------------------------- // // Data Provider Collection methods // //-------------------------------------------------------------------------- /** * @private * Called when the grid's dataProvider dispatches a * CollectionEvent.COLLECTION_CHANGE event. It handles * each of the events defined in CollectionEventKind. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function dataProviderCollectionChanged(event:CollectionEvent):void { inCollectionHandler = true; switch (event.kind) { case CollectionEventKind.ADD: { dataProviderCollectionAdd(event); break; } case CollectionEventKind.MOVE: { dataProviderCollectionMove(event); break; } case CollectionEventKind.REFRESH: { dataProviderCollectionRefresh(event); break; } case CollectionEventKind.REMOVE: { dataProviderCollectionRemove(event); break; } case CollectionEventKind.REPLACE: { dataProviderCollectionReplace(event); break; } case CollectionEventKind.RESET: { dataProviderCollectionReset(event); break; } case CollectionEventKind.UPDATE: { dataProviderCollectionUpdate(event); break; } } inCollectionHandler = false; } /** * @private * Add an item to the collection. */ private function dataProviderCollectionAdd(event:CollectionEvent):void { handleRowAdd(event.location, event.items.length); ensureRequiredSelection(); } /** * @private */ private function handleRowAdd(insertIndex:int, insertCount:int=1):void { for (var cnt:int = 0; cnt < insertCount; cnt++) { for (var crIndex:int = 0; crIndex < cellRegions.length; crIndex++) { var cr:CellRect = cellRegions[crIndex]; // If the insert is before the region or at the first row of // the region, move the region down a row. If the insert is // in the region (but not the first row), split the region // into two and insert the new region. if (insertIndex <= cr.y) { cr.y++; } else if (insertIndex < cr.bottom) { var newCR:CellRect = new CellRect(insertIndex + 1, cr.x, cr.bottom - insertIndex, cr.width, cr.isAdd); cr.height = insertIndex - cr.y; // insert newCR just after cr cellRegions.splice(++crIndex, 0, newCR); _selectionLength = -1; // recalculate } } } } /** * @private * The item has been moved from the oldLocation to location. */ private function dataProviderCollectionMove(event:CollectionEvent):void { const oldRowIndex:int = event.oldLocation; const newRowIndex:int = event.location; handleRowRemove(oldRowIndex); // If the row is removed before the newly added item // then change index to account for this. if (newRowIndex > oldRowIndex) newRowIndex--; handleRowAdd(newRowIndex); } /** * @private * The sort or filter on the collection changed. */ private function dataProviderCollectionRefresh(event:CollectionEvent):void { handleRefreshAndReset(event); } /** * @private * If preserving the selection and the selected item is in the new view, * keep the item selected. Otherwise, clear the selection (or maintain one * if requireSelection is true). */ private function handleRefreshAndReset(event:CollectionEvent):void { // Is the selectedItem still in the collection? if (selectedItem) { const view:ICollectionView = event.currentTarget as ICollectionView; if (view && view.contains(selectedItem)) { // Selection is in view so move it to the new row location. const newRowIndex:int = grid.dataProvider.getItemIndex(selectedItem); if (selectionMode == GridSelectionMode.SINGLE_ROW) { internalSetCellRegion(newRowIndex); } else { var oldSelectedCell:CellPosition = allCells()[0]; internalSetCellRegion(newRowIndex, oldSelectedCell.columnIndex); } return; } } // Not preserving selection or selection not in current view so remove // selection. removeSelection(); ensureRequiredSelection(); return; } /** * @private * An item has been removed from the collection. */ private function dataProviderCollectionRemove(event:CollectionEvent):void { if (getGridDataProviderLength() == 0) { removeSelection(); return; } handleRowRemove(event.location, event.items.length); ensureRequiredSelection(); } /** * @private */ private function handleRowRemove(removeIndex:int, removeCount:int=1):void { for (var cnt:int = 0; cnt < removeCount; cnt++) { var crIndex:int = 0 while (crIndex < cellRegions.length) { var cr:CellRect = cellRegions[crIndex]; // Handle the cases where the remove is before the cell region // or in the cell region. if (removeIndex < cr.y) { cr.y--; } else if (removeIndex >= cr.y && removeIndex < cr.bottom) { _selectionLength = -1; // recalculate cr.height--; if (cr.height == 0) { cellRegions.splice(crIndex, 1); continue; } } crIndex++; } } } /** * @private * The item has been replaced. */ private function dataProviderCollectionReplace(event:CollectionEvent):void { // Nothing to do here unless we're saving the data items to preserve // the selection. } /** * @private * The data source changed or all the items were removed from the data * source. If there is a preserved selected item and it is in the new * data source the selection will be maintained. */ private function dataProviderCollectionReset(event:CollectionEvent):void { handleRefreshAndReset(event); } /** * @private * One or more items in the collection have been updated. */ private function dataProviderCollectionUpdate(event:CollectionEvent):void { // Nothing to do. } //-------------------------------------------------------------------------- // // Columns Collection methods // //-------------------------------------------------------------------------- /** * @private * Called when the grid's columns dispatches a * CollectionEvent.COLLECTION_CHANGE event. It handles * each of the events defined in CollectionEventKind. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function columnsCollectionChanged(event:CollectionEvent):void { inCollectionHandler = true; switch (event.kind) { case CollectionEventKind.ADD: { columnsCollectionAdd(event); break; } case CollectionEventKind.MOVE: { columnsCollectionMove(event); break; } case CollectionEventKind.REMOVE: { columnsCollectionRemove(event); break; } case CollectionEventKind.REPLACE: case CollectionEventKind.UPDATE: { break; } case CollectionEventKind.REFRESH: { columnsCollectionRefresh(event); break; } case CollectionEventKind.RESET: { columnsCollectionReset(event); break; } } inCollectionHandler = false; } /** * @private * Add an column to the columns collection. */ private function columnsCollectionAdd(event:CollectionEvent):void { // If no selectionMode or a row-based selectionMode, nothing to do. if (!isCellSelectionMode()) return; handleColumnAdd(event.location, event.items.length); ensureRequiredSelection(); } /** * @private */ private function handleColumnAdd(insertIndex:int, insertCount:int=1):void { for (var cnt:int = 0; cnt < insertCount; cnt++) { for (var crIndex:int = 0; crIndex < cellRegions.length; crIndex++) { var cr:CellRect = cellRegions[crIndex]; // If the insert is to the left of the region or at the // first column of the region, move the region to the right a // column. If the insert is in the region (but not the first // column), split the region into two and insert the new region. if (insertIndex <= cr.x) { cr.x++; } else if (insertIndex < cr.x) { var newCR:CellRect = new CellRect(cr.y, insertIndex + 1, cr.height, cr.right - insertIndex, cr.isAdd); cr.width = insertIndex - cr.x; // insert newCR just after cr cellRegions.splice(++crIndex, 0, newCR); _selectionLength = -1; // recalculate } } } } /** * @private * The column has been moved from the oldLocation to location in the * columns collection. */ private function columnsCollectionMove(event:CollectionEvent):void { // If no selectionMode or a row-based selectionMode, nothing to do. if (!isCellSelectionMode()) return; const oldColumnIndex:int = event.oldLocation; const newColumnIndex:int = event.location; handleColumnRemove(oldColumnIndex); // If the column is removed before the newly added column // then change index to account for this. if (newColumnIndex > oldColumnIndex) newColumnIndex--; handleColumnAdd(newColumnIndex); } /** * @private * A column has been removed from the columns collection. */ private function columnsCollectionRemove(event:CollectionEvent):void { // If no selectionMode or a row-based selectionMode, nothing to do. if (!isCellSelectionMode()) return; if (getGridColumnsLength() == 0) { removeSelection(); return; } handleColumnRemove(event.location, event.items.length); ensureRequiredSelection(); } /** * @private */ private function handleColumnRemove(removeIndex:int, removeCount:int=1):void { for (var cnt:int = 0; cnt < removeCount; cnt++) { var crIndex:int = 0 while (crIndex < cellRegions.length) { var cr:CellRect = cellRegions[crIndex]; // Handle the cases where the remove is before the cell region // or in the cell region. if (removeIndex < cr.x) { cr.x--; } else if (removeIndex >= cr.x && removeIndex < cr.right) { _selectionLength = -1; // recalculate cr.width--; if (cr.width == 0) { cellRegions.splice(crIndex, 1); continue; } } crIndex++; } } } /** * @private * The sort or filter on the collection changed. For columns, this is * the same as a ""reset"" event. */ private function columnsCollectionRefresh(event:CollectionEvent):void { columnsCollectionReset(event); } /** * @private * The columns changed. If the selectionMode is cell-based, don't preserve * the selection. */ private function columnsCollectionReset(event:CollectionEvent):void { // If no selectionMode or a row-based selectionMode, nothing to do. if (!isCellSelectionMode()) return; removeSelection(); ensureRequiredSelection(); } } } import flash.geom.Rectangle; /** * @private * A CellRect is a rectangle with one additional, isAdd property. * A CellRect for a row is represented with columnIndex=0 and columnCount=1. * * Mappings between Rectangle and selection cell regions: * y = rowIndex * x = columnIndex * height = rowCount * width = columnCount */ internal class CellRect extends Rectangle { public var isAdd:Boolean = false; // For a row, columnIndex=0 and columnCount=1. public function CellRect(rowIndex:int, columnIndex:int, rowCount:uint, columnCount:uint, isAdd:Boolean) { super(columnIndex, rowIndex, columnCount, rowCount); this.isAdd = isAdd; } public function containsCell(cellRowIndex:int, cellColumnIndex:int):Boolean { return contains(cellColumnIndex, cellRowIndex); } }",12516,True,2610.284904466343,median " // MPU-6050 Accelerometer + Gyro // ----------------------------- // // By arduino.cc user ""Krodal"". // June 2012 // Open Source / Public Domain // // Using Arduino 1.0.1 // It will not work with an older version, // since Wire.endTransmission() uses a parameter // to hold or release the I2C bus. // // Documentation: // - The InvenSense documents: // - ""MPU-6000 and MPU-6050 Product Specification"", // PS-MPU-6000A.pdf // - ""MPU-6000 and MPU-6050 Register Map and Descriptions"", // RM-MPU-6000A.pdf or RS-MPU-6000A.pdf // - ""MPU-6000/MPU-6050 9-Axis Evaluation Board User Guide"" // AN-MPU-6000EVB.pdf // // The accuracy is 16-bits. // // Temperature sensor from -40 to +85 degrees Celsius // 340 per degrees, -512 at 35 degrees. // // At power-up, all registers are zero, except these two: // Register 0x6B (PWR_MGMT_2) = 0x40 (I read zero). // Register 0x75 (WHO_AM_I) = 0x68. // #include float Q_angle = 0.01; float Q_gyro = 0.0003; float R_angle = 0.01; float x_bias = 0; float y_bias = 0; float XP_00 = 0, XP_01 = 0, XP_10 = 0, XP_11 = 0; float YP_00 = 0, YP_01 = 0, YP_10 = 0, YP_11 = 0; float KFangleX = 0.0; float KFangleY = 0.0; /**************Kalman Filter Functions**************/ float kalmanFilterY(float accAngle, float gyroRate, float dt) { float y, S; float K_0, K_1; KFangleY += dt * (gyroRate - y_bias); YP_00 += - dt * (YP_10 + YP_01) + Q_angle * dt; YP_01 += - dt * YP_11; YP_10 += - dt * YP_11; YP_11 += + Q_gyro * dt; y = accAngle - KFangleY; S = YP_00 + R_angle; K_0 = YP_00 / S; K_1 = YP_10 / S; KFangleY += K_0 * y; y_bias += K_1 * y; YP_00 -= K_0 * YP_00; YP_01 -= K_0 * YP_01; YP_10 -= K_1 * YP_00; YP_11 -= K_1 * YP_01; return KFangleY; } float kalmanFilterX(float accAngle, float gyroRate, float dt) { float y, S; float K_0, K_1; KFangleX += dt * (gyroRate - x_bias); XP_00 += - dt * (XP_10 + XP_01) + Q_angle * dt; XP_01 += - dt * XP_11; XP_10 += - dt * XP_11; XP_11 += + Q_gyro * dt; y = accAngle - KFangleX; S = XP_00 + R_angle; K_0 = XP_00 / S; K_1 = XP_10 / S; KFangleX += K_0 * y; x_bias += K_1 * y; XP_00 -= K_0 * XP_00; XP_01 -= K_0 * XP_01; XP_10 -= K_1 * XP_00; XP_11 -= K_1 * XP_01; return KFangleX; } // The name of the sensor is ""MPU-6050"". // For program code, I omit the '-', // therefor I use the name ""MPU6050...."". // Register names according to the datasheet. // According to the InvenSense document // ""MPU-6000 and MPU-6050 Register Map // and Descriptions Revision 3.2"", there are no registers // at 0x02 ... 0x18, but according other information // the registers in that unknown area are for gain // and offsets. // #define MPU6050_AUX_VDDIO 0x01 // R/W #define MPU6050_SMPLRT_DIV 0x19 // R/W #define MPU6050_CONFIG 0x1A // R/W #define MPU6050_GYRO_CONFIG 0x1B // R/W #define MPU6050_ACCEL_CONFIG 0x1C // R/W #define MPU6050_FF_THR 0x1D // R/W #define MPU6050_FF_DUR 0x1E // R/W #define MPU6050_MOT_THR 0x1F // R/W #define MPU6050_MOT_DUR 0x20 // R/W #define MPU6050_ZRMOT_THR 0x21 // R/W #define MPU6050_ZRMOT_DUR 0x22 // R/W #define MPU6050_FIFO_EN 0x23 // R/W #define MPU6050_I2C_MST_CTRL 0x24 // R/W #define MPU6050_I2C_SLV0_ADDR 0x25 // R/W #define MPU6050_I2C_SLV0_REG 0x26 // R/W #define MPU6050_I2C_SLV0_CTRL 0x27 // R/W #define MPU6050_I2C_SLV1_ADDR 0x28 // R/W #define MPU6050_I2C_SLV1_REG 0x29 // R/W #define MPU6050_I2C_SLV1_CTRL 0x2A // R/W #define MPU6050_I2C_SLV2_ADDR 0x2B // R/W #define MPU6050_I2C_SLV2_REG 0x2C // R/W #define MPU6050_I2C_SLV2_CTRL 0x2D // R/W #define MPU6050_I2C_SLV3_ADDR 0x2E // R/W #define MPU6050_I2C_SLV3_REG 0x2F // R/W #define MPU6050_I2C_SLV3_CTRL 0x30 // R/W #define MPU6050_I2C_SLV4_ADDR 0x31 // R/W #define MPU6050_I2C_SLV4_REG 0x32 // R/W #define MPU6050_I2C_SLV4_DO 0x33 // R/W #define MPU6050_I2C_SLV4_CTRL 0x34 // R/W #define MPU6050_I2C_SLV4_DI 0x35 // R #define MPU6050_I2C_MST_STATUS 0x36 // R #define MPU6050_INT_PIN_CFG 0x37 // R/W #define MPU6050_INT_ENABLE 0x38 // R/W #define MPU6050_INT_STATUS 0x3A // R #define MPU6050_ACCEL_XOUT_H 0x3B // R #define MPU6050_ACCEL_XOUT_L 0x3C // R #define MPU6050_ACCEL_YOUT_H 0x3D // R #define MPU6050_ACCEL_YOUT_L 0x3E // R #define MPU6050_ACCEL_ZOUT_H 0x3F // R #define MPU6050_ACCEL_ZOUT_L 0x40 // R #define MPU6050_TEMP_OUT_H 0x41 // R #define MPU6050_TEMP_OUT_L 0x42 // R #define MPU6050_GYRO_XOUT_H 0x43 // R #define MPU6050_GYRO_XOUT_L 0x44 // R #define MPU6050_GYRO_YOUT_H 0x45 // R #define MPU6050_GYRO_YOUT_L 0x46 // R #define MPU6050_GYRO_ZOUT_H 0x47 // R #define MPU6050_GYRO_ZOUT_L 0x48 // R #define MPU6050_EXT_SENS_DATA_00 0x49 // R #define MPU6050_EXT_SENS_DATA_01 0x4A // R #define MPU6050_EXT_SENS_DATA_02 0x4B // R #define MPU6050_EXT_SENS_DATA_03 0x4C // R #define MPU6050_EXT_SENS_DATA_04 0x4D // R #define MPU6050_EXT_SENS_DATA_05 0x4E // R #define MPU6050_EXT_SENS_DATA_06 0x4F // R #define MPU6050_EXT_SENS_DATA_07 0x50 // R #define MPU6050_EXT_SENS_DATA_08 0x51 // R #define MPU6050_EXT_SENS_DATA_09 0x52 // R #define MPU6050_EXT_SENS_DATA_10 0x53 // R #define MPU6050_EXT_SENS_DATA_11 0x54 // R #define MPU6050_EXT_SENS_DATA_12 0x55 // R #define MPU6050_EXT_SENS_DATA_13 0x56 // R #define MPU6050_EXT_SENS_DATA_14 0x57 // R #define MPU6050_EXT_SENS_DATA_15 0x58 // R #define MPU6050_EXT_SENS_DATA_16 0x59 // R #define MPU6050_EXT_SENS_DATA_17 0x5A // R #define MPU6050_EXT_SENS_DATA_18 0x5B // R #define MPU6050_EXT_SENS_DATA_19 0x5C // R #define MPU6050_EXT_SENS_DATA_20 0x5D // R #define MPU6050_EXT_SENS_DATA_21 0x5E // R #define MPU6050_EXT_SENS_DATA_22 0x5F // R #define MPU6050_EXT_SENS_DATA_23 0x60 // R #define MPU6050_MOT_DETECT_STATUS 0x61 // R #define MPU6050_I2C_SLV0_DO 0x63 // R/W #define MPU6050_I2C_SLV1_DO 0x64 // R/W #define MPU6050_I2C_SLV2_DO 0x65 // R/W #define MPU6050_I2C_SLV3_DO 0x66 // R/W #define MPU6050_I2C_MST_DELAY_CTRL 0x67 // R/W #define MPU6050_SIGNAL_PATH_RESET 0x68 // R/W #define MPU6050_MOT_DETECT_CTRL 0x69 // R/W #define MPU6050_USER_CTRL 0x6A // R/W #define MPU6050_PWR_MGMT_1 0x6B // R/W #define MPU6050_PWR_MGMT_2 0x6C // R/W #define MPU6050_FIFO_COUNTH 0x72 // R/W #define MPU6050_FIFO_COUNTL 0x73 // R/W #define MPU6050_FIFO_R_W 0x74 // R/W #define MPU6050_WHO_AM_I 0x75 // R // Defines for the bits, to be able to change // between bit number and binary definition. // By using the bit number, programming the sensor // is like programming the AVR microcontroller. // But instead of using ""(1< 180) { accel_angle_x -= 360; } // Y accel if (accel_angle_y < -180) { accel_angle_y += 360; } else if (accel_angle_y > 180) { accel_angle_y -= 360; } // Z accel if (accel_angle_z < -180) { accel_angle_z += 360; } else if (accel_angle_z > 180) { accel_angle_z -= 360; } // GYRO // X gyro if (gyro_angle_x < -180) { gyro_angle_x += 360; } else if (gyro_angle_x > 180) { gyro_angle_x -= 360; } // Y gyro if (gyro_angle_y < -180) { gyro_angle_y += 360; } else if (gyro_angle_y > 180) { gyro_angle_y -= 360; } // Z gyro if (gyro_angle_z < -180) { gyro_angle_z += 360; } else if (gyro_angle_z > 180) { gyro_angle_z -= 360; } uint32_t del_t = tK/tC; // Send the data to the serial port Serial.print(F(""DEL:"")); //Delta T Serial.print(dt, 2); Serial.print(F(""#ACC:"")); //Accelerometer angle Serial.print(accel_angle_x, 2); Serial.print(F("","")); Serial.print(accel_angle_y, 2); Serial.print(F("","")); Serial.print(accel_angle_z, 2); Serial.print(F(""#GYR:"")); Serial.print(unfiltered_gyro_angle_x, 2); //Gyroscope angle Serial.print(F("","")); Serial.print(unfiltered_gyro_angle_y, 2); Serial.print(F("","")); Serial.print(unfiltered_gyro_angle_z, 2); Serial.print(F(""#MAG:"")); //Magnetometer angle Serial.print(mag_x, 2); Serial.print(F("","")); Serial.print(mag_y, 2); Serial.print(F("","")); Serial.print(mag_z, 2); Serial.print(F(""#FIL:"")); //Filtered angle Serial.print(angle_x, 2); Serial.print(F("","")); Serial.print(angle_y, 2); Serial.print(F("","")); Serial.print(angle_z, 2); Serial.print(F(""#KAL:"")); //Filtered angle Serial.print(kal_x, 2); Serial.print(F("","")); Serial.print(kal_y, 2); Serial.print(F("","")); Serial.print(kal_z, 2); // Serial.print(""TIM:""); // Serial.print(tC); // Serial.print(F("","")); // Serial.print(tK); // Serial.print(F("","")); // Serial.print(del_t); Serial.println(F("""")); // Delay so we don't swamp the serial port delay(5); } // -------------------------------------------------------- // **************MPU6050_read***************** // // This is a common function to read multiple bytes // from an I2C device. // // It uses the boolean parameter for Wire.endTransMission() // to be able to hold or release the I2C-bus. // This is implemented in Arduino 1.0.1. // // Only this function is used to read. // There is no function for a single byte. // int MPU6050_read(int start, uint8_t *buffer, int size) { int i, n, error; Wire.beginTransmission(MPU6050_I2C_ADDRESS); n = Wire.write(start); if (n != 1) return (-10); n = Wire.endTransmission(false); // hold the I2C-bus if (n != 0) return (n); // Third parameter is true: relase I2C-bus after data is read. Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true); i = 0; while(Wire.available() && iselectedIndex property or a change * to the selected tab in the TabBar control. * * @eventType spark.events.IndexChangeEvent.CHANGE * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""change"", type=""spark.events.IndexChangeEvent"")] /** * Dispatched before the selected view navigator is changed. * Canceling this event prevents the active view navigator * from changing. * * @eventType spark.events.IndexChangeEvent.CHANGING * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""changing"", type=""spark.events.IndexChangeEvent"")] /** * Dispatched when the collection of view navigators managed by the * TabbedViewNavigator changes. * * @eventType mx.events.CollectionEvent.COLLECTION_CHANGE * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""collectionChange"", type=""mx.events.CollectionEvent"")] /** * Dispatched when the view navigator's selected index changes. * When this event is dispatched, the selectedIndex * and selectedNavigator properties reference the * newly selected view navigator. * * @eventType mx.events.FlexEvent.VALUE_COMMIT * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""valueCommit"", type=""mx.events.FlexEvent"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""TabbedViewNavigator.png"")] /** * The TabbedViewNavigator class is a container that manages a collection * of view navigator containers. * Only one view navigator is active and visible at a time. * This class includes a TabBar control that provides the ability to toggle between * the collection of view navigators. * *

The following image shows a TabbedViewNavigator with three sections: * Employees, Contacts, and Search:

* *

* *

* *

The TabbedViewNavigatorApplication container automatically creates * a single TabbedViewNavigator container for the entire application. * You can reference the TabbedViewNavigator object by using the navigator * property of the TabbedViewNavigatorApplication container.

* *

The active or selected navigator can be changed by clicking the corresponding * tab in the TabBar or by changing the selectedIndex property of * the component.

* *

The contents of a child view navigator is destroyed when it is deactivate, * and dynamically created when activated.

* * @see spark.components.View * @see spark.components.ViewNavigator * @see spark.components.TabBar * * @includeExample examples/TabbedViewNavigatorExample.mxml -noswf * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class TabbedViewNavigator extends ViewNavigatorBase implements ISelectableList { //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- // TODO (chiedozi): Consider having a NO_SELECTION constant to differentiate // between NO_PROPOSED_SELECTION and clearing the selection. See List. It // seems redundant because TabbedViewNavigator expects requireSelection to be // true on its TabBar. /** * @private * Static constant representing no proposed selection. */ private static const NO_PROPOSED_SELECTION:int = -1; /** * @private * The animation duration used when hiding and showing the action bar. */ private static const TAB_BAR_ANIMATION_DURATION:Number = 250; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function TabbedViewNavigator() { super(); addEventListener(ElementExistenceEvent.ELEMENT_ADD, elementAddHandler); addEventListener(ElementExistenceEvent.ELEMENT_REMOVE, elementRemoveHandler); } //-------------------------------------------------------------------------- // // Skin Parts // //-------------------------------------------------------------------------- [Bindable] [SkinPart(required=""false"")] /** * A skin part that defines the tab bar of the navigator. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var tabBar:ButtonBarBase; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var animateTabBarVisbility:Boolean = false; /** * @private */ private var contentGroupProps:Object; /** * @private * Determines if a changing event has already been dispatched. * This was introduced to prevent the IndexChangeEvent from * dispatching twice when the tabBar selection changes. */ private var changingEventDispatched:Boolean = false; /** * @private */ private var dataProviderChanged:Boolean = false; /** * @private */ private var explicitTabBarMouseEnabled:Boolean = false; /** * @private * Keeps track of the tab that was last selected. See * tabBarRendererClicked() for information on how it's used. */ private var lastSelectedIndex:int = -1; /** * @private */ private var selectedIndexChanged:Boolean = false; /** * @private */ private var selectedIndexAdjusted:Boolean = false; /** * @private */ private var showingTabBar:Boolean; /** * @private */ private var tabBarVisibilityEffect:IEffect; /** * @private */ private var tabBarProps:Object; /** * @private */ private var tabBarVisibilityChanged:Boolean = false; /** * @private */ mx_internal var selectedNavigatorChangingView:Boolean = false; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // activeView //---------------------------------- [Bindable(""viewChangeComplete"")] /** * @private */ override public function get activeView():View { if (selectedNavigator) return selectedNavigator.activeView; return null; } //---------------------------------- // exitApplicationOnBackKey //---------------------------------- /** * @private */ override mx_internal function get exitApplicationOnBackKey():Boolean { if (selectedNavigator) return selectedNavigator.exitApplicationOnBackKey; return super.exitApplicationOnBackKey; } //---------------------------------- // maintainNavigationStack //---------------------------------- private var _maintainNavigationStack:Boolean = true; /** * @private * Specifies whether the navigation stack of the view navigator * should remain intact when the view navigator is deactivated. * If true, when reactivated the view history * remains the same. * If false, the navigator displays the * first view in its navigation stack. * * @default true * * @see spark.components.ViewNavigator * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function get maintainNavigationStack():Boolean { return _maintainNavigationStack; } /** * @private */ mx_internal function set maintainNavigationStack(value:Boolean):void { _maintainNavigationStack = value; } //---------------------------------- // navigators //---------------------------------- /** * The view navigators that are managed by this TabbedViewNavigator. * Each view navigator is represented as a tab in the tab bar * of this TabbedViewNavigator. * Only one view navigator can be active at a time. * You can reference the active view navigator by using * the selectedNavigator property. * *

Changing this property causes the current view navigator to be removed, * and sets the selectedIndex to 0. * This operation cannot be canceled and is committed immediately.

* * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get navigators():Vector. { var mxmlContent:Array = currentContentGroup.getMXMLContent(); if (!mxmlContent) return null; // When this class was first released, navigators was typed Vector // and not Array. In 4.6, TabbedViewNavigator moved away from this // model and uses mxmlContent to manage children. To maintain backwards // compatibility, the return type for this method remained the same. // As a result, the mxmlContent array will need to converted. return Vector.(mxmlContent); } /** * @private */ public function set navigators(value:Vector.):void { // When this class was first released, navigators was typed Vector // and not Array. In 4.6, TabbedViewNavigator moved away from this // model and uses mxmlContent to manage children. To maintain backwards // compatibility, the return type for this method remained the same. // As a result, the value vector needs to be converted to an array var contentArray:Array = []; for each (var navigator:ViewNavigatorBase in value) { contentArray.push(navigator); setupNavigator(navigator); } mxmlContent = contentArray; // The proposed selected index is reset because it is no longer valid // since the array of navigators has changed. selectedIndexChanged = false; // Invalidate property flags dataProviderChanged = true; invalidateProperties(); // Notify listeners that the collection changed internalDispatchEvent(CollectionEventKind.RESET); } //---------------------------------- // selectedNavigator //---------------------------------- [Bindable(""change"")] /** * The selected view navigator for the TabbedViewNavigator. * Only one view navigator can be active at a time. * The active view navigator can be set by changing the * selectedIndex property or by selecting * a tab in the TabBar control. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectedNavigator():ViewNavigatorBase { if (length == 0 || selectedIndex < 0 || selectedIndex >= length) return null; return getElementAt(selectedIndex) as ViewNavigatorBase; } //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- /** * Hides the tab bar of the navigator. * * @param animate Indicates whether a hide effect should play * as the tab bar disappears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function hideTabBar(animate:Boolean = true):void { if (!tabBar) return; showingTabBar = false; animateTabBarVisbility = animate; tabBarVisibilityChanged = true; invalidateProperties(); } /** * Shows the tab bar of the navigator * * @param animate Indicates whether a show effect should play * as the tab bar appears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function showTabBar(animate:Boolean = true):void { if (!tabBar) return; showingTabBar = true; animateTabBarVisbility = animate; tabBarVisibilityChanged = true; invalidateProperties(); } /** * @private * Updates the navigator's state based on the properties set * on the active view. The main use cases are to hide the * TabBar and the change the overlay state. * * @param view The active view. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override public function updateControlsForView(view:View):void { super.updateControlsForView(view); if (view) { if (tabBar) tabBar.visible = tabBar.includeInLayout = view.tabBarVisible; overlayControls = view.overlayControls; } else { // If the current view is null, the tab bar is shown so that the // user still has a ui for changing the selected tab. if (tabBar) tabBar.visible = tabBar.includeInLayout = true; overlayControls = false; } tabBarVisibilityChanged = false; } /** * Calls the backKeyUpHandler() of the selected navigator. * *

TabbedViewNavigatorApplication automatically calls this method when * the back key is pressed.

* * @langversion 3.0 * @playerversion AIR 3.1 * @productversion Flex 4.6 */ override public function backKeyUpHandler():void { if (selectedNavigator) selectedNavigator.backKeyUpHandler(); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * @private * Calculates the final positions for the tab bar visibility animations. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function prepareTabBarForAnimation(showAnimation:Boolean):void { var animateTabBarUp:Boolean; if (overlayControls) { // If the control is overlaid on top, the tabBar is animated up if // the tabBar is above the center of the navigator animateTabBarUp = (tabBar.y + (tabBar.height / 2)) <= height / 2; } else { // The tabBar is animated up if it is above the contentGroup animateTabBarUp = tabBar.y <= contentGroup.y; } // Need to validate to capture final positions and sizes of skin parts LayoutManager.getInstance().validateNow(); // This will store the final location and sizes of the components tabBarProps.end = captureAnimationValues(tabBar); contentGroupProps.end = captureAnimationValues(contentGroup); if (tabBarVisibilityChanged) { if (animateTabBarUp) { if (tabBarProps.start.visible) tabBarProps.end.y = -tabBar.height; else tabBarProps.start.y = -tabBar.height; } else { if (tabBarProps.start.visible) tabBarProps.end.y = this.height; else tabBarProps.start.y = this.height; } } tabBar.visible = true; tabBar.includeInLayout = false; tabBar.cacheAsBitmap = true; } /** * @private */ override mx_internal function canRemoveCurrentView():Boolean { return (!selectedNavigator || selectedNavigator.canRemoveCurrentView()); } /** * @private */ private function addNavigatorListeners(navigator:ViewNavigatorBase):void { navigator.addEventListener(""viewChangeComplete"", navigator_viewChangeCompleteHandler); navigator.addEventListener(""viewChangeStart"", navigator_viewChangeStartHandler); navigator.addEventListener(ElementExistenceEvent.ELEMENT_ADD, navigator_elementAddHandler); navigator.addEventListener(ElementExistenceEvent.ELEMENT_REMOVE, navigator_elementRemoveHandler); } /** * @private */ private function removeNavigatorListeners(navigator:ViewNavigatorBase):void { navigator.removeEventListener(""viewChangeComplete"", navigator_viewChangeCompleteHandler); navigator.removeEventListener(""viewChangeStart"", navigator_viewChangeStartHandler); navigator.removeEventListener(ElementExistenceEvent.ELEMENT_ADD, navigator_elementAddHandler); navigator.removeEventListener(ElementExistenceEvent.ELEMENT_REMOVE, navigator_elementRemoveHandler); } /** * @private */ private function setupNavigator(navigator:ViewNavigatorBase):void { navigator.setParentNavigator(this); navigator.visible = false; navigator.includeInLayout = false; // All navigators should be inactive when initialized. The proper // navigator will be activated during commitProperties(). navigator.setActive(false); startTrackingUpdates(navigator); } /** * @private */ private function cleanUpNavigator(navigator:ViewNavigatorBase):void { navigator.setParentNavigator(null); if (navigator.isActive) navigator.setActive(false); if (navigator.activeView) { navigator.activeView.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } removeNavigatorListeners(navigator); stopTrackingUpdates(navigator); } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override protected function commitProperties():void { var changeEvent:IndexChangeEvent; if (selectedIndexChanged || selectedIndexAdjusted || dataProviderChanged) { var navigator:ViewNavigatorBase; // Store the old index var oldIndex:int = _selectedIndex; if (selectedIndex >= length) selectedIndex = (length > 0) ? 0 : NO_PROPOSED_SELECTION; var indexChangedPrevented:Boolean = false; // The selected index property can be changed programmitically on the // TabbedViewNavigator or by its tab bar in response to a user action. If // this was initiated by the tab bar, a chaning event would have already been // dispatched in tabBar_indexChanging(). if (initialized && selectedIndexChanged && !changingEventDispatched) { // If the active view's REMOVING event or the navigator's // CHANGING event was canceled, prevent the index change if (!indexCanChange(selectedIndex)) { _proposedSelectedIndex = NO_PROPOSED_SELECTION; indexChangedPrevented = true; } } changingEventDispatched = false; if (!indexChangedPrevented) { // If the data provider has changed, the navigator elements have // already been removed, so the following code doesn't need to run if (!selectedIndexAdjusted && !dataProviderChanged && _selectedIndex >= 0 && _selectedIndex < length) { navigator = getElementAt(_selectedIndex) as ViewNavigatorBase; navigator.setActive(false, !maintainNavigationStack); navigator.visible = false; navigator.includeInLayout = false; if (navigator.activeView) navigator.activeView.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); removeNavigatorListeners(navigator); } commitSelection(); if (_selectedIndex >= 0) { // If there is no focus or the item that had focus isn't // on the display list anymore, update the focus to be // the active view or the view navigator updateFocus(); navigator = getElementAt(_selectedIndex) as ViewNavigatorBase; navigator.setActive(true); navigator.visible = true; navigator.includeInLayout = true; addNavigatorListeners(navigator); // Update the states of the controls on the newly activated view navigator. // The updateControlsForView() method will automatically bubble up to all // parents of the navigator. navigator.updateControlsForView(navigator.activeView); // Force a validation of the new navigator to prevent a flicker from // occurring in cases where multiple validation passes are required // to completely validate a view if (initialized) currentContentGroup.validateNow(); if (navigator.activeView) { navigator.activeView.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } } // Dispatch selection change event if (hasEventListener(IndexChangeEvent.CHANGE)) { changeEvent = new IndexChangeEvent(IndexChangeEvent.CHANGE, false, false); changeEvent.oldIndex = oldIndex; changeEvent.newIndex = _selectedIndex; } } selectedIndexAdjusted = false; dataProviderChanged = false; selectedIndexChanged = false; } if (tabBarVisibilityChanged) commitVisibilityChanges(); // When true, this flag prevents tab bar animations from running. This flag // is only set to true if the application received an orientation event this // frame (See ViewNavigatorBase). The flag is reset at the end of commitProperties // so that animations run again. if (disableNextControlAnimation) disableNextControlAnimation = false; // Call base class' commitProperties after the above so that state changes // as a result of overlayControls are caught. This should be okay because // TabbedViewNavigator doesn't need any properties in its base class being // validated to complete the above code super.commitProperties(); // Dispatch the index change event after super.commitProperties() has changed // so the callbacks can deal with state changes performed by commitProperties. if (changeEvent) dispatchEvent(changeEvent); } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function commitSelection():void { _selectedIndex = _proposedSelectedIndex; _proposedSelectedIndex = NO_PROPOSED_SELECTION; lastSelectedIndex = _selectedIndex; if (hasEventListener(FlexEvent.VALUE_COMMIT)) dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } /** * @private * Commits the requested visibility changes made to the action * bar and tab bar. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function commitVisibilityChanges():void { // Can't change the visibility during a view transition if (selectedNavigatorChangingView) return; // If an animation is running, end it if (tabBarVisibilityEffect) tabBarVisibilityEffect.end(); // Change the visibility of the tabBar if the desired state // is different than the current state if (tabBar && showingTabBar != tabBar.visible) { // The animateTabBarVisibility flag is set to true if the // hideTabBar() or showTabBar() methods are called with the // animate flag set to true if (!disableNextControlAnimation && transitionsEnabled && animateTabBarVisbility) { tabBarProps = {target:tabBar, showing:showingTabBar}; tabBarVisibilityEffect = showingTabBar ? createTabBarShowEffect() : createTabBarHideEffect(); tabBarVisibilityEffect.addEventListener(EffectEvent.EFFECT_END, visibilityAnimation_effectEndHandler); tabBarVisibilityEffect.play(); } else { // Since the visibility is not being animated, toggle the state tabBar.visible = tabBar.includeInLayout = showingTabBar; if (activeView) activeView.setTabBarVisible(showingTabBar); } } tabBarVisibilityChanged = false; } /** * Creates the effect to play when the TabBar control is shown. * The produced effect is responsible for animating both the * TabBar and the content group of the navigator. * *

TabbedViewNavigator will expect the includeInLayout * and visible properties of the TabBar to be true * after this effect is run.

* * @return An effect to play when the TabBar control appears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarShowEffect():IEffect { return createTabBarVisibilityEffect(true); } /** * Creates the effect to play when the TabBar control is hidden. * The produced effect is responsible for animating both the * TabBar and the content group of the navigator. * *

TabbedViewNavigator expects the includeInLayout * and visible properties of the TabBar to be false * after this effect runs.

* * @return An effect to play when the TabBar control is hidden. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarHideEffect():IEffect { return createTabBarVisibilityEffect(false); } /** * Creates the animation that will be played when the TabBar is * hidden. * * @return The effect ot play * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function createTabBarVisibilityEffect(showAnimation:Boolean):IEffect { var effect:IEffect; var finalEffect:Parallel = new Parallel(); // Grab initial values tabBarProps.start = captureAnimationValues(tabBar); contentGroupProps = { start:captureAnimationValues(contentGroup) }; // Update actionBar layout properties tabBar.visible = tabBar.includeInLayout = showingTabBar; // Calculate final positions. This method will force a validation prepareTabBarForAnimation(showAnimation); var animate:Animate = new Animate(); animate.target = tabBar; animate.duration = TAB_BAR_ANIMATION_DURATION; animate.motionPaths = new Vector.(); animate.motionPaths.push(new SimpleMotionPath(""y"", tabBarProps.start.y, tabBarProps.end.y)); effect = animate; finalEffect.addChild(effect); // Create content group animation animate = new Animate(); animate.target = contentGroup; animate.duration = TAB_BAR_ANIMATION_DURATION; animate.motionPaths = new Vector.(); animate.motionPaths.push(new SimpleMotionPath(""y"", contentGroupProps.start.y, contentGroupProps.end.y)); animate.motionPaths.push(new SimpleMotionPath(""height"", contentGroupProps.start.height, contentGroupProps.end.height)); contentGroup.includeInLayout = false; finalEffect.addChild(animate); finalEffect.duration = TAB_BAR_ANIMATION_DURATION; return finalEffect; } /** * @private */ private function navigator_elementAddHandler(event:ElementExistenceEvent):void { event.element.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } /** * @private */ private function navigator_elementRemoveHandler(event:ElementExistenceEvent):void { event.element.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } /** * @private * Dispatched when a property on a child navigator changed. */ private function navigator_propertyChangeHandler(event:PropertyChangeEvent):void { itemUpdated(event.target, event.property, event.oldValue, event.newValue); } /** * @private */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == tabBar) { tabBar.addEventListener(IndexChangeEvent.CHANGING, tabBar_indexChanging); tabBar.dataGroup.addEventListener(RendererExistenceEvent.RENDERER_ADD, tabBar_elementAddHandler); tabBar.dataProvider = this; tabBar.requireSelection = true; } } /** * @private */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == tabBar) { tabBar.dataGroup.removeEventListener(RendererExistenceEvent.RENDERER_ADD, tabBar_elementAddHandler); tabBar.removeEventListener(IndexChangeEvent.CHANGING, tabBar_indexChanging); tabBar.dataProvider = null; } } /** * @private */ override public function loadViewData(value:Object):void { super.loadViewData(value); var savedStacks:Vector.; var savedSelectedIndex:Number = value.selectedIndex as Number; // By the time this method is called, all skin parts should be // added to the component meaning that it is okay to directly // manipulate the child navigators. if (!isNaN(savedSelectedIndex) && savedSelectedIndex < length) selectedIndex = savedSelectedIndex; savedStacks = value.childrenStates as Vector.; if (savedStacks) { var navigator:ViewNavigatorBase; var len:Number = Math.min(savedStacks.length, length); for (var i:int = 0; i < len; i++) { navigator = getElementAt(i) as ViewNavigatorBase; navigator.loadViewData(savedStacks[i]); } } } /** * @private */ override public function saveViewData():Object { var savedData:Object = super.saveViewData(); var childrenStates:Vector. = new Vector.(); for (var i:int = 0; i < length; i++) childrenStates.push((getElementAt(i) as ViewNavigatorBase).saveViewData()); if (!savedData) savedData = {}; savedData.selectedIndex = selectedIndex; savedData.childrenStates = childrenStates; return savedData; } /** * @private * Redispatches the child navigator's COMPLETE event. */ private function navigator_viewChangeCompleteHandler(event:Event):void { if (hasEventListener(""viewChangeComplete"")) dispatchEvent(event); selectedNavigatorChangingView = false; if (tabBar) tabBar.mouseEnabled = explicitTabBarMouseEnabled; } /** * @private */ private function navigator_viewChangeStartHandler(event:Event):void { selectedNavigatorChangingView = true; // Disable mouse interaction with the tabBar if (tabBar) { explicitTabBarMouseEnabled = tabBar.mouseEnabled; tabBar.mouseEnabled = false; } } /** * @private */ private function tabBar_elementAddHandler(event:RendererExistenceEvent):void { event.target.addEventListener(MouseEvent.CLICK, tabBarRenderer_clickHandler); } /** * @private * Determines if the selection of the tab bar can change. */ private function tabBar_indexChanging(event:IndexChangeEvent):void { if (!indexCanChange(event.newIndex)) { event.preventDefault(); // Clear changing flag changingEventDispatched = false; } } /** * @private */ private function elementRemoveHandler(event:ElementExistenceEvent):void { cleanUpNavigator(event.element as ViewNavigatorBase); internalDispatchEvent(CollectionEventKind.REMOVE, event.element, event.index); // Element removed event is called before the element is removed from the // display list. So if the last navigator is about to be removed, numElements // should be 1 if (numElements == 1) selectedIndex = -1; } /** * @private */ private function elementAddHandler(event:ElementExistenceEvent):void { setupNavigator(event.element as ViewNavigatorBase); internalDispatchEvent(CollectionEventKind.ADD, event.element, event.index); // If the added element is the first view navigator, update the selection // to point to it if (numElements == 1) selectedIndex = 0; } /** * @private * Method is called when a tab is clicked by the user. The default * implementation checks if the clicked tab is currently selected, and if * so, pops the active navigator to its root view. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function tabBarRenderer_clickHandler(event:MouseEvent):void { // lastSelectedIndex is used instead of tabBar.selectedIndex // because by the time this method is called, the tabBar's // proposedSelectedIndex has changed, which causes its selectedIndex // method to return the proposed index instead of the currently // selected index. if ((event.target is IItemRenderer) && (IItemRenderer(event.target).itemIndex == lastSelectedIndex)) { if (selectedNavigator is ViewNavigator) ViewNavigator(selectedNavigator).popToFirstView(); } } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function view_propertyChangeHandler(event:PropertyChangeEvent):void { if (event.property == ""tabBarVisible"") { if (event.newValue) showTabBar(); else hideTabBar(); } else if (event.property == ""overlayControls"") { overlayControls = event.newValue; } } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function visibilityAnimation_effectEndHandler(event:EffectEvent):void { event.target.removeEventListener(EffectEvent.EFFECT_END, visibilityAnimation_effectEndHandler); tabBarVisibilityEffect = null; if (activeView) activeView.setTabBarVisible(tabBarProps.showing); // Check if the visible and cacheAsBitmap properties have been set. These are // only set if the default transitions are used. If developers create their // own animations, these properties won't be set. if (tabBarProps.start != undefined) { tabBar.visible = tabBar.includeInLayout = tabBarProps.end.visible; tabBar.cacheAsBitmap = tabBarProps.start.cacheAsBitmap; } tabBarProps = null; if (contentGroupProps) { contentGroup.includeInLayout = contentGroupProps.start.includeInLayout; contentGroup.cacheAsBitmap = contentGroupProps.start.cacheAsBitmap; // The default tab bar hide and show animation will animate the width and height // of the navigator's contentGroup. If the explicitWidth or explicitHeight properties // were NaN before the animation, they'll be set to real values by the animation. As // a result, it is necessary to restore them to NaN so that layout properly sizes these // components. if (isNaN(contentGroupProps.start.explicitHeight)) contentGroup.explicitHeight = NaN; if (isNaN(contentGroupProps.start.explicitWidth)) contentGroup.explicitWidth = NaN; if (!isNaN(contentGroupProps.start.percentWidth)) contentGroup.percentWidth = contentGroupProps.start.percentWidth; if (!isNaN(contentGroupProps.start.percentHeight)) contentGroup.percentHeight = contentGroupProps.start.percentHeight; contentGroupProps = null; } } //-------------------------------------------------------------------------- // // Methods: ISelectableList // //-------------------------------------------------------------------------- //---------------------------------- // selectedIndex //---------------------------------- /** * @private * The proposed selected index. This is a temporary variable that is * used until the selected index is committed. */ protected var _proposedSelectedIndex:int = NO_PROPOSED_SELECTION; /** * @private * The backing variable for selectedIndex. */ protected var _selectedIndex:int = NO_PROPOSED_SELECTION; [Bindable(""change"")] [Bindable(""valueCommit"")] /** * The 0-based index of the selected view navigator, or -1 if none is selected. * Setting the selectedIndex property deselects the currently selected * navigator and selects the navigator at the specified index. * *

The value is always between -1 and (navigators.length - 1). * If items at a lower index than selectedIndex are * removed from the component, the selected index is adjusted downward * accordingly.

* *

If the selected item is removed, the selected index is set to:

* *
    *
  • -1 if there are no remaining items.
  • *
  • selectedIndex - 1 if there is at least one item.
  • *
* * @default -1 * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectedIndex():int { if (_proposedSelectedIndex != NO_PROPOSED_SELECTION) return _proposedSelectedIndex; return _selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { if (!dataProviderChanged && value == selectedIndex) return; if (activeView) activeView.dispatchEvent(new Event(""_navigationChange_"")); _proposedSelectedIndex = value; selectedIndexChanged = true; invalidateProperties(); } /** * @private * This method determines the navigator can change its selected index. * This function will be called if the selection changed on the * tab bar, or if the selectedIndex property has changed. */ private function indexCanChange(proposedSelection:int):Boolean { changingEventDispatched = true; if (!canRemoveCurrentView()) return false; if (hasEventListener(IndexChangeEvent.CHANGING)) { var e:IndexChangeEvent = new IndexChangeEvent(IndexChangeEvent.CHANGING, false, true); e.oldIndex = _selectedIndex; e.newIndex = proposedSelection; if (!dispatchEvent(e)) return false; } return true; } //---------------------------------- // length //---------------------------------- /** * The number of child view navigators being managed by the * this component. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get length():int { return numElements; } /** * Add the specified view navigator to the end of the list. * Equivalent to calling addItemAt(item, length);. * * @param item The view navigator to add. * It must extend the ViewNavigatorBase class. * * @see spark.components.supportClasses.ViewNavigatorBase * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addItem(item:Object):void { addItemAt(item, length); } /** * Add the view navigator at the specified index. * Any view navigator that was after this index is moved down by one. * * @param item The view navigator to add. * It must extend the ViewNavigatorBase class. * * @param index The index at which to place the item. * * @throws RangeError If index is less than 0 or greater than the length * * @see spark.components.supportClasses.ViewNavigatorBase * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addItemAt(item:Object, index:int):void { // If the added type is not a ViewNavigatorBase, we ignore the call // TODO (chiedozi): Consider throwing an exception here if (!(item is ViewNavigatorBase)) return; if (index < 0 || index > length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } setupNavigator(ViewNavigatorBase(item)); addElementAt(ViewNavigatorBase(item), index); if (selectedIndex == NO_PROPOSED_SELECTION || numElements == 1) { selectedIndex = 0; } else if (index <= selectedIndex) { selectedIndex++; selectedIndexAdjusted = true; } } /** * Get the view navigator object at the specified index. * * @param index The index in the list from which to retrieve the item. * * @param prefetch Indicating both the direction and amount of items * to fetch during the request, should the item not be local. * * @return The navigator at the specified index, or null if there is none. * * @throws RangeError If the index < 0 or index >= length * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function getItemAt(index:int, prefetch:int = 0):Object { if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } return getElementAt(index); } /** * Return the index of the view navigator if it is in the list * of view navigators. * * @param item The view navigator object to locate. * * @return The index of the view navigator, or -1 if the item is not in the list. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function getItemIndex(item:Object):int { return getElementIndex(item as ViewNavigatorBase); } /** * Notify external components that a property on a view navigator has * been updated. * * @param item The view navigator that was updated. * * @param property A String, QName, or int * specifying the property that was updated. * * @param oldValue The old value of that property. * If property was null, this can be the old value of the item. * * @param newValue The new value of that property. * If property was null, there's no need to specify this * as the item is assumed to be the new value. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function itemUpdated(item:Object, property:Object = null, oldValue:Object = null, newValue:Object = null):void { var event:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); event.kind = PropertyChangeEventKind.UPDATE; event.source = item; event.property = property; event.oldValue = oldValue; event.newValue = newValue; internalDispatchEvent(CollectionEventKind.UPDATE, event); } /** * Remove all child view navigators from the navigator. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeAll():void { // Deactive the active navigator and its view if (selectedNavigator) selectedNavigator.setActive(false); // Remove all navigators navigators = null; } /** * Removes the specified item from this list, should it exist. * Relies on ArrayList implementation * * @param item Object reference to the item that should be removed. * @return Boolean indicating if the item was removed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Apache Flex 4.10 */ public function removeItem( item:Object ):Boolean { var element:IVisualElement = removeElement(item as ViewNavigatorBase); return element != null; } /** * Remove the view navigator at the specified index and return it. * The index of any items that were after this index are decreased by one. * * @param index The index from which to remove the item. * * @return The item that was removed. * * @throws RangeError If index < 0 or index >= length. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeItemAt(index:int):Object { if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } if (index <= selectedIndex) { selectedIndex--; selectedIndexAdjusted = true; } var removed:Object = removeElementAt(index); return removed; } /** * Add the view navigator at the specified index. * If an item was already at that index, the new item replaces it, * and it is returned. * * @param item The view navigator to place at the index. * * @param index The index at which to place the navigator. * * @return The navigator that was replaced, or null if none. * * @throws RangeError If index is less than 0 or greater than or equal to length * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setItemAt(item:Object, index:int):Object { // If the added type is not a ViewNavigatorBase, we ignore the call // TODO (chiedozi): Consider throwing an exception here if (!(item is ViewNavigator)) return null; if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } var oldItem:Object = removeElementAt(index); addElementAt(item as ViewNavigatorBase, index); // Let the navigator know that the item at the selectedIndex changed. // The commitProperties method will pick this up. if (index == selectedIndex) { selectedIndexAdjusted = true; invalidateProperties(); } if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)) { var updateInfo:PropertyChangeEvent; updateInfo = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); updateInfo.kind = PropertyChangeEventKind.UPDATE; updateInfo.oldValue = oldItem; updateInfo.newValue = item; updateInfo.property = index; internalDispatchEvent(CollectionEventKind.REPLACE, updateInfo, index); } return oldItem; } /** * Return an Array that is populated in the same order as the IList * implementation. * * @return The Array. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function toArray():Array { return contentGroup.getMXMLContent(); } /** * @private * Dispatches a collection event with the specified information. * * @param kind String indicates what the kind property of the event should be * @param item Object reference to the item that was added or removed * @param location int indicating where in the source the item was added. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function internalDispatchEvent(kind:String, item:Object = null, location:int = -1):void { if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)) { var event:CollectionEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE); event.kind = kind; event.items.push(item); event.location = location; dispatchEvent(event); } // now dispatch a complementary PropertyChangeEvent if (hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE) && (kind == CollectionEventKind.ADD || kind == CollectionEventKind.REMOVE)) { var objEvent:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); objEvent.property = location; if (kind == CollectionEventKind.ADD) objEvent.newValue = item; else objEvent.oldValue = item; dispatchEvent(objEvent); } } /** * @private * If the item is an IEventDispatcher watch it for updates. * This is called by addItemAt and when the source is initially * assigned. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function startTrackingUpdates(item:Object):void { if (item && (item is IEventDispatcher)) { IEventDispatcher(item).addEventListener( PropertyChangeEvent.PROPERTY_CHANGE, navigator_propertyChangeHandler, false, 0, true); } } /** * @private * If the item is an IEventDispatcher stop watching it for updates. * This is called by removeItemAt, removeAll, and before a new * source is assigned. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function stopTrackingUpdates(item:Object):void { if (item && item is IEventDispatcher) { IEventDispatcher(item).removeEventListener( PropertyChangeEvent.PROPERTY_CHANGE, navigator_propertyChangeHandler); } } } }",12204,True,2615.4928343605766,median "/* Weather.ino Show weather icons from open-iconic set. Plus demo for text scrolling. This example requires display height >= 64. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list #define SUN 0 #define SUN_CLOUD 1 #define CLOUD 2 #define RAIN 3 #define THUNDER 4 void drawWeatherSymbol(u8g2_uint_t x, u8g2_uint_t y, uint8_t symbol) { // fonts used: // u8g2_font_open_iconic_embedded_6x_t // u8g2_font_open_iconic_weather_6x_t // encoding values, see: https://github.com/olikraus/u8g2/wiki/fntgrpiconic switch(symbol) { case SUN: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 69); break; case SUN_CLOUD: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 65); break; case CLOUD: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 64); break; case RAIN: u8g2.setFont(u8g2_font_open_iconic_weather_6x_t); u8g2.drawGlyph(x, y, 67); break; case THUNDER: u8g2.setFont(u8g2_font_open_iconic_embedded_6x_t); u8g2.drawGlyph(x, y, 67); break; } } void drawWeather(uint8_t symbol, int degree) { drawWeatherSymbol(0, 48, symbol); u8g2.setFont(u8g2_font_logisoso32_tf); u8g2.setCursor(48+3, 42); u8g2.print(degree); u8g2.print(""°C""); // requires enableUTF8Print() } /* Draw a string with specified pixel offset. The offset can be negative. Limitation: The monochrome font with 8 pixel per glyph */ void drawScrollString(int16_t offset, const char *s) { static char buf[36]; // should for screen with up to 256 pixel width size_t len; size_t char_offset = 0; u8g2_uint_t dx = 0; size_t visible = 0; len = strlen(s); if ( offset < 0 ) { char_offset = (-offset)/8; dx = offset + char_offset*8; if ( char_offset >= u8g2.getDisplayWidth()/8 ) return; visible = u8g2.getDisplayWidth()/8-char_offset+1; strncpy(buf, s, visible); buf[visible] = '\\0'; u8g2.setFont(u8g2_font_8x13_mf); u8g2.drawStr(char_offset*8-dx, 62, buf); } else { char_offset = offset / 8; if ( char_offset >= len ) return; // nothing visible dx = offset - char_offset*8; visible = len - char_offset; if ( visible > u8g2.getDisplayWidth()/8+1 ) visible = u8g2.getDisplayWidth()/8+1; strncpy(buf, s+char_offset, visible); buf[visible] = '\\0'; u8g2.setFont(u8g2_font_8x13_mf); u8g2.drawStr(-dx, 62, buf); } } void draw(const char *s, uint8_t symbol, int degree) { int16_t offset = -(int16_t)u8g2.getDisplayWidth(); int16_t len = strlen(s); for(;;) { u8g2.firstPage(); do { drawWeather(symbol, degree); drawScrollString(offset, s); } while ( u8g2.nextPage() ); delay(20); offset+=2; if ( offset > len*8+1 ) break; } } void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); u8g2.enableUTF8Print(); } void loop(void) { draw(""What a beautiful day!"", SUN, 27); draw(""The sun's come out!"", SUN_CLOUD, 19); draw(""It's raining cats and dogs."", RAIN, 8); draw(""That sounds like thunder."", THUNDER, 12); draw(""It's stopped raining"", CLOUD, 15); } ",16249,True,4596.194988653357,median "/* GraphicsTest.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8glib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 16); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display // End of constructor list void u8g2_prepare(void) { u8g2.setFont(u8g2_font_6x10_tf); u8g2.setFontRefHeightExtendedText(); u8g2.setDrawColor(1); u8g2.setFontPosTop(); u8g2.setFontDirection(0); } void u8g2_box_title(uint8_t a) { u8g2.drawStr( 10+a*2, 5, ""U8g2""); u8g2.drawStr( 10, 20, ""GraphicsTest""); u8g2.drawFrame(0,0,u8g2.getDisplayWidth(),u8g2.getDisplayHeight() ); } void u8g2_box_frame(uint8_t a) { u8g2.drawStr( 0, 0, ""drawBox""); u8g2.drawBox(5,10,20,10); u8g2.drawBox(10+a,15,30,7); u8g2.drawStr( 0, 30, ""drawFrame""); u8g2.drawFrame(5,10+30,20,10); u8g2.drawFrame(10+a,15+30,30,7); } void u8g2_disc_circle(uint8_t a) { u8g2.drawStr( 0, 0, ""drawDisc""); u8g2.drawDisc(10,18,9); u8g2.drawDisc(24+a,16,7); u8g2.drawStr( 0, 30, ""drawCircle""); u8g2.drawCircle(10,18+30,9); u8g2.drawCircle(24+a,16+30,7); } void u8g2_r_frame(uint8_t a) { u8g2.drawStr( 0, 0, ""drawRFrame/Box""); u8g2.drawRFrame(5, 10,40,30, a+1); u8g2.drawRBox(50, 10,25,40, a+1); } void u8g2_string(uint8_t a) { u8g2.setFontDirection(0); u8g2.drawStr(30+a,31, "" 0""); u8g2.setFontDirection(1); u8g2.drawStr(30,31+a, "" 90""); u8g2.setFontDirection(2); u8g2.drawStr(30-a,31, "" 180""); u8g2.setFontDirection(3); u8g2.drawStr(30,31-a, "" 270""); } void u8g2_line(uint8_t a) { u8g2.drawStr( 0, 0, ""drawLine""); u8g2.drawLine(7+a, 10, 40, 55); u8g2.drawLine(7+a*2, 10, 60, 55); u8g2.drawLine(7+a*3, 10, 80, 55); u8g2.drawLine(7+a*4, 10, 100, 55); } void u8g2_triangle(uint8_t a) { uint16_t offset = a; u8g2.drawStr( 0, 0, ""drawTriangle""); u8g2.drawTriangle(14,7, 45,30, 10,40); u8g2.drawTriangle(14+offset,7-offset, 45+offset,30-offset, 57+offset,10-offset); u8g2.drawTriangle(57+offset*2,10, 45+offset*2,30, 86+offset*2,53); u8g2.drawTriangle(10+offset,40+offset, 45+offset,30+offset, 86+offset,53+offset); } void u8g2_ascii_1() { char s[2] = "" ""; uint8_t x, y; u8g2.drawStr( 0, 0, ""ASCII page 1""); for( y = 0; y < 6; y++ ) { for( x = 0; x < 16; x++ ) { s[0] = y*16 + x + 32; u8g2.drawStr(x*7, y*10+10, s); } } } void u8g2_ascii_2() { char s[2] = "" ""; uint8_t x, y; u8g2.drawStr( 0, 0, ""ASCII page 2""); for( y = 0; y < 6; y++ ) { for( x = 0; x < 16; x++ ) { s[0] = y*16 + x + 160; u8g2.drawStr(x*7, y*10+10, s); } } } void u8g2_extra_page(uint8_t a) { u8g2.drawStr( 0, 0, ""Unicode""); u8g2.setFont(u8g2_font_unifont_t_symbols); u8g2.setFontPosTop(); u8g2.drawUTF8(0, 24, ""☀ ☁""); switch(a) { case 0: case 1: case 2: case 3: u8g2.drawUTF8(a*3, 36, ""☂""); break; case 4: case 5: case 6: case 7: u8g2.drawUTF8(a*3, 36, ""☔""); break; } } void u8g2_xor(uint8_t a) { uint8_t i; u8g2.drawStr( 0, 0, ""XOR""); u8g2.setFontMode(1); u8g2.setDrawColor(2); for( i = 0; i < 5; i++) { u8g2.drawBox(10+i*16, 18 + (i&1)*4, 21,31); } u8g2.drawStr( 5+a, 19, ""XOR XOR XOR XOR""); u8g2.setDrawColor(0); u8g2.drawStr( 5+a, 29, ""CLR CLR CLR CLR""); u8g2.setDrawColor(1); u8g2.drawStr( 5+a, 39, ""SET SET SET SET""); u8g2.setFontMode(0); } #define cross_width 24 #define cross_height 24 static const unsigned char cross_bits[] U8X8_PROGMEM = { 0x00, 0x18, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0xC0, 0x00, 0x03, 0x38, 0x3C, 0x1C, 0x06, 0x42, 0x60, 0x01, 0x42, 0x80, 0x01, 0x42, 0x80, 0x06, 0x42, 0x60, 0x38, 0x3C, 0x1C, 0xC0, 0x00, 0x03, 0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x18, 0x00, }; #define cross_fill_width 24 #define cross_fill_height 24 static const unsigned char cross_fill_bits[] U8X8_PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x64, 0x00, 0x26, 0x84, 0x00, 0x21, 0x08, 0x81, 0x10, 0x08, 0x42, 0x10, 0x10, 0x3C, 0x08, 0x20, 0x00, 0x04, 0x40, 0x00, 0x02, 0x80, 0x00, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x00, 0x01, 0x40, 0x00, 0x02, 0x20, 0x00, 0x04, 0x10, 0x3C, 0x08, 0x08, 0x42, 0x10, 0x08, 0x81, 0x10, 0x84, 0x00, 0x21, 0x64, 0x00, 0x26, 0x18, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; #define cross_block_width 14 #define cross_block_height 14 static const unsigned char cross_block_bits[] U8X8_PROGMEM = { 0xFF, 0x3F, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0xC1, 0x20, 0xC1, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0xFF, 0x3F, }; void u8g2_bitmap_overlay(uint8_t a) { uint8_t frame_size = 28; u8g2.drawStr(0, 0, ""Bitmap overlay""); u8g2.drawStr(0, frame_size + 12, ""Solid / transparent""); u8g2.setBitmapMode(false /* solid */); u8g2.drawFrame(0, 10, frame_size, frame_size); u8g2.drawXBMP(2, 12, cross_width, cross_height, cross_bits); if(a & 4) u8g2.drawXBMP(7, 17, cross_block_width, cross_block_height, cross_block_bits); u8g2.setBitmapMode(true /* transparent*/); u8g2.drawFrame(frame_size + 5, 10, frame_size, frame_size); u8g2.drawXBMP(frame_size + 7, 12, cross_width, cross_height, cross_bits); if(a & 4) u8g2.drawXBMP(frame_size + 12, 17, cross_block_width, cross_block_height, cross_block_bits); } void u8g2_bitmap_modes(uint8_t transparent) { const uint8_t frame_size = 24; u8g2.drawBox(0, frame_size * 0.5, frame_size * 5, frame_size); u8g2.drawStr(frame_size * 0.5, 50, ""Black""); u8g2.drawStr(frame_size * 2, 50, ""White""); u8g2.drawStr(frame_size * 3.5, 50, ""XOR""); if(!transparent) { u8g2.setBitmapMode(false /* solid */); u8g2.drawStr(0, 0, ""Solid bitmap""); } else { u8g2.setBitmapMode(true /* transparent*/); u8g2.drawStr(0, 0, ""Transparent bitmap""); } u8g2.setDrawColor(0);// Black u8g2.drawXBMP(frame_size * 0.5, 24, cross_width, cross_height, cross_bits); u8g2.setDrawColor(1); // White u8g2.drawXBMP(frame_size * 2, 24, cross_width, cross_height, cross_bits); u8g2.setDrawColor(2); // XOR u8g2.drawXBMP(frame_size * 3.5, 24, cross_width, cross_height, cross_bits); } uint8_t draw_state = 0; void draw(void) { u8g2_prepare(); switch(draw_state >> 3) { case 0: u8g2_box_title(draw_state&7); break; case 1: u8g2_box_frame(draw_state&7); break; case 2: u8g2_disc_circle(draw_state&7); break; case 3: u8g2_r_frame(draw_state&7); break; case 4: u8g2_string(draw_state&7); break; case 5: u8g2_line(draw_state&7); break; case 6: u8g2_triangle(draw_state&7); break; case 7: u8g2_ascii_1(); break; case 8: u8g2_ascii_2(); break; case 9: u8g2_extra_page(draw_state&7); break; case 10: u8g2_xor(draw_state&7); break; case 11: u8g2_bitmap_modes(0); break; case 12: u8g2_bitmap_modes(1); break; case 13: u8g2_bitmap_overlay(draw_state&7); break; } } void setup(void) { /* U8g2 Project: SSD1306 Test Board */ pinMode(10, OUTPUT); pinMode(9, OUTPUT); digitalWrite(10, 0); digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); u8g2.begin(); //u8g2.setFlipMode(0); } void loop(void) { // picture loop u8g2.firstPage(); do { draw(); } while( u8g2.nextPage() ); // increase the state draw_state++; if ( draw_state >= 14*8 ) draw_state = 0; // delay between each page delay(150); } ",16141,True,3570.476460758194,median "/* IconMenu.ino This is an interactive demo and requires ""next"", ""prev"" and ""select"" button. Minimum height of the display should be 64. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Frame Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_F_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1322_NHD_256X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_MIDAS_128X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_F_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_F_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_F u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_F u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_F_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_F_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_F_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LC7981_160X80_F_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_F_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_F_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_F_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_F u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FG with GND //U8G2_SED1330_240X128_F_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // A0 is dc pin! //U8G2_RA8835_NHD_240X128_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_F_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1604_JLX19264_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_F_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Due, SW SPI, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_F_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Due, SW SPI, DOGXL240 Test Board //U8G2_UC1611_EW50850_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1638_160X128_F_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_MAX7219_64X8_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); //U8G2_MAX7219_32X8_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); //U8G2_MAX7219_8X8_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); //U8G2_LS013B7DH03_128X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_F_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { // DOGS102 Shield (http://shieldlist.org/controlconnection/dogs102) // u8g2.begin(/* menu_select_pin= */ 5, /* menu_next_pin= */ 4, /* menu_prev_pin= */ 2, /* menu_home_pin= */ 3); // DOGM128 Shield (http://shieldlist.org/schmelle2/dogm128) + DOGXL160 Shield u8g2.begin(/* menu_select_pin= */ 2, /* menu_next_pin= */ 3, /* menu_prev_pin= */ 7, /* menu_home_pin= */ 8); // MKR Zero Test Board u8g2.begin(/*Select=*/ 0, /*Right/Next=*/ 1, /*Left/Prev=*/ 2, /*Up=*/ 4, /*Down=*/ 3, /*Home/Cancel=*/ A6); // Arduboy //u8g2.begin(/*Select=*/ A0, /*Right/Next=*/ 5, /*Left/Prev=*/ 9, /*Up=*/ 8, /*Down=*/ 10, /*Home/Cancel=*/ A1); // Arduboy DevKit //u8g2.begin(/*Select=*/ 7, /*Right/Next=*/ A1, /*Left/Prev=*/ A2, /*Up=*/ A0, /*Down=*/ A3, /*Home/Cancel=*/ 8); // Arduboy 10 (Production) u8g2.setFont(u8g2_font_6x12_tr); } struct menu_entry_type { const uint8_t *font; uint16_t icon; const char *name; }; struct menu_state { int16_t menu_start; /* in pixel */ int16_t frame_position; /* in pixel */ uint8_t position; /* position, array index */ }; /* Icon configuration Width and height must match the icon font size GAP: Space between the icons BGAP: Gap between the display border and the cursor. */ #define ICON_WIDTH 32 #define ICON_HEIGHT 32 #define ICON_GAP 4 #define ICON_BGAP 16 #define ICON_Y 32+ ICON_GAP struct menu_entry_type menu_entry_list[] = { { u8g2_font_open_iconic_embedded_4x_t, 65, ""Clock Setup""}, { u8g2_font_open_iconic_embedded_4x_t, 66, ""Gear Game""}, { u8g2_font_open_iconic_embedded_4x_t, 67, ""Flash Light""}, { u8g2_font_open_iconic_embedded_4x_t, 68, ""Home""}, { u8g2_font_open_iconic_embedded_4x_t, 72, ""Configuration""}, { NULL, 0, NULL } }; int8_t button_event = 0; // set this to 0, once the event has been processed void check_button_event(void) { if ( button_event == 0 ) button_event = u8g2.getMenuEvent(); } void draw(struct menu_state *state) { int16_t x; uint8_t i; x = state->menu_start; i = 0; while( menu_entry_list[i].icon > 0 ) { if ( x >= -ICON_WIDTH && x < u8g2.getDisplayWidth() ) { u8g2.setFont(menu_entry_list[i].font); u8g2.drawGlyph(x, ICON_Y, menu_entry_list[i].icon ); } i++; x += ICON_WIDTH + ICON_GAP; check_button_event(); } u8g2.drawFrame(state->frame_position-1, ICON_Y-ICON_HEIGHT-1, ICON_WIDTH+2, ICON_WIDTH+2); u8g2.drawFrame(state->frame_position-2, ICON_Y-ICON_HEIGHT-2, ICON_WIDTH+4, ICON_WIDTH+4); u8g2.drawFrame(state->frame_position-3, ICON_Y-ICON_HEIGHT-3, ICON_WIDTH+6, ICON_WIDTH+6); check_button_event(); } void to_right(struct menu_state *state) { if ( menu_entry_list[state->position+1].font != NULL ) { if ( (int16_t)state->frame_position+ 2*(int16_t)ICON_WIDTH + (int16_t)ICON_BGAP < (int16_t)u8g2.getDisplayWidth() ) { state->position++; state->frame_position += ICON_WIDTH + (int16_t)ICON_GAP; } else { state->position++; state->frame_position = (int16_t)u8g2.getDisplayWidth() - (int16_t)ICON_WIDTH - (int16_t)ICON_BGAP; state->menu_start = state->frame_position - state->position*((int16_t)ICON_WIDTH + (int16_t)ICON_GAP); } } } void to_left(struct menu_state *state) { if ( state->position > 0 ) { if ( (int16_t)state->frame_position >= (int16_t)ICON_BGAP+(int16_t)ICON_WIDTH+ (int16_t)ICON_GAP ) { state->position--; state->frame_position -= ICON_WIDTH + (int16_t)ICON_GAP; } else { state->position--; state->frame_position = ICON_BGAP; state->menu_start = state->frame_position - state->position*((int16_t)ICON_WIDTH + (int16_t)ICON_GAP); } } } uint8_t towards_int16(int16_t *current, int16_t dest) { if ( *current < dest ) { (*current)++; return 1; } else if ( *current > dest ) { (*current)--; return 1; } return 0; } uint8_t towards(struct menu_state *current, struct menu_state *destination) { uint8_t r = 0; uint8_t i; for( i = 0; i < 6; i++ ) { r |= towards_int16( &(current->frame_position), destination->frame_position); r |= towards_int16( &(current->menu_start), destination->menu_start); } return r; } struct menu_state current_state = { ICON_BGAP, ICON_BGAP, 0 }; struct menu_state destination_state = { ICON_BGAP, ICON_BGAP, 0 }; void loop(void) { do { u8g2.firstPage(); do { draw(¤t_state); u8g2.setFont(u8g2_font_helvB10_tr); u8g2.setCursor((u8g2.getDisplayWidth()-u8g2.getStrWidth(menu_entry_list[destination_state.position].name))/2,u8g2.getDisplayHeight()-5); u8g2.print(menu_entry_list[destination_state.position].name); check_button_event(); delay(10); } while( u8g2.nextPage() ); if ( button_event == U8X8_MSG_GPIO_MENU_NEXT ) to_right(&destination_state); if ( button_event == U8X8_MSG_GPIO_MENU_PREV ) to_left(&destination_state); if ( button_event == U8X8_MSG_GPIO_MENU_SELECT ) { u8g2.setFont(u8g2_font_helvB10_tr); u8g2.userInterfaceMessage(""Selection:"", menu_entry_list[destination_state.position].name, """", "" Ok ""); } if ( button_event > 0 ) // all known events are processed, clear event button_event = 0; } while ( towards(¤t_state, &destination_state) ); } ",16316,True,4318.217092038876,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.components { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import mx.core.DPIClassification; import mx.core.FlexGlobals; import mx.core.ILayoutElement; import mx.core.IVisualElement; import mx.core.LayoutDirection; import mx.core.UIComponent; import mx.core.mx_internal; import mx.events.ResizeEvent; import mx.managers.SystemManager; import mx.utils.MatrixUtil; import mx.utils.PopUpUtil; use namespace mx_internal; //-------------------------------------- // Styles //-------------------------------------- /** * Appearance of the contentGroup. * Valid MXML values are inset, * flat, and none. * *

In ActionScript, you can use the following constants * to set this property: * ContentBackgroundAppearance.INSET, * ContentBackgroundAppearance.FLAT and * ContentBackgroundAppearance.NONE.

* * @default ContentBackgroundAppearance.INSET * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ [Style(name=""contentBackgroundAppearance"", type=""String"", enumeration=""inset,flat,none"", inherit=""no"")] /** * Color of the frame border and arrow outline of the Callout control. * @default 0 * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3.8 * @productversion Flex 4.11 */ [Style(name=""borderColor"", type=""uint"", format=""Color"", inherit=""no"", theme=""spark, mobile"")] /** * Thickness of the border stroke around the backgroundColor Callout ""frame"" and arrow. * Set to NaN or 0 to hide the border ; * * @default NaN * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3.8 * @productversion Flex 4.11 */ [Style(name=""borderThickness"", type=""Number"", format=""Length"", inherit=""no"", theme=""spark,mobile"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""Callout.png"")] /** * The Callout container is a SkinnablePopUpContainer that functions as a pop-up * with additional owner-relative positioning options similar to PopUpAnchor. * Callout also adds an optional arrow skin part that visually * displays the direction toward the owner. * * *

You can also use the CalloutButton control to open a callout container. * The CalloutButton control encapsulates in a single control the callout container * and all of the logic necessary to open and close the callout. * The CalloutButton control is then said to the be the owner, or host, * of the callout.

* *

Callout uses the horizontalPosition and * verticalPosition properties to determine the position of the * Callout relative to the owner that is specified by the open() * method. * Both properties can be set to CalloutPosition.AUTO which selects a * position based on the aspect ratio of the screen for the Callout to fit * with minimal overlap with the owner and and minimal adjustments at the * screen bounds.

* *

Once positioned, the Callout positions the arrow on the side adjacent * to the owner, centered as close as possible on the horizontal or vertical * center of the owner as appropriate. The arrow is hidden in cases where * the Callout position is not adjacent to any edge.

* *

You do not create a Callout container as part of the normal layout * of its parent container. * Instead, it appears as a pop-up container on top of its parent. * Therefore, you do not create it directly in the MXML code of your application.

* *

Instead, you create is as an MXML component, often in a separate MXML file. * To show the component create an instance of the MXML component, and * then call the open() method. * You can also set the size and position of the component when you open it.

* *

To close the component, call the close() method. * If the pop-up needs to return data to a handler, you can add an event listener for * the PopUp.CLOSE event, and specify the returned data in * the close() method.

* *

The Callout is initially in its closed skin state. * When it opens, it adds itself as a pop-up to the PopUpManager, * and transition to the normal skin state. * To define open and close animations, use a custom skin with transitions between * the closed and normal skin states.

* *

Callout changes the default inheritance behavior seen in Flex components * and instead, inherits styles from the top-level application. This prevents * Callout's contents from unintentionally inheriting styles from an owner * (i.e. Button or TextInput) where the default appearance was desired and * expected.

* *

The Callout container has the following default characteristics:

* * * * * * * *
CharacteristicDescription
Default sizeLarge enough to display its children
Minimum size0 pixels
Maximum size10000 pixels wide and 10000 pixels high
Default skin classspark.skins.mobile.CalloutSkin
* spark.skins.spark.CalloutSkin on desktops
* * @mxml

The <s:Callout> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:

* *
 *  <s:Callout
 *    Properties
 *    horizontalPosition=""auto""
 *    verticalPosition=""auto""
 *
 *    Styles
 *    contentBackgroundAppearance=""inset""
 *  />
 *  
* * @see spark.components.CalloutButton * @see spark.skins.mobile.CalloutSkin * @see spark.components.ContentBackgroundAppearance * @see spark.components.CalloutPosition * * @includeExample examples/CalloutExample.mxml -noswf * * @langversion 3.0 * @playerversion Flash 11 * * @playerversion AIR 3 * @productversion Flex 4.6 */ public class Callout extends SkinnablePopUpContainer { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- private static var decomposition:Vector. = new [0,0,0,0,0]; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public function Callout() { super(); } //-------------------------------------------------------------------------- // // Skin parts // //-------------------------------------------------------------------------- [Bindable] [SkinPart(required=""false"")] /** * An optional skin part that visually connects the owner to the * contentGroup. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public var arrow:UIComponent; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var invalidatePositionFlag:Boolean = false; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // horizontalPosition //---------------------------------- private var _horizontalPosition:String = CalloutPosition.AUTO; [Inspectable(category=""General"", enumeration=""before,start,middle,end,after,auto"", defaultValue=""auto"")] /** * Horizontal position of the callout relative to the owner. * *

Possible values are ""before"", ""start"", * ""middle"", ""end"", ""after"", * and ""auto"" (default).

* * @default CalloutPosition.AUTO * @see spark.components.CalloutPosition * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public function get horizontalPosition():String { return _horizontalPosition; } /** * @private */ public function set horizontalPosition(value:String):void { if (value == _horizontalPosition) return; _horizontalPosition = value; invalidatePosition(); } //---------------------------------- // actualHorizontalPosition //---------------------------------- private var _actualHorizontalPosition:String; /** * Fully resolved horizontal position after evaluating CalloutPosition.AUTO. * *

Update this property in commitProperties() when the * explicit horizontalPosition is CalloutPosition.AUTO. * This property must be updated in updatePopUpPosition() * when attempting to reposition the Callout.

* *

Subclasses should read this property when computing the arrowDirection, * the arrow position in updateSkinDisplayList().

* * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ mx_internal function get actualHorizontalPosition():String { if (_actualHorizontalPosition) return _actualHorizontalPosition; return horizontalPosition; } /** * @private */ mx_internal function set actualHorizontalPosition(value:String):void { _actualHorizontalPosition = value; } //---------------------------------- // verticalPosition //---------------------------------- private var _verticalPosition:String = CalloutPosition.AUTO; [Inspectable(category=""General"", enumeration=""before,start,middle,end,after,auto"", defaultValue=""auto"")] /** * Vertical position of the callout relative to the owner. * *

Possible values are ""before"", ""start"", * ""middle"", ""end"", ""after"", * and ""auto"" (default).

* * @default CalloutPosition.AUTO * @see spark.components.CalloutPosition * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public function get verticalPosition():String { return _verticalPosition; } /** * @private */ public function set verticalPosition(value:String):void { if (value == _verticalPosition) return; _verticalPosition = value; invalidatePosition(); } //---------------------------------- // actualVerticalPosition //---------------------------------- private var _actualVerticalPosition:String; /** * Fully resolved vertical position after evaluating CalloutPosition.AUTO. * *

Update this property in commitProperties() when the * explicit verticalPosition is CalloutPosition.AUTO. * This property must be updated in updatePopUpPosition() * when attempting to reposition the Callout.

* *

Subclasses should read this property when computing the arrowDirection, * the arrow position in updateSkinDisplayList().

* * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ mx_internal function get actualVerticalPosition():String { if (_actualVerticalPosition) return _actualVerticalPosition; return verticalPosition; } /** * @private */ mx_internal function set actualVerticalPosition(value:String):void { _actualVerticalPosition = value; } //---------------------------------- // arrowDirection //---------------------------------- private var _arrowDirection:String = ArrowDirection.NONE; /** * @private * Indicates if arrow direction was flipped automatically. */ private var arrowDirectionAdjusted:Boolean = false; /** * A read-only property that indicates the direction from the callout * towards the owner. * *

This value is computed based on the callout position given by * horizontalPosition and verticalPosition. * Exterior and interior positions will point from the callout towards * the edge of the owner. Corner and absolute center positions are not * supported and will return a value of ""none"".

* * @default none * * @see spark.components.ArrowDirection * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public function get arrowDirection():String { return _arrowDirection; } /** * @private * Invalidate skin when the arrowDirection changes. Dispatches an * ""arrowDirectionChanged"" event when the property is set. */ mx_internal function setArrowDirection(value:String):void { if (_arrowDirection == value) return; _arrowDirection = value; // Instead of using skin states for each arrowDirection, the // skin must override commitProperties() and account for // arrowDirection on it's own. skin.invalidateProperties(); // adjust margins based on arrow direction switch (arrowDirection) { case ArrowDirection.DOWN: { // Set the marginBottom to zero to place the arrow adjacent to the keyboard softKeyboardEffectMarginBottom = 0; softKeyboardEffectMarginTop = margin; break; } case ArrowDirection.UP: { // Arrow should already be adjacent to the owner or the top of // the screen. softKeyboardEffectMarginTop = 0; softKeyboardEffectMarginBottom = margin; break; } default: { softKeyboardEffectMarginBottom = margin; softKeyboardEffectMarginTop = margin; break; } } if (hasEventListener(""arrowDirectionChanged"")) dispatchEvent(new Event(""arrowDirectionChanged"")); } //---------------------------------- // margin //---------------------------------- private var _margin:Number = NaN; /** * @private * Defines a margin around the Callout to nudge it's position away from the * edge of the screen. */ mx_internal function get margin():Number { if (isNaN(_margin)) { var dpi:Number; if(FlexGlobals.topLevelApplication.hasOwnProperty(""applicationDPI"")) { dpi = FlexGlobals.topLevelApplication[""applicationDPI""]; } if (dpi) { switch (dpi) { case DPIClassification.DPI_640: { _margin = 32; break; } case DPIClassification.DPI_480: { _margin = 24; break; } case DPIClassification.DPI_320: { _margin = 16; break; } case DPIClassification.DPI_240: { _margin = 12; break; } case DPIClassification.DPI_120: { _margin = 6; break; } default: { // default DPI_160 _margin = 8; break; } } } else { _margin = 8; } } return _margin; } private var _explicitMoveForSoftKeyboard:Boolean = false; /** * @private */ override public function get moveForSoftKeyboard():Boolean { // If no explicit setting, then automatically disable move when // pointing up towards the owner. if (!_explicitMoveForSoftKeyboard && (arrowDirection == ArrowDirection.UP)) { return false; } return super.moveForSoftKeyboard; } /** * @private */ override public function set moveForSoftKeyboard(value:Boolean):void { super.moveForSoftKeyboard = value; _explicitMoveForSoftKeyboard = true; } //---------------------------------- // calloutMaxWidth //---------------------------------- private var _calloutMaxWidth:Number = NaN; /** * @private */ mx_internal function get calloutMaxWidth():Number { return _calloutMaxWidth; } /** * @private */ mx_internal function set calloutMaxWidth(value:Number):void { if (_calloutMaxWidth == value) return; _calloutMaxWidth = value; invalidateMaxSize(); } //---------------------------------- // calloutMaxHeight //---------------------------------- private var _calloutMaxHeight:Number = NaN; /** * @private */ mx_internal function get calloutMaxHeight():Number { return _calloutMaxHeight; } /** * @private */ mx_internal function set calloutMaxHeight(value:Number):void { if (_calloutMaxHeight == value) return; _calloutMaxHeight = value; invalidateMaxSize(); } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override public function get explicitMaxWidth():Number { if (!isNaN(super.explicitMaxWidth)) return super.explicitMaxWidth; return calloutMaxWidth; } /** * @private */ override public function get explicitMaxHeight():Number { if (!isNaN(super.explicitMaxHeight)) return super.explicitMaxHeight; return calloutMaxHeight; } /** * @private */ override protected function commitProperties():void { super.commitProperties(); // Do not commit position changes if closed (no owner) or owner was // removed from the display list. if (!owner || !owner.parent) return; // Compute actual positions when using AUTO commitAutoPosition(); // Compute max size based on actual positions commitMaxSize(); if (arrow) { // arrowDirection can be set in 2 ways: (1) horizontalPostion/verticalPosition // changes and (2) flipping the axis to fit on screen. if (!arrowDirectionAdjusted) { // Invalidate only when the arrow direction changes var direction:String = determineArrowPosition(actualHorizontalPosition, actualVerticalPosition); if (arrowDirection != direction) { setArrowDirection(direction); if (arrow) arrow.visible = (arrowDirection != ArrowDirection.NONE); } } // Always reset the arrow position invalidateDisplayList(); } } /** * @private * Re-position the pop-up using actualHorizontalPosition and * actualVerticalPosition. */ override public function updatePopUpPosition():void { if (!owner || !systemManager) return; var popUpPoint:Point = calculatePopUpPosition(); var ownerComponent:UIComponent = owner as UIComponent; var concatenatedColorTransform:ColorTransform = (ownerComponent) ? ownerComponent.$transform.concatenatedColorTransform : null; PopUpUtil.applyPopUpTransform(owner, concatenatedColorTransform, systemManager, this, popUpPoint); } /** * @private * * Cooperative layout * @see spark.components.supportClasses.TrackBase#partAdded */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == arrow) arrow.addEventListener(ResizeEvent.RESIZE, arrow_resizeHandler); } /** * @private */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == arrow) arrow.removeEventListener(ResizeEvent.RESIZE, arrow_resizeHandler); } /** * @private */ override public function open(owner:DisplayObjectContainer, modal:Boolean=false):void { if (isOpen) return; // reset state invalidatePositionFlag = false; arrowDirectionAdjusted = false; // Add to PopUpManager, calls updatePopUpPosition(), and change state super.open(owner, modal); // Reposition the callout when the screen changes var systemManagerParent:SystemManager = this.parent as SystemManager; if (systemManagerParent) systemManagerParent.addEventListener(Event.RESIZE, systemManager_resizeHandler); } /** * @private */ override public function close(commit:Boolean=false, data:*=null):void { if (!isOpen) return; var systemManagerParent:SystemManager = this.parent as SystemManager; if (systemManagerParent) systemManagerParent.removeEventListener(Event.RESIZE, systemManager_resizeHandler); super.close(commit, data); } /** * @private */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); // Callout can be respositioned while open via SystemManager resize or // explicit changes to horizontalPostion and verticalPosition. if (isOpen && invalidatePositionFlag) { updatePopUpPosition(); invalidatePositionFlag = false; } // Position the arrow updateSkinDisplayList(); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private */ private function invalidatePosition():void { arrowDirectionAdjusted = false; invalidateProperties(); if (isOpen) invalidatePositionFlag = true; } /** * @private * Force a new measurement when callout should use it's screen-constrained * max size. */ private function invalidateMaxSize():void { // calloutMaxWidth and calloutMaxHeight don't invalidate // explicitMaxWidth or explicitMaxHeight. If callout's max size changes // and explicit max sizes aren't set, then invalidate size here so that // callout's max size is applied. if (!canSkipMeasurement() && !isMaxSizeSet) skin.invalidateSize(); } /** * Sets the bounds of arrow, whose geometry isn't fully * specified by the skin's layout. * *

Subclasses can override this method to update the arrow's size, * position, and visibility, based on the computed * arrowDirection.

* *

By default, this method aligns the arrow on the shorter of either * the arrow bounds or the owner bounds. This * implementation assumes that the arrow and the Callout skin * share the same coordinate space.

* * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected function updateSkinDisplayList():void { var ownerVisualElement:IVisualElement = owner as IVisualElement; // Sanity check to verify owner is still on the display list. If not, // leave the arrow in the current position. if (!arrow || !ownerVisualElement || (arrowDirection == ArrowDirection.NONE) || (!ownerVisualElement.parent)) return; var isStartPosition:Boolean = false; var isMiddlePosition:Boolean = false; var isEndPosition:Boolean = false; var position:String = (isArrowVertical) ? actualHorizontalPosition : actualVerticalPosition; isStartPosition = (position == CalloutPosition.START); isMiddlePosition = (position == CalloutPosition.MIDDLE); isEndPosition = (position == CalloutPosition.END); var isEndOfCallout:Boolean = (arrowDirection == ArrowDirection.DOWN) || (arrowDirection == ArrowDirection.RIGHT); var calloutWidth:Number = getLayoutBoundsWidth(); var calloutHeight:Number = getLayoutBoundsHeight(); var arrowWidth:Number = arrow.getLayoutBoundsWidth(); var arrowHeight:Number = arrow.getLayoutBoundsHeight(); // arrow X/Y in pop-up coordinates var arrowX:Number = 0; var arrowY:Number = 0; // Max arrow positions var maxArrowX:Number = calloutWidth - arrowWidth; var maxArrowY:Number = calloutHeight - arrowHeight; // Find the registration point of the owner var sandboxRoot:DisplayObject = systemManager.getSandboxRoot(); var regPoint:Point = owner.localToGlobal(new Point()); regPoint = sandboxRoot.globalToLocal(regPoint); if (isArrowVertical) { // Vertical arrows need horizontal alignment var ownerX:Number = regPoint.x; var ownerVisibleWidth:Number = (ownerVisualElement) ? ownerVisualElement.getLayoutBoundsWidth() : owner.width; // Edge cases when start/end of owner is not visible if ((ownerX < 0) && (ownerVisibleWidth < screen.width)) ownerVisibleWidth = Math.max(ownerVisibleWidth + ownerX, 0); else if ((ownerX >= 0) && ((ownerX + ownerVisibleWidth) >= screen.width)) ownerVisibleWidth = Math.max(screen.width - ownerX, 0); ownerVisibleWidth = Math.min(ownerVisibleWidth, screen.width); if (calloutWidth <= ownerVisibleWidth) { arrowX = (calloutWidth - arrowWidth) / 2; } else // if (calloutWidth > ownerWidth) { // Center the arrow on the owner arrowX = (ownerVisibleWidth - arrowWidth) / 2; // Add owner offset if (ownerX > 0) arrowX += Math.abs(ownerX - getLayoutBoundsX()); if (ownerX < margin) arrowX -= (margin - ownerX); } // arrow should not extend past the callout bounds arrowX = Math.max(Math.min(maxArrowX, arrowX), 0); // Move the arrow to the bottom of the callout if (isEndOfCallout) arrowY = calloutHeight - arrowHeight; } else { // Horizontal arrows need vertical alignment var ownerY:Number = regPoint.y; var ownerVisibleHeight:Number = (ownerVisualElement) ? ownerVisualElement.getLayoutBoundsHeight() : owner.height; // Edge cases when start/end of owner is not visible if ((ownerY < 0) && (ownerVisibleHeight < screen.height)) ownerVisibleHeight = Math.max(ownerVisibleHeight + ownerY, 0); else if ((ownerY >= 0) && ((ownerY + ownerVisibleHeight) >= screen.height)) ownerVisibleHeight = Math.max(screen.height - ownerY, 0); ownerVisibleHeight = Math.min(ownerVisibleHeight, screen.height); if (calloutHeight <= ownerVisibleHeight) { arrowY = (calloutHeight - arrowHeight) / 2; } else // if (calloutHeight > ownerHeight) { // Center the arrow on the owner arrowY = (ownerVisibleHeight - arrowHeight) / 2; // Add owner offset if (ownerY > 0) arrowY += Math.abs(ownerY - getLayoutBoundsY()); if (ownerY < margin) ownerY -= (margin - ownerY); } // arrow should not extend past the callout bounds arrowY = Math.max(Math.min(maxArrowY, arrowY), 0); // Move the arrow to the end of the callout if (isEndOfCallout) arrowX = calloutWidth - arrowWidth; } arrow.setLayoutBoundsPosition(Math.floor(arrowX), Math.floor(arrowY)); arrow.invalidateDisplayList(); } /** * @private * * Flip or clear the adjusted position when the callout bounds are outside * the screen bounds. */ mx_internal function adjustCalloutPosition(actualPosition:String, preferredPosition:String, calloutStart:Number, calloutEnd:Number, screenStart:Number, screenEnd:Number, ownerStart:Number, ownerEnd:Number, revert:Boolean=false):String { if (!actualPosition) return null; var adjustedPosition:String = null; var calloutSize:Number = calloutEnd - calloutStart; // Exterior space var exteriorSpaceStart:Number = Math.max(0, ownerStart - screenStart); var exteriorSpaceEnd:Number = Math.max(0, ownerEnd - screenEnd); // Fallback to interior positions if using AUTO and callout can not // fit in either exterior positions var useInterior:Boolean = (preferredPosition == CalloutPosition.AUTO) && (exteriorSpaceStart < calloutSize) && (exteriorSpaceEnd < calloutSize); var isExterior:Boolean = false; // Flip to opposite position switch (actualPosition) { case CalloutPosition.BEFORE: { isExterior = true; if (calloutStart < screenStart) adjustedPosition = CalloutPosition.AFTER; break; } case CalloutPosition.AFTER: { isExterior = true; if (calloutEnd > screenEnd) adjustedPosition = CalloutPosition.BEFORE; break; } case CalloutPosition.END: { if (calloutStart < screenStart) adjustedPosition = CalloutPosition.START; break; } case CalloutPosition.START: { if (calloutEnd > screenEnd) adjustedPosition = CalloutPosition.END; break; } // case CalloutPosition.MIDDLE: // Nudge instead of flipping } // Use interior position if exterior flipping was necessary if (useInterior && adjustedPosition && isExterior) { // Choose the exterior position with the most available space. // Note that START grows towards the exterior END and vice versa. adjustedPosition = (exteriorSpaceEnd >= exteriorSpaceStart) ? CalloutPosition.START : CalloutPosition.END; } // Return null to revert the adjusted position // Otherwise, return the incoming position if (revert) return (adjustedPosition) ? null : actualPosition; // Adjusted position or null if the callout already fits return adjustedPosition; } /** * @private * * Nudge the callout position to fit on screen. Prefer top/left positions * and allow overflow to get clipped on the bottom/right. */ mx_internal function nudgeToFit(calloutStart:Number, calloutEnd:Number, screenStart:Number, screenEnd:Number, scaleFactor:Number):Number { var position:Number = 0; if (calloutStart < screenStart) position += (screenStart - calloutStart) / scaleFactor; else if (calloutEnd > screenEnd) position -= (calloutEnd - screenEnd) / scaleFactor; return position; } /** * @private * * Basically the same as PopUpAnchor, but with more position options * including exterior, interior and corner positions. * * Nudging to fit the screen accounts for margin so that * the Callout is not positioned in the margin. * * arrowDirection will change if required for the callout * to fit. * * @see #margin */ mx_internal function calculatePopUpPosition():Point { // This implementation doesn't handle rotation var sandboxRoot:DisplayObject = systemManager.getSandboxRoot(); var matrix:Matrix = MatrixUtil.getConcatenatedMatrix(owner, sandboxRoot); var regPoint:Point = new Point(); if (!matrix) return regPoint; var adjustedHorizontalPosition:String; var adjustedVerticalPosition:String; var calloutBounds:Rectangle = determinePosition(actualHorizontalPosition, actualVerticalPosition, matrix, regPoint); var ownerBounds:Rectangle = owner.getBounds(systemManager.getSandboxRoot()); // Position the callout in the opposite direction if it // does not fit on the screen. if (screen) { adjustedHorizontalPosition = adjustCalloutPosition( actualHorizontalPosition, horizontalPosition, calloutBounds.left, calloutBounds.right, screen.left, screen.right, ownerBounds.left, ownerBounds.right); adjustedVerticalPosition = adjustCalloutPosition( actualVerticalPosition, verticalPosition, calloutBounds.top, calloutBounds.bottom, screen.top, screen.bottom, ownerBounds.top, ownerBounds.bottom); } var oldArrowDirection:String = arrowDirection; var actualArrowDirection:String = null; // Reset arrowDirectionAdjusted arrowDirectionAdjusted = false; // Get the new registration point based on the adjusted position if ((adjustedHorizontalPosition != null) || (adjustedVerticalPosition != null)) { var adjustedRegPoint:Point = new Point(); var tempHorizontalPosition:String = (adjustedHorizontalPosition) ? adjustedHorizontalPosition : actualHorizontalPosition; var tempVerticalPosition:String = (adjustedVerticalPosition) ? adjustedVerticalPosition : actualVerticalPosition; // Adjust arrow direction after adjusting position actualArrowDirection = determineArrowPosition(tempHorizontalPosition, tempVerticalPosition); // All position flips gaurantee an arrowDirection change setArrowDirection(actualArrowDirection); arrowDirectionAdjusted = true; if (arrow) arrow.visible = (arrowDirection != ArrowDirection.NONE); // Reposition the arrow updateSkinDisplayList(); var adjustedBounds:Rectangle = determinePosition(tempHorizontalPosition, tempVerticalPosition, matrix, adjustedRegPoint); if (screen) { // If we adjusted the position but the callout still doesn't fit, // then revert to the original position. adjustedHorizontalPosition = adjustCalloutPosition( adjustedHorizontalPosition, horizontalPosition, adjustedBounds.left, adjustedBounds.right, screen.left, screen.right, ownerBounds.left, ownerBounds.right, true); adjustedVerticalPosition = adjustCalloutPosition( adjustedVerticalPosition, verticalPosition, adjustedBounds.top, adjustedBounds.bottom, screen.top, screen.bottom, ownerBounds.top, ownerBounds.bottom, true); } if ((adjustedHorizontalPosition != null) || (adjustedVerticalPosition != null)) { regPoint = adjustedRegPoint; calloutBounds = adjustedBounds; // Temporarily set actual positions to reposition the arrow if (adjustedHorizontalPosition) actualHorizontalPosition = adjustedHorizontalPosition; if (adjustedVerticalPosition) actualVerticalPosition = adjustedVerticalPosition; // Reposition the arrow with the new actual position updateSkinDisplayList(); } else { // Restore previous arrow direction *before* reversing the // adjusted positions setArrowDirection(oldArrowDirection); arrowDirectionAdjusted = false; // Reposition the arrow to the original position updateSkinDisplayList(); } } MatrixUtil.decomposeMatrix(decomposition, matrix, 0, 0); var concatScaleX:Number = decomposition[3]; var concatScaleY:Number = decomposition[4]; // If the callout still doesn't fit, then nudge it // so it is completely on the screen. Make sure to include scale. var screenTop:Number = screen.top; var screenBottom:Number = screen.bottom; var screenLeft:Number = screen.left; var screenRight:Number = screen.right; // Allow zero margin on the the side with the arrow switch (arrowDirection) { case ArrowDirection.UP: { screenBottom -= margin; screenLeft += margin; screenRight -= margin break; } case ArrowDirection.DOWN: { screenTop += margin; screenLeft += margin; screenRight -= margin break; } case ArrowDirection.LEFT: { screenTop += margin; screenBottom -= margin; screenRight -= margin break; } case ArrowDirection.RIGHT: { screenTop += margin; screenBottom -= margin; screenLeft += margin; break; } default: { screenTop += margin; screenBottom -= margin; screenLeft += margin; screenRight -= margin break; } } regPoint.y += nudgeToFit(calloutBounds.top, calloutBounds.bottom, screenTop, screenBottom, concatScaleY); regPoint.x += nudgeToFit(calloutBounds.left, calloutBounds.right, screenLeft, screenRight, concatScaleX); // Compute the stage coordinates of the upper,left corner of the PopUp, taking // the postTransformOffsets - which include mirroring - into account. // If we're mirroring, then the implicit assumption that x=left will fail, // so we compensate here. if (layoutDirection == LayoutDirection.RTL) regPoint.x += calloutBounds.width; return MatrixUtil.getConcatenatedComputedMatrix(owner, sandboxRoot).transformPoint(regPoint); } /** * @private * Computes actualHorizontalPosition and/or * actualVerticalPosition values when using * CalloutPosition.AUTO. When implementing subclasses of * Callout, use actualHorizontalPosition and * actualVerticalPosition to compute * arrowDirection and positioning in * updatePopUpPosition() and updateSkinDisplayList(). * *

The default implementation chooses ""outer"" positions for the callout * such that the owner is not obscured. Horizontal/Vertical orientation * relative to the owner choosen based on the aspect ratio.

* *

When the aspect ratio is landscape, and the callout can fit to the * left or right of the owner, actualHorizontalPosition is * set to CalloutPosition.BEFORE or * CalloutPosition.AFTER as appropriate. * actualVerticalPosition is set to * CalloutPosition.MIDDLE to have the vertical center of the * callout align to the vertical center of the owner.

* *

When the aspect ratio is portrait, and the callout can fit * above or below the owner, actualVerticalPosition is * set to CalloutPosition.BEFORE or * CalloutPosition.AFTER as appropriate. * actualHorizontalPosition is set to * CalloutPosition.MIDDLE to have the horizontal center of the * callout align to the horizontal center of the owner.

* *

Subclasses may override to modify automatic positioning behavior.

*/ mx_internal function commitAutoPosition():void { if (!screen || ((horizontalPosition != CalloutPosition.AUTO) && (verticalPosition != CalloutPosition.AUTO))) { // Use explicit positions instead of AUTO actualHorizontalPosition = null; actualVerticalPosition = null; return; } var ownerBounds:Rectangle = owner.getBounds(systemManager.getSandboxRoot()); // Use aspect ratio to determine vertical/horizontal preference var isLandscape:Boolean = (screen.width > screen.height); // Exterior space var exteriorSpaceLeft:Number = Math.max(0, ownerBounds.left); var exteriorSpaceRight:Number = Math.max(0, screen.width - ownerBounds.right); var exteriorSpaceTop:Number = Math.max(0, ownerBounds.top); var exteriorSpaceBottom:Number = Math.max(0, screen.height - ownerBounds.bottom); if (verticalPosition != CalloutPosition.AUTO) { // Horizontal auto only switch (verticalPosition) { case CalloutPosition.START: case CalloutPosition.MIDDLE: case CalloutPosition.END: { actualHorizontalPosition = (exteriorSpaceRight > exteriorSpaceLeft) ? CalloutPosition.AFTER : CalloutPosition.BEFORE; break; } default: { actualHorizontalPosition = CalloutPosition.MIDDLE; break; } } actualVerticalPosition = null; } else if (horizontalPosition != CalloutPosition.AUTO) { // Vertical auto only switch (horizontalPosition) { case CalloutPosition.START: case CalloutPosition.MIDDLE: case CalloutPosition.END: { actualVerticalPosition = (exteriorSpaceBottom > exteriorSpaceTop) ? CalloutPosition.AFTER : CalloutPosition.BEFORE; break; } default: { actualVerticalPosition = CalloutPosition.MIDDLE; break; } } actualHorizontalPosition = null; } else // if ((verticalPosition == CalloutPosition.AUTO) && (horizontalPosition == CalloutPosition.AUTO)) { if (!isLandscape) { // Arrow will be vertical when in portrait actualHorizontalPosition = CalloutPosition.MIDDLE; actualVerticalPosition = (exteriorSpaceBottom > exteriorSpaceTop) ? CalloutPosition.AFTER : CalloutPosition.BEFORE; } else { // Arrow will be horizontal when in landscape actualHorizontalPosition = (exteriorSpaceRight > exteriorSpaceLeft) ? CalloutPosition.AFTER : CalloutPosition.BEFORE; actualVerticalPosition = CalloutPosition.MIDDLE; } } } /** * @private * Return true if user-specified max size if set */ mx_internal function get isMaxSizeSet():Boolean { var explicitMaxW:Number = super.explicitMaxWidth; var explicitMaxH:Number = super.explicitMaxHeight; return (!isNaN(explicitMaxW) && !isNaN(explicitMaxH)); } /** * @private * Return the original height if the soft keyboard is active. This height * is used to stabilize AUTO positioning so that the position is based * on the original height of the Callout instead of a possibly shorter * height due to soft keyboard effects. */ mx_internal function get calloutHeight():Number { return (isSoftKeyboardEffectActive) ? softKeyboardEffectCachedHeight : getLayoutBoundsHeight(); } /** * @private * Compute max width and max height. Uses the the owner and screen bounds * as well as preferred positions to determine max width and max height * for all possible exterior and interior positions. */ mx_internal function commitMaxSize():void { var ownerBounds:Rectangle = owner.getBounds(systemManager.getSandboxRoot()); var ownerLeft:Number = ownerBounds.left; var ownerRight:Number = ownerBounds.right; var ownerTop:Number = ownerBounds.top; var ownerBottom:Number = ownerBounds.bottom; var maxW:Number; var maxH:Number; switch (actualHorizontalPosition) { case CalloutPosition.MIDDLE: { // Callout matches screen width maxW = screen.width - (margin * 2); break; } case CalloutPosition.START: case CalloutPosition.END: { // Flip left and right when using inner positions ownerLeft = ownerBounds.right; ownerRight = ownerBounds.left; // Fall through } default: { // Maximum is the larger of the actual position or flipped position maxW = Math.max(ownerLeft, screen.right - ownerRight) - margin; break; } } // If preferred position was AUTO, then allow maxWidth to grow to // fit the interior position if the owner is wide if ((horizontalPosition == CalloutPosition.AUTO) && (ownerBounds.width > maxW)) maxW += ownerBounds.width; switch (actualVerticalPosition) { case CalloutPosition.MIDDLE: { // Callout matches screen height maxH = screen.height - (margin * 2); break; } case CalloutPosition.START: case CalloutPosition.END: { // Flip top and bottom when using inner positions ownerTop = ownerBounds.bottom; ownerBottom = ownerBounds.top; // Fall through } default: { // Maximum is the larger of the actual position or flipped position maxH = Math.max(ownerTop, screen.bottom - ownerBottom) - margin; break; } } // If preferred position was AUTO, then allow maxHeight to grow to // fit the interior position if the owner is tall if ((verticalPosition == CalloutPosition.AUTO) && (ownerBounds.height > maxH)) maxH += ownerBounds.height; calloutMaxWidth = maxW; calloutMaxHeight = maxH; } /** * @private */ mx_internal function determineArrowPosition(horizontalPos:String, verticalPos:String):String { // Determine arrow direction, outer positions get priority. // Corner positions and center show no arrow var direction:String = ArrowDirection.NONE; if (horizontalPos == CalloutPosition.BEFORE) { if ((verticalPos != CalloutPosition.BEFORE) && (verticalPos != CalloutPosition.AFTER)) { direction = ArrowDirection.RIGHT; } } else if (horizontalPos == CalloutPosition.AFTER) { if ((verticalPos != CalloutPosition.BEFORE) && (verticalPos != CalloutPosition.AFTER)) { direction = ArrowDirection.LEFT; } } else if (verticalPos == CalloutPosition.BEFORE) { direction = ArrowDirection.DOWN; } else if (verticalPos == CalloutPosition.AFTER) { direction = ArrowDirection.UP; } else if (horizontalPos == CalloutPosition.START) { direction = ArrowDirection.LEFT; } else if (horizontalPos == CalloutPosition.END) { direction = ArrowDirection.RIGHT; } else if (verticalPos == CalloutPosition.START) { direction = ArrowDirection.UP; } else if (verticalPos == CalloutPosition.END) { direction = ArrowDirection.DOWN; } return direction; } /** * @private * * Uses horizontalPosition and verticalPosition to determine the bounds of * the callout. */ mx_internal function determinePosition(horizontalPos:String, verticalPos:String, matrix:Matrix, registrationPoint:Point):Rectangle { var ownerVisualElement:ILayoutElement = owner as ILayoutElement; var ownerWidth:Number = (ownerVisualElement) ? ownerVisualElement.getLayoutBoundsWidth() : owner.width; var ownerHeight:Number = (ownerVisualElement) ? ownerVisualElement.getLayoutBoundsHeight() : owner.height; var calloutWidth:Number = getLayoutBoundsWidth(); var calloutHeight:Number = this.calloutHeight; switch (horizontalPos) { case CalloutPosition.BEFORE: { // The full width of the callout is before the owner // All arrow directions are ArrowDirection.RIGHT x=(width - arrow.width) registrationPoint.x = -calloutWidth; break; } case CalloutPosition.START: { // ArrowDirection.LEFT is at x=0 registrationPoint.x = 0; break; } case CalloutPosition.END: { // The ends of the owner and callout are aligned registrationPoint.x = (ownerWidth - calloutWidth); break; } case CalloutPosition.AFTER: { // The full width of the callout is after the owner // All arrow directions are ArrowDirection.LEFT (x=0) registrationPoint.x = ownerWidth; break; } default: // case CalloutPosition.MIDDLE: { registrationPoint.x = Math.floor((ownerWidth - calloutWidth) / 2); break; } } switch (verticalPos) { case CalloutPosition.BEFORE: { // The full height of the callout is before the owner // All arrow directions are ArrowDirection.DOWN y=(height - arrow.height) registrationPoint.y = -calloutHeight; break; } case CalloutPosition.START: { // ArrowDirection.UP is at y=0 registrationPoint.y = 0; break; } case CalloutPosition.MIDDLE: { registrationPoint.y = Math.floor((ownerHeight - calloutHeight) / 2); break; } case CalloutPosition.END: { // The ends of the owner and callout are aligned registrationPoint.y = (ownerHeight - calloutHeight); break; } default: //case CalloutPosition.AFTER: { // The full height of the callout is after the owner // All arrow directions are ArrowDirection.UP (y=0) registrationPoint.y = ownerHeight; break; } } var topLeft:Point = registrationPoint.clone(); var size:Point = MatrixUtil.transformBounds(calloutWidth, calloutHeight, matrix, topLeft); var bounds:Rectangle = new Rectangle(); bounds.left = topLeft.x; bounds.top = topLeft.y; bounds.width = size.x; bounds.height = size.y; return bounds; } /** * @private */ mx_internal function get isArrowVertical():Boolean { return (arrowDirection == ArrowDirection.UP || arrowDirection == ArrowDirection.DOWN); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function arrow_resizeHandler(event:Event):void { updateSkinDisplayList(); } /** * @private */ private function systemManager_resizeHandler(event:Event):void { //callLater() solves bug FLEX-34712 only affecting android device and not affecting ios device or simulator //where calculatePopUpPosition()'s correct x or y may not be immediately available callLater(queued_systemManager_resizeHandler, [event]); } /** * @private */ private function queued_systemManager_resizeHandler(event:Event):void { // Remove explicit settings if due to Resize effect softKeyboardEffectResetExplicitSize(); // Screen resize might require a new arrow direction and callout position invalidatePosition(); if (!isSoftKeyboardEffectActive) { // Force validation and use new screen size only if the keyboard // effect is not active. The stage dimensions may be invalid while // the soft keyboard is active. See SDK-31860. validateNow(); } } } } ",12098,False,2154.6626004614436,median "/* IVT (IVEE-TINY) - A FORTH-programable Scientific RPN Calculator that fits in 8 kilobytes (Arduino, ATTINY85) ____________________ PREAMBLE ____________________ IVT (IVEE-TINY) is the smallest member of the IV-calculator series (FORTH-like programable calculators). The name Ivee or IV stands for the roman number 4, which was the basis for naming FORTH (4th generation programming language). The hardware is simple: - AVR ATTINY85 microcontroller (8192/512/512 bytes of FLASH/RAM/EEPROM) - OLED-display (128x32, I2C, SSD1306) - 16 keys touch sensitive keypad (TTP229-BSF, 2-wire) - CR2032 battery IVT was made without making compromises to offer a complete FORTH-like programming environment and a maximum of mathematical functions (mostly written in FORTH itself). And it's amazing, how much calculating power fits into 8 kilobytes: - 80 intrinsic functions based on FORTH - A wide range of mathematical and scientific commands (DUP DROP SWAP ROT OVER / * - + PI SQRT POWER INV INT EXP LN SIN COS TAN ASIN ACOS ATAN GAMMA P>R R>P nPr nCr) - Statistics, line best fit and normal distibution (CDF/PDF) - Present value calculations - Programming: Up to 16 user definable programs with a total of 440 steps (< = <> > IF ELSE THEN BEGIN UNTIL) - A solver to find roots of user defined functions - A dictionary of all commands, words and programs - An user definable menu for fast access to all commands, words and programs - Storing of 10 numbers/constants (permanently) - Adjustable brightness of the display Have fun! deetee ____________________ COMPILING ____________________ As IVT consumes 8190 bytes of flash memory (maximal 8192 bytes possible) compiling with proper settings is essential. Use the Arduino IDE, load the right library for the ATTINY85 and use the following settings: - Library: ""attiny by Davis A. Mellis"" - Board: ""ATtiny25/45/85 (No bootloader)"" - Chip: ""ATtiny85"" - Clock: ""8 MHz (internal)"" - B.O.D. Level: B.O.D. Disabled - Save EEPROM: ""EEPROM retained"" - Timer 1 Clock: ""CPU (CPU frequency)"" - LTO: ""Enabled"" - millis()/micros(): ""Disabled"" ____________________ KEYBOARD ____________________ F(MENU) 7(SUM+) 8(PRG) 9(/) E(SWAP) 4(DICT) 5(USR) 6(*) N(ROT) 1(RCL) 2(STO) 3(-) C(CA) 0(PI) .(INT) D(+) ____________________ LIMITS ____________________ As a microprocessor is primarily not made to do such complex things like performing a powerful calculator there are some limits in performance and resources. Most obvious is the limited precision of the intrinsic float format (IEEE 754, 32 bit). As four bytes only are used to represent a float respective double number the decimal digits of precision are limited to 6...7. In addition the resources of a microcontroller are limited like the FLASH memory (holds the executable program code), the RAM memory (holds variables and data while running) and the EEPROM (holds permanent data like settings or user programs). Due to the target of maximal calculating power IVT lacks on many ""features of comfort"". For example there is no error control - a division by zero results in a ""non interpretable"" display. However IVT tries to offer a maximum of features, comfort and performance with a minimum of required resources. LIMITS: 24 ... Maximal data stack size 7 ... Maximum number of displayed significant digits of a number 10 ... Maximal amount of numbers saved permanently (0~9) 16 ... Maximal number of user programs 440 ... Maximal size (steps) of all user programs 32 ... Maximal definable command slots of user menu ____________________ BROWSING MENUS ____________________ To navigate through the menu of some functions (MENU, DICT or USR) all selectable items are divided into four sections. Every section has its own up and down key (section I: E/N, section II: 4/1, section III: 5/2 and section IV: 6/3). To select one of the four presented items use the appropriate function key (F/7/8/9) or escape the menu with ""C"". There is some kind of hidden feature: If you leave the menu with the D-key the brightness of the display will be set (0~255, not permanent!). ____________________ COMMANDS ____________________ BASIC KEYS: 0~9. ... Digits and decimal point EE N ... 10-exponent (actually Y*10^X) and negate (change sign) D ... DUP (push stack) or complete number input C ... DROP top of stack or clear entry when in number input F ... Shift to select function keys or double press for user menu FUNCTION KEYS: + - * / ... Basic operations MENU ... Browse (and select) the user menu SUM+ ... Enter X-data for statistics or X,Y-data for linear regression PRG ... Edit program (00~15) - enter program number first SWAP ... Swap the two top numbers of stack (1 2 -> 2 1) DICT ... Browse (and select) the complete dictionary USR ... Set dictionary entry to user menu ROT ... Rotate stack (1 2 3 -> 2 3 1) STO RCL ... Store/recall number - enter memory number first (0~9) CA ... Clear stack and memories for statistics (5~7) PI ... Push PI to stack INT ... Integer value DICTIONARY (4 sections): F 7 8 9 ... F-key, numbers EE 4 5 6 ... 10-exponent, numbers N 1 2 3 ... NEGATE, numbers C 0 . D ... Clear/DROP, number, dot, DUP M S+ PR / ... MENU, SUM+, PRG edit, divide >< DC US * ... SWAP, DICT, set USER menu, multiply RT RC ST - ... ROT, RCL, STO, subtract CA PI IN + ... CA (clear all), PI, INT, add IF EL TH PC ... IF, ELSE, THEN, nPr/nCr < = <> > ... LESSTHAN, EQUAL, NOTEQUAL, GREATERTHAN BE UN SO I ... BEGIN, UNTIL, SOLVE, INV (1/X) c t- E LN ... COS, ATAN, EXP, LN s t s- c- ... SIN, TAN, ASIN, ACOS OV SQ yx !L ... OVER, SQRT, POW (y^x), ln(GAMMA) PV ND P> R> ... Present value, normal distribution, P->R, R->P S+ Sc x- LR ... SUM+, SUMclr (clears memories 5~9), MEAN/STDEV, L.R. 00 01 02 03 ... User programs 04 05 06 07 ... User programs 08 09 10 11 ... User programs 12 13 14 15 ... User programs ____________________ PV, ND, P<>R, STAT ____________________ PV ... Present value of given interest rate (ie. 0.08) and periods ND ... PDF (X) and CDF (Y) of standard normal distribution P> R> ... Polar/Rectangular conversion STAT ... Mean value (X) and standard deviation (Y). Note that the memories 5~9 (see RCL/STO) are used as statistic registers (Sxx, Sxy, n, Sx, Sy). LR ... Line best fit (y = X * x + Y) ____________________ PROGRAMMING ____________________ IVT is able to deal with up to 16 user programs (named 00~15) with a total number of 440 steps/commands. The maximal size per user program rises from 20 steps (program 00) to 35 steps (program 15). To edit a program, enter the program number (00~15) followed by PRG (F-8). The display shows P (for program), the program number (00~15), the program step number (vary with cursor keys E and N) and the command of this step. To insert a program step - press a key (number or DUP), - press a shifted key (press F twice to toggle) or - press DICT (F-4) to select a command from the dictionary. To delete a program step press ""."". Leave and save the program with ""C"". To execute a program select the appropriate program number/name from DICT. Please note that the first user program (00) will be used by the solver. ____________________ SOLVER ____________________ To find a root of a function (programmed in user program 00) enter an appropriate start value and select the command SO from the dictionary. ____________________ POWER CONSUMPTION ____________________ As IVT provides a maximum of calculating power there where less resources for a good power management (i.e. idle, screen saver, auto power off) left. Merely the not needed timer1 and AD-convertes are set off to save approximately 0.9 mA. The power consumption of IVT depends mainly on the usage of the display. That's why per default the brightness of the display is set to minimum. Please note that you can (not permanently) set the brightness of the display with pressing D when in any menu (takes brightness value from stack). In total IVT consumes approximately 9 mA - so a a single battery (CR2032) which has a capacity of approximately 200 mAh should theoretically work at least 20 hours. Electrical current drawn by device (approximately): - ATTINY85 ... 5 mA - Keypad ... 2 mA - Display ... 1~4 mA (promt ~ display full of 8's) ____________________ PROGRAM EXAMPLES ____________________ ABS: DUP 0 LT IF NEG THEN FRAC: DUP INT - SINH: EXP DUP INV NEG + 2 / ... sinh=(exp(x)-exp(-x))/2 COSH: EXP DUP INV + 2 / ... cosh=(exp(x)+exp(-x))/2 TANH: 2 * EXP DUP 1 - SWAP 1 + / ... tanh=(exp(2*x)-1)/(exp(2*x)+1) ASINH: DUP DUP * 1 + SQRT + LN ... asinh(x)=ln(x+sqrt(x*x+1)) ACOSH: DUP DUP * 1 - SQRT + LN ... acosh(x)=ln(x+sqrt(x*x-1)) ATANH: DUP 1 + SWAP NEG 1 + / SQRT LN ... atanh(x)=ln(sqrt((1+x)/(1-x))) POW10: 1 SWAP EE LOG: LN 1 0 LN / ... log(x)=ln(x)/ln(10) %: OVER / 1 0 0 * ... %=x/B*100% CHG%: OVER - OVER / 1 0 0 * ... chg%=(x-B)/B*100% QE: OVER 2 / DUP * SWAP - SQRT SWAP 2 / NEG SWAP OVER OVER - ROT ROT + ... x12=-p/2+-sqrt(p*p/4-q) DEG<>RAD: DUP PI * 1 8 0 / SWAP 1 8 0-* PI / C<>F: DUP 1 . 8 * 3 2 + SWAP 3 2 - 1 . 8 / KM<>MI: DUP 1 . 6 0 9 3 4 4 DUP DUP ROT SWAP / ROT ROT * M<>FT: DUP 3 . 3 7 0 0 7 9 DUP DUP ROT * ROT ROT / CM<>IN: DUP 2 . 5 4 DUP DUP ROT SWAP / ROT ROT * KG<>LBS: DUP 2 . 2 0 4 6 2 3 DUP DUP ROT * ROT ROT / L<>GAL: DUP 3. 7 8 5 4 1 2 DUP DUP ROT SWAP / ROT ROT * HMS2H: DOT 0 0 0 0 0 1 ADD // Round up to prevent leaps DUP DUP INT SWAP OVER - 1 0 0 * INT // hh mm ROT 3 PICK SUB 1 0 0 MULT OVER SUB 1 0 0 MULT, // ss 3 6 0 0 / SWAP 6 0 / + + // ->s ->h H2HMS: DUP 3 6 0 0 * DUP ROT INT // h->s SWAP OVER 3 6 0 0 * - 60 DIV INT, // hh mm ROT OVER 6 0 MULT SUB 3 PICK 3 6 0 0 * - // ss 1 0 0 0 0 / SWAP 1 0 0 / + + // hh.mmss nPr = n!/(n-r)! : OVER ROT ROT - 1 ROT ROT SWAP BEGIN SWAP ROT 1 ROT + DUP ROT * SWAP ROT OVER OVER SWAP LT UNTIL DROP DROP nCr = n!/(n-r)!/r! = nPr/r! : DUP ROT SWAP PERM 1 ROT BEGIN ROT ROT DUP ROT SWAP / ROT ROT 1 + SWAP OVER 1 - OVER SWAP LT UNTIL DROP DROP ____________________ ATTINY85 PINS ____________________ _____ Analog0/Reset P5 H1|* U |H8 Vcc Analog2 P3 H2| |H7 P2 SCK/Analog1 Analog3 P4 H3| |H6 P1 PWM1/MISO GND H4|_____|H5 P0 PWM0/AREF/SDA/MOSI ____________________ CIRCUIT DIAGRAM ____________________ _________________ | OLED-DISPLAY | | 128x32 SSD1306 | |_GND_VCC_SCK_SDA_| | | | | | | __|___|___|___|__ | GND VCC P2 P0 | | AVR ATTINY85 | |_________P3__P1__| | | | | __|___|___|___|__ | VCC GND SCL SDO | |Keypad TTP229-BSF| |-----------------| | O O O O | | | | O O O O | | O O O O | | | |... Solder to enable | O O O O | 16-key-mode (TP2=0) | | */ // ***** I N C L U D E S #include // I2C wire communication with display #include // Needed for (simple) power management #include // For saving data to EEPROM // ***** F O N T (4x8) // Font table #define __0 0 #define __1 1 #define __2 2 #define __3 3 #define __4 4 #define __5 5 #define __6 6 #define __7 7 #define __8 8 #define __9 9 #define __A 10 #define __B 11 #define __C 12 #define __D 13 #define __E 14 #define __F 15 #define __H 16 #define __I 17 #define __L 18 #define __M 19 #define __N 20 #define __O 21 #define __P 22 #define __R 23 #define __S 24 #define __T 25 #define __U 26 #define __V 27 #define __c 28 #define __s 29 #define __t 30 #define ___ 31 // space #define __DOT 32 #define __MULT 33 #define __ADD 34 #define __SUB 35 #define __DIV 36 #define __EM 37 // ! #define __LT 38 #define __EQ 39 #define __GT 40 #define __ARROW 41 #define __FINV 42 #define __POW1 43 #define __PI 44 #define __SQRT 45 #define __MEAN 46 #define __SWAP 47 #define FONTWIDTH 4 // Font width const byte font [] PROGMEM = { 0xff, 0x81, 0x81, 0xff, // 0 0x00, 0x02, 0xff, 0x00, // 1 0xf9, 0x89, 0x89, 0x8f, // 2 0x81, 0x89, 0x89, 0xff, // 3 0x0f, 0x08, 0x08, 0xff, // 4 0x8f, 0x89, 0x89, 0xf9, // 5 0xff, 0x89, 0x89, 0xf8, // 6 0x03, 0x01, 0x01, 0xff, // 7 0xff, 0x89, 0x89, 0xff, // 8 0x0f, 0x89, 0x89, 0xff, // 9 0xff, 0x09, 0x09, 0xff, // A 0xff, 0x89, 0x8f, 0xf8, // B 0xff, 0x81, 0x81, 0x80, // C 0x81, 0xfF, 0x81, 0xfF, // D 0xfF, 0x89, 0x89, 0x81, // E 0xfF, 0x09, 0x09, 0x01, // F 0xfF, 0x08, 0x08, 0xfF, // H 0x81, 0xff, 0x81, 0x80, // I 0xfF, 0x80, 0x80, 0x80, // L 0xfF, 0x06, 0x06, 0xfF, // M 0xfF, 0x0c, 0x18, 0xfF, // N 0xff, 0x81, 0x81, 0xff, // O 0xfF, 0x09, 0x09, 0x0f, // P 0xfF, 0x09, 0xf9, 0x8f, // R 0x8f, 0x89, 0x89, 0xf8, // S 0x01, 0xff, 0x01, 0x01, // T 0xfF, 0x80, 0x80, 0xfF, // U 0x1F, 0xf0, 0xf0, 0x1F, // V 0xfc, 0x84, 0x84, 0x84, // c 0x9c, 0x94, 0x94, 0xf4, // s 0x04, 0xff, 0x84, 0x80, // t 0x00, 0x00, 0x00, 0x00, // space 0xc0, 0xc0, 0x00, 0x00, // . 0x24, 0x18, 0x18, 0x24, // * 0x10, 0x38, 0x10, 0x00, // + 0x08, 0x08, 0x08, 0x08, // - 0xc0, 0x30, 0x0c, 0x03, // / 0x00, 0xbf, 0x00, 0x00, // ! 0x08, 0x14, 0x22, 0x41, // < 0x14, 0x14, 0x14, 0x14, // = 0x41, 0x22, 0x14, 0x08, // > 0x7f, 0x3e, 0x1c, 0x08, // arrow 0xff, 0xc1, 0xf5, 0xff, // inverted F 0x08, 0x08, 0x02, 0x1f, // ^-1 0x0c, 0xfc, 0x04, 0xfc, // PI 0x10, 0xff, 0x01, 0x01, // sqrt 0xda, 0x22, 0x22, 0xda, // mean 0x22, 0x72, 0x27, 0x22, // swap }; // ***** D I S P L A Y // DEFINES #define CONTRAST 0x00 // Initial contrast/brightness #define DADDRESS 0x3C // I2C slave address #define DPAGES 4 // Lines of screen #define DCOMMAND 0x00 // Command byte #define DDATA 0x40 // Data byte #define SCREENWIDTH 128 // Screen width in pixel #define MAXSTRBUF 10 // Maximal length of string buffer sbuf[] #define CHARW 3 // Character width (3 x FONTWIDTH) #define CHARH 4 // Character height (4 lines) #define DIGITS 8 // Number of digits when printing a number #define ALMOSTZERO 1e-37 // Limits to decide if sci or fix #define FIXMIN 1e-3 // Limits for fix display guarantee maximal #define FIXMAX 1e7 // number of significant digits #define PRINTNUMBER 9 // Digits to print number (small space for '.') - printsbuf #define PRINTMENU 8 // Digits to print menu (pairs of two) - printsbuf // VARIABLES static byte renderram = 0xB0, drawram = 0x40; // Masks to address GDDRAM of display static byte sbuf[MAXSTRBUF]; // Holds string to print static boolean isnewnumber = true; // True if stack has to be lifted before entering a new number static byte decimals = 0; // Number of decimals entered (input after decimal dot) static boolean isdot = false; // True if dot was pressed and decimals will be entered // MACROS #define _abs(x) ((x<0)?(-x):(x)) // abs()-substitute macro #define _ones(x) ((x)%10) // Calculates ones unit #define _tens(x) (((x)/10)%10) // Calculates tens unit #define _huns(x) (((x)/100)%10) // Calculates hundreds unit #define _tsds(x) (((x)/1000)%10) // Calculates thousands unit // SUBPROGRAMS static void dbegin(void) { // Initialize communication TinyWireM.begin(); } static void dsendstart(void) { // Start communication TinyWireM.beginTransmission(DADDRESS); } static bool dsendbyte(byte b) { // Send byte return (TinyWireM.write(b)); } static void dsendstop(void) { // Stop communication TinyWireM.endTransmission(); } static void dsenddatastart(void) { // Start data transfer dsendstart(); dsendbyte(DDATA); } static void dsenddatabyte(byte b) { // Send data byte if (!dsendbyte(b)) { dsendstop(); dsenddatastart(); dsendbyte(b); } } static void dsendcmdstart(void) { // Start command transfer dsendstart(); dsendbyte(DCOMMAND); } static void dsendcmd(byte cmd) { // Send command dsendcmdstart(); dsendbyte(cmd); dsendstop(); } static const byte initscreen [] PROGMEM = { // Initialization sequence 0xC8, // Set scan direction (C0 scan from COM0 to COM[N-1] or C8 mirroring) 0xA1, // Set segment remap (A0 regular or A1 flip) 0xA8, 0x1F, // Set mux ratio (N+1) where: 14> 4)); dsendbyte(x & 0x0f); dsendstop(); } static void dfill(byte b) { // Fill screen with byte/pattern b dsetcursor(0, 0); dsenddatastart(); for (int i = 0; i < SCREENWIDTH * DPAGES; i++) dsenddatabyte(b); dsendstop(); } static byte expand2bit(byte b) { // Expand 2 bits 000000ab b = (b | (b << 3)) & 0x11; // 000a000b for (byte i = 0; i < 3; i++) b |= (b << 1); // aaaabbbb return (b); } static double pow10(int8_t e) { // Calculates 10 raised to the power of e double f = 1.0F; if (e > 0) while (e--) f *= 10.0F; else while (e++) f /= 10.0F; return (f); } static void printcat(byte c, byte x) { // Print char c at position x for (byte y = 0; y < CHARH; y++) { // Lines (4) dsetcursor(x, y); // Set cursor for (byte j = 0; j < FONTWIDTH; j++) { // Fontbyte - shifted one pixel down byte bits = pgm_read_byte(&font[FONTWIDTH * c + j]); // Fontbyte bits = expand2bit((bits >> (y * 2)) & 0x03); // Expand 000000ab dsenddatastart(); for (byte i = 0; i < CHARW; i++) dsenddatabyte(bits); dsendstop(); } } } static void printsbuf(byte digits) { // Print ""digits"" elements of sbuf[] (shrink ""."") int8_t dotx = 0; for (byte i = 0; i < digits; i++) { printcat(sbuf[i], (FONTWIDTH + 1) * CHARW * i + dotx); if (digits == PRINTMENU) { if (i != 0 && i % 2) dotx += 3; // Menu - group in pairs } else if (sbuf[i] == __DOT) dotx = -6; // Number - small space for dot } } static void sbufclr(void) { // Clear sbuf for (byte i = 0; i < sizeof(sbuf); i++) sbuf[i] = ___; } static void printnum(double f) { // Print number int8_t ee = 0; // Fixed format int8_t e = 1; // Exponent long m; // Mantissa sbufclr(); if (f < 0.0F) { // # Manage sign f = - f; sbuf[0] = __SUB; } if (f >= ALMOSTZERO && (f < FIXMIN || f >= FIXMAX)) { // # SCI format ee = log10(f); // Exponent if (ee < 0) ee--; f /= pow10(ee); } if (f >= 1.0F) e = log10(f) + 1; // Calculate new exponent if (f !< 1) double a = pow10(7 - e); // # Calculate pre dot double d = (f * a + 0.5) / a; // Rounding m = d; for (byte i = e; i > 0; i--) { sbuf[i] = _ones(m); m /= 10; } sbuf[e + 1] = __DOT; if ((long)f >= (long)d) d = f; // # Calculate after dot (and suppress trailing zeros) m = (d - (long)d) * a + 0.5; boolean istrail = true; for (byte i = DIGITS; i > e + 1; i--) { byte one = _ones(m); if (!istrail || ((isnewnumber || i - e - 1 <= decimals) && (!isnewnumber || one != 0))) { sbuf[i] = one; // Assign digit istrail = false; // End of trailing zeros } m /= 10L; } if (ee) { // # Scientific exponent if applicable sbuf[6] = (ee < 0) ? __SUB : ___; if (ee < 0) ee = -ee; sbuf[8] = _ones(ee); sbuf[7] = _tens(ee); } printsbuf(PRINTNUMBER); } // ***** K E Y B O A R D // Defines #define KCLOCK 3 // SCL - Keyboard clock pin #define KDATA 1 // SDO - Keyboard data pin #define PREENDKEY 254 // Only evaluate keys smaller #define ENDKEY 255 // Evaluate keys smaller // Variables static byte key = PREENDKEY, oldkey = PREENDKEY; // Holds entered and old key (prevent keyrepeat) static byte getkey(void) { // Read keypad (TTP229-BSF) byte k; for (byte i = 0; i < 16; i++) { digitalWrite(KCLOCK, LOW); k = digitalRead(KDATA); digitalWrite(KCLOCK, HIGH); if (!k) return (i); } return (ENDKEY); } static byte key2nr(byte k) { // Convert key to number on keypad if (k >= 1 && k <= 3) return (k + 6); else if (k >= 5 && k <= 7) return (k - 1); else if (k >= 9 && k <= 11) return (k - 8); else return (0); } // ***** A P P L I C A T I O N #define RAD (180.0F/PI) // 180/PI ... used for _atan and _cos #define MAXCMDI 48 // Number of commands of intrinsic functions #define MAXCMDB 64 //120 End of builtin commands #define MAXCMDU 80 //160 End of user commands #define ISF 1 // F-key demanded #define MAXPRG 16 // Maximal number of user programs #define MAXPRGBUF 36 // Maximal size of prgbuf #define MEDIMENU 2 // Number of menu entry lines #define MEDIDICT 5 // Number of dict entry lines // EEPROM dimensions and addresses #define MEMSTO 10 // Number of memories #define EESTO 0 // Memories (MEMSTOx4 bytes) #define MENUITEMS 32 // Number of selectable user menu items #define EEMENU 40 // User menu (MENUITEMS bytes) #define EEUSTART 72 // User programs #define EEUEND EEPROM.length() #define EEU (EEUEND-EEUSTART) // Available user memory #define UL0 20 // Length of first user program #define UN 16 // Number of user programs // VARIABLES static boolean isprintscreen = true; // True, if screen should be printed static unsigned int mp; // MEMPOINTER (builtin and user functions) static byte fgm = 0, setfgm = 0; // F-key variables static byte select; // Selected options static byte medi = 0; // MEnu and DIctionary static boolean issetusr = false; // True if dict is used for setting usr menu static boolean isprgdict = false; // To select dict entry for program static byte setusrselect; // Stores selected cmd value to store static boolean isprgedit = false; // True, if program is edited static byte prgnr; // Number of program edited static int prgaddr; // Address of recent program in EEPROM (includes EEUSTART) static byte prgpos; // Position in edited program static byte prglength; // Size of program in program buffer static byte prgbuf[MAXPRGBUF]; // Program buffer #define DELTAX 1E-4 // Delta for solver static byte runs; // Solver cycle runs static boolean issolve = false; // True if solving is demanded #define DATASTACKSIZE 24 // DATA STACK double ds[DATASTACKSIZE]; static byte dp = 0; #define ADDRSTACKSIZE 24 // ADDRESS STACK static int as[ADDRSTACKSIZE]; static byte ap = 0; byte cl = 0; // CONDITIONAL LEVEL // Command code defines #define _7 1 // Intrinsic commands #define _8 2 #define _9 3 #define _4 5 #define _5 6 #define _6 7 #define _NEG 8 #define _1 9 #define _2 10 #define _3 11 #define _DROP 12 #define _0 13 #define _DOT 14 #define _DUP 15 #define _DIV 19 #define _SWAP 20 #define _MULT 23 #define _RCL 25 #define _STO 26 #define _ROT 24 #define _SUB 27 #define _PI 29 #define _ADD 31 #define _IF 32 #define _ELSE 33 #define _THEN 34 #define _LT 36 #define _NE 38 #define _INV 43 #define _BEGIN 40 #define _UNTIL 41 #define _COS 44 #define _ATAN 45 #define _EXP 46 #define _LN 47 #define _SIN MAXCMDI+0 // Builtin commands (mem) #define _TAN MAXCMDI+1 #define _ASIN MAXCMDI+2 #define _ACOS MAXCMDI+3 #define _OVER MAXCMDI+4 #define _SQRT MAXCMDI+5 #define _POW MAXCMDI+6 #define _PV MAXCMDI+7 #define _SUMADD MAXCMDI+8 #define _SUMCLR MAXCMDI+9 #define _SUMLR MAXCMDI+10 #define _SUMSTAT MAXCMDI+11 #define _GAMMALN MAXCMDI+12 #define _POL2RECT MAXCMDI+13 #define _RECT2POL MAXCMDI+14 #define _ND MAXCMDI+15 #define _PERMCOMB MAXCMDI+16 #define _END 255 // Function delimiter // Builtin functions (mem) const byte mem[] PROGMEM = { _END, // Necessary to prevent function starting with mp = 0 _9, _0, _SWAP, _SUB, _COS, _END, //0 SIN =cos(90-x) _DUP, _SIN, _SWAP, _COS, _DIV, _END, //1 TAN =sin/cos _DUP, _MULT, _INV, _1, _SUB, _SQRT, _INV, _ATAN, _END, //2 ASIN =atan(1/(sqrt(1/x/x-1)) _DUP, _MULT, _INV, _1, _SUB, _SQRT, _ATAN, _END, //3 ACOS =atan(sqrt(1/x/x-1)) _SWAP, _DUP, _ROT, _ROT, _END, //4 OVER _DUP, _0, _NE, _IF, _LN, _2, _DIV, _EXP, _THEN, _END, //5 SQRT =exp(ln(x)/2) _SWAP, _LN, _MULT, _EXP, _END, //6 POW a^b=exp(b*ln(a)) _OVER, _1, _ADD, _SWAP, _POW, _DUP, _1, _SUB, _SWAP, _DIV, _SWAP, _DIV, _END, //7 PV PV(i,n)=((1+i)^n-1)/(1+i)^n/i _7, _RCL, _1, _ADD, _7, _STO, //8 SUMADD - n _DUP, _8, _RCL, _ADD, _8, _STO, // X _DUP, _DUP, _MULT, _5, _RCL, _ADD, _5, _STO, // XX _OVER, _MULT, _6, _RCL, _ADD, _6, _STO, // XY _9, _RCL, _ADD, _9, _STO, _7, _RCL, _END, // Y push(n) _0, _DUP, _DUP, _DUP, _DUP, _DUP, //9 CLRSUMCLR _5, _STO, _6, _STO, _7, _STO, _8, _STO, _9, _STO, _END, _6, _RCL, _7, _RCL, _MULT, _8, _RCL, _9, _RCL, _MULT, _SUB, //10 SUMLR - a _5, _RCL, _7, _RCL, _MULT, _8, _RCL, _DUP, _MULT, _SUB, _DIV, _DUP, _8, _RCL, _MULT, _NEG, _9, _RCL, _ADD, _7, _RCL, _DIV, _SWAP, _END, // b _8, _RCL, _7, _RCL, _DIV, //11 STAT - mean (X/n) _DUP, _DUP, _MULT, _7, _RCL, _MULT, _NEG, _5, _RCL, _ADD, // stddev (XX-n*m^2)/(n-1) _7, _RCL, _1, _SUB, _DIV, _SQRT, _SWAP, _END, _1, _ADD, _DUP, _DUP, _DUP, _DUP, _1, _2, _MULT, //12 GAMMALN: ln!=(ln(2*PI)-ln(x))/2+x*(ln(x+1/(12*x-1/10/x))-1) _SWAP, _1, _0, _MULT, _INV, _SUB, _INV, _ADD, _LN, _1, _SUB, _MULT, _SWAP, _LN, _NEG, _2, _PI, _MULT, _LN, _ADD, _2, _DIV, _ADD, _END, _DUP, _ROT, _DUP, _COS, _SWAP, _SIN, _ROT, _MULT, _ROT, _ROT, _MULT, _END, //13 P>R y=r*sin(a) x=r*cos(a) _DUP, _MULT, _SWAP, _DUP, _MULT, _DUP, _ROT, _DUP, _ROT, _ADD, _SQRT, //14 R>P r=sqrt(x*x+y*y) a=atan(y/x) _ROT, _ROT, _DIV, _SQRT, _ATAN, _SWAP, _END, _DUP, _DUP, _DUP, _DUP, _MULT, _MULT, _DOT, _0, _7, _MULT, //15 ND _SWAP, _1, _DOT, _6, _MULT, _NEG, _ADD, _EXP, _1, _ADD, _INV, _SWAP, //CDF ~ 1/(1+exp(-0.07*x^3-1.6*x)) _DUP, _MULT, _NEG, _2, _DIV, _EXP, _2, _PI, _MULT, _SQRT, _INV, _MULT, _END, //PDF = exp(-x*x/2)/sqrt(2*PI) _DUP, _ROT, _SWAP, //16 PERM COMB _OVER, _ROT, _ROT, _SUB, _1, _ROT, _ROT, _SWAP, // PERM _BEGIN, _SWAP, _ROT, _1, _ROT, _ADD, _DUP, _ROT, _MULT, _SWAP, _ROT, _OVER, _OVER, _SWAP, _LT, _UNTIL, _DROP, _DROP, _DUP, _ROT, _1, _SWAP, // COMB _BEGIN, _ROT, _ROT, _DUP, _ROT, _SWAP, _DIV, _ROT, _ROT, _1, _ADD, _SWAP, _OVER, _1, _SUB, _OVER, _SWAP, _LT, _UNTIL, _DROP, _DROP, _END, }; // Command names static const byte cmd[] PROGMEM = { __FINV, ___, ___, __7, ___, __8, ___, __9, // 0 Primary keys __E, __E, ___, __4, ___, __5, ___, __6, __N, ___, ___, __1, ___, __2, ___, __3, __C, ___, ___, __0, ___, __DOT, ___, __D, __M, ___, __S, __ADD, __P, __R, ___, __DIV, // 16 F-keys __SWAP, ___, __D, __C, __U, __S, ___, __MULT, __R, __T, __R, __C, __S, __T, ___, __SUB, __C, __A, __PI, ___, __I, __N, ___, __ADD, __I, __F, __E, __L, __T, __H, __P, __C, // 32 Intrinsic functions __LT, ___, __EQ, ___, __LT, __GT, ___, __GT, __B, __E, __U, __N, __S, __O, __I, ___, __c, ___, __t, __POW1, __E, ___, __L, __N, __s, ___, __t, ___, __s, __POW1, __c, __POW1, // 48 Builtin functions __O, __V, __SQRT, ___, __P, ___, __EM, __L, __P, __V, __N, __D, __P, __ARROW, __R, __ARROW, __S, __ADD, __S, __c, __MEAN, ___, __L, __R, __0, __0, __0, __1, __0, __2, __0, __3, // 64 User functions __0, __4, __0, __5, __0, __6, __0, __7, __0, __8, __0, __9, __1, __0, __1, __1, __1, __2, __1, __3, __1, __4, __1, __5, }; // FUNCTION POINTER ARRAY static void (*dispatch[])(void) = { // Function pointer array &_keyf, &_num, &_num, &_num, // 00 Primary keys &_e, &_num, &_num, &_num, &_neg, &_num, &_num, &_num, &_drop, &_num, &_dot, &_dup, &_menu, &_sumadd, &_prgedit, &_div, // 16 F-keys &_swap, &_dict, &_usrset, &_mul, &_rot, &_mrcl, &_msto, &_sub, &_clr, &_pi, &_int, &_add, &_condif, &_condelse, &_condthen, &_permcomb, // 32 Intrinsic functions &_condlt, &_condeq, &_condne, &_condgt, &_begin, &_until, &_solve, &_inv, &_cos, &_atan, &_exp, &_ln, &_sin, &_tan, &_asin, &_acos, // 48 Builtin functions &_over, &_sqrt, &_pow, &_gammaln, &_pv, &_nd, &_pol2rect, &_rect2pol, &_sumadd, &_sumclr, &_sumstat, &_sumlr, }; //static void _nop(void) {} // NOP - no operation static void _num(void) { // Insert number _numinput(key2nr(key)); } static void _add(void) { // ADD + dpush(dpop() + dpop()); } static void _acos(void) { // ACOS seekmem(_ACOS); } static void _asin(void) { // ASIN seekmem(_ASIN); } static void _atan(void) { // ATAN dpush(atan(dpop()) * RAD); } static void _begin(void) { // BEGIN apush(mp); } static void _ce(void) { // CE if (isdot) { if (decimals) { decimals--; double a = pow10(decimals); dpush(((long)(dpop() * a) / a)); } else isdot = false; } else { long a = dpop() / 10.0F; if (!a) isnewnumber = true; else dpush(a); } } static void _clr(void) { // CLR dp = 0; _sumclr(); } static void _condelse(void) { // CONDITION ELSE _condseek(); // Seek next THEN cl--; } static void _condeq(void) { // CONDITION = dpush(dpop() == dpop()); } static void _condgt(void) { // CONDITION > dpush(dpop() < dpop()); } static void _condif(void) { // CONDITION IF cl++; // Increment conditional level if (!dpop()) _condseek(); // FALSE-Clause - seek next ELSE or THEN } static void _condlt(void) { // CONDITION < _condgt(); dpush(!dpop()); } static void _condne(void) { // CONDITION <> _condeq(); dpush(!dpop()); } static void _condseek(void) { // CONDITION - seek next ELSE or THEN boolean isloop = true; byte cltmp = 0; // Local conditional level while (isloop) { byte c = 0; if (mp < sizeof(mem)) c = pgm_read_byte(mem + mp++); // Builtin else if (mp < sizeof(mem) + EEU) c = EEPROM[mp++ -sizeof(mem) + EEUSTART]; if (mp >= sizeof(mem) + EEU) isloop = false; // No corresponding ELSE or THEN else if (c == _IF) cltmp++; // Nested IF found else if (cltmp && c == _THEN) cltmp--; // Nested IF ended else if (!cltmp && (c == _ELSE || c == _THEN)) isloop = false; } } static void _condthen(void) { // CONDITION THEN cl--; // Decrement conditional level } static void _cos(void) { // COS dpush(cos(dpop() / RAD)); } static void _dict(void) { // DICT select = 0; medi = MEDIDICT; } static void _div(void) { // DIV / _inv(); _mul(); } static void _dot(void) { // DOT . if (isnewnumber) { dpush(0.0F); // Start new number with 0 decimals = 0; isnewnumber = false; } isdot = true; } static void _drop(void) { // DROP if (!isnewnumber) _ce(); // Clear entry else if (dp) dp--; // Clear TOS } static void _dup(void) { // DUP if (isnewnumber && dp) dpush(ds[dp - 1]); } static void _e(void) { // E dpush(pow10(dpop())); _mul(); } static void _exp(void) { // EXP boolean isneg = false; // True for negative x if (dpush(dpop()) < 0.0F) { // Taylor series ist weak for negative x ... calculate exp(-x)=1/exp(x) _neg(); isneg = true; } dpush(1.0F); // Stack: x res for (byte i = 255; i; i--) { _swap(); _dup(); _rot(); // Duplicate x (TOS-1) dpush(i); _div(); _mul(); dpush(1.0F); _add(); // res = 1.0 + x * res / i; } if (isneg) _inv(); // Negative argument _swap(); _drop(); // Remove x (TOS-1) } static void _gammaln(void) { // GAMMALN seekmem(_GAMMALN); } static void _int(void) { // INT dpush((long)dpop()); } static void _inv(void) { // INV dpush(1.0F / dpop()); } static void _keyf(void) { // KEY-F fgm = ISF; setfgm = 0; } static void _ln(void) { // LN dpush(log(dpop())); } static void _menu(void) { // MENU select = 0; medi = MEDIMENU; } static void _mrcl(void) { // MRCL _mstorcl(false); } static void _msto(void) { // MSTO _mstorcl(true); } static void _mstorcl(boolean issto) { // MRCL byte nr = dpop(); byte addr = EESTO + nr * sizeof(double); // Has to be <255 (byte) if (nr < MEMSTO) { if (issto) EEwrite(addr, dpop()); else { double a; EEread(addr, a); dpush(a); } } } static void _mul(void) { // MULT * dpush(dpop()*dpop()); } /*static void _nand(void) { // NAND long b = dpop(); dpush(~((long)dpop() & b)); }*/ static void _nd(void) { // ND seekmem(_ND); } static void _neg(void) { // NEGATE dpush(-dpop()); } static void _numinput(byte k) { // NUM Numeric input (0...9) if (isdot) { // Append decimal dpush(k); dpush(pow10(++decimals)); _div(); _add(); } else if (isnewnumber) dpush((double)k); // Push new numeral else { // Append numeral dpush(10.0F); _mul(); dpush(k); _add(); } isnewnumber = false; } static void _over(void) { // OVER seekmem(_OVER); } void _permcomb(void) { // PERM COMB seekmem(_PERMCOMB); } static void _pi(void) { // PI dpush(PI); } void _pol2rect(void) { // POL2RECT seekmem(_POL2RECT); } void _pow(void) { // POWER seekmem(_POW); } void _pv(void) { // PRESENT VALUE seekmem(_PV); } static void _prgedit(void) { // PRGEDIT isprgedit = true; if ((prgnr = dpop()) >= MAXPRG) prgnr = 0; prgpos = prglength = 0; prgaddr = EEUSTART + eeudist(prgnr); byte len = prgnr + UL0, prgstep = EEPROM[prgaddr]; // Max program length and first step while (prglength < len && prgstep != _END) { prgbuf[prglength] = prgstep; // Load step from EEPROM to prgbuf prgstep = EEPROM[prgaddr + ++prglength]; // Next step } } void _rect2pol(void) { // RECT2POL seekmem(_RECT2POL); } static void _rot(void) { // ROT if (dp > 2) { double a = dpop(), b = dpop(), c = dpop(); dpush(b); dpush(a); dpush(c); } } static void _sin(void) { // SIN seekmem(_SIN); } static void _solve(void) { // SOLVE _dup(); _dup(); // 3 x0 on stack runs = 0; issolve = true; } static void _sqrt(void) { // SQRT seekmem(_SQRT); } static void _sub(void) { // SUB - _neg(); _add(); } static void _sumadd(void) { // SUM+ seekmem(_SUMADD); } static void _sumclr(void) { // SUMclr seekmem(_SUMCLR); } static void _sumlr(void) { // SUM LR seekmem(_SUMLR); } static void _sumstat(void) { // SUM STAT seekmem(_SUMSTAT); } static void _swap(void) { // SWAP if (dp > 1) { double a = dpop(), b = dpop(); dpush(a); dpush(b); } } static void _tan(void) { // TAN seekmem(_TAN); } static void _until(void) { // UNTIL if (!ap) ; // No BEGIN for this UNTIL else if (dpop()) apop(); // Go on (delete return address) else apush(mp = apop()); // Go back to BEGIN } static void _usrset(void) { // USR select = 0; medi = MEDIDICT; issetusr = true; } // SUBPROGRAMS static void delayshort(byte ms) { // Delay in ms (8MHz) for (long k = 0; k < ms * 8000L; k++) __asm__ __volatile__ (""nop\\n\\t""); } static int eeudist(byte i) { // Distance of user program number i from EEUSTART return ((2 * UL0 + i - 1) * i / 2); } static void execute(byte cmd) { // Execute command if (cmd < MAXCMDB) (*dispatch[cmd])(); // Dispatch intrinsic/builtin command else if (cmd < MAXCMDU) mp = eeudist(cmd - MAXCMDB) + sizeof(mem); // Execute user command if ((cmd % 4 == 0 && cmd != 12) || cmd > 14) { // New number - except: 0-9. DROP decimals = 0; isdot = false; isnewnumber = true; } if (fgm && setfgm) fgm = setfgm = 0; // Hold demanded F-key status one cycle setfgm = 1; } static void prgstepins(byte c) { // Insert step (character c in prgbuf at prgeditstart) for (byte i = prglength; i > prgpos; i--) prgbuf[i] = prgbuf[i - 1]; prgbuf[prgpos + 1] = c; prglength++; prgpos++; } template void EEwrite(int ee, const T& value) { // Write any datatype to EEPROM const byte* p = (const byte*)(const void*)&value; for (byte i = 0; i < sizeof(value); i++) EEPROM.write(ee++, *p++); } template void EEread(int ee, T& value) { // Read any datatype from EEPROM byte* p = (byte*)(void*)&value; for (byte i = 0; i < sizeof(value); i++) *p++ = EEPROM.read(ee++); } static void upn(byte n, byte l) { // Selection up l lines if (select > n * l && select <= (n + 1) * l - 1) select--; else select = (n + 1) * l - 1; } static void downn(byte n, byte l) { // Selection down l lines if (select >= n * l && select < (n + 1) * l - 1) select++; else select = n * l; } static byte menuselect(byte lines) { // Selection (1 line = 16 items) char k = key; if (k <= 3) return (select * 4 + k); // Execute else if (k >= 4 && k <= 7) upn(k - 4, lines); // # Up else if (k >= 8 && k <= 11) downn(k - 8, lines); // # Down0 if (k == 12) return (ENDKEY); // Escape /*if (k == 13) { // Hidden feature: Display off doff(); return (ENDKEY); }*/ if (k == 15) { // Hidden feature: Set contrast dcontrast(dpop()); return (ENDKEY); } return (PREENDKEY); } // *** S T A C K static void floatstack() { memcpy(ds, &ds[1], (DATASTACKSIZE - 1) * sizeof(double)); dp--; } static double dpush(double d) { // Push complex number to data-stack if (dp >= DATASTACKSIZE) floatstack(); // Float stack return (ds[dp++] = d); } static double dpop(void) { // Pop real number from data-stack return (dp ? ds[--dp] : 0.0F); } static void apush(int addr) { // Push address (int) to address-stack as[ap++] = addr; } static int apop(void) { // Pop address (int) from address-stack return (ap ? as[--ap] : NULL); } static void seekmem(byte n) { // Find run-address (mp) of n-th builtin function mp = 0; while (n + 1 - MAXCMDI) if (pgm_read_byte(&mem[mp++]) == _END) n--; } // ***** P R I N T I N G static boolean printscreen(void) { // Print screen due to state dfill(0x00); if (medi) { // MEnu or DIct for (byte i = 0; i < 4; i++) { byte nr = select * 4 + i; if (medi == MEDIMENU) nr = EEPROM[EEMENU + nr]; for (byte j = 0; j < 2; j++) sbuf[2 * i + j] = pgm_read_byte(&cmd[2 * nr + j]); } printsbuf(PRINTMENU); } else if (isprgedit) { // # Edit program sbuf[0] = ___; sbuf[1] = __P; sbuf[3] = _ones(prgnr); sbuf[2] = _tens(prgnr); // Program number sbuf[5] = _ones(prgpos); sbuf[4] = _tens(prgpos); // Program pos for (byte i = 0; i < 2; i++) sbuf[6 + i] = pgm_read_byte(&cmd[2 * prgbuf[prgpos] + i]); // Command printsbuf(PRINTMENU); } else if (dp) printnum(ds[dp - 1]); // Stack else printcat(__ARROW, 0); // Empty stack prompt if (!isnewnumber) printcat(__ARROW, 0); // Num input indicator if (fgm) printcat(__FINV, 0); // F indicator ddisplay(); return (false); // To determine isprintscreen } // ***** S E T U P A N D L O O P void setup() { dinit(); // Init display drender(); // Render current half of GDDRAM pinMode(KCLOCK, OUTPUT); pinMode(KDATA, INPUT); // Init keyboard pins //power_timer0_disable(); // Power off timer0 (saves 0.1 mA) power_timer1_disable(); // Power off timer1 (saves 0.6 mA) ADCSRA &= ~bit(ADEN); // Power off AD converter (saves 0.4 mA) } void loop() { if (isprintscreen) isprintscreen = printscreen(); // Print screen if (mp) { // *** Execute/run code if (mp < sizeof(mem)) key = pgm_read_byte(&mem[mp++]); // Builtin else if (mp < sizeof(mem) + EEU) key = EEPROM[mp++ -sizeof(mem) + EEUSTART]; // User else mp = 0; // cmd > MAXCMDU if (key >= MAXCMDI && key != _END) apush(mp); // Subroutine detected - branch if (key == _END) { // _END reached if (ap) mp = apop(); // End of subroutine - return else { // End of run mp = 0; if (!issolve) isprintscreen = true; // Print screen if not in solver } } else execute(key); } else { // *** No run - get key key = getkey(); // READ KEY delayshort(1); // Give keypad some time to settle if (issolve) { // # SOLVE if (++runs < 3) { if (runs == 2) { // Second run - f(x0+dx) _swap(); dpush(DELTAX); _add(); // x0+DELTAX ... Prepare new x-value } execute(MAXCMDB); // Execute first user program } else { // Third run - x1 _swap(); _div(); dpush(-1.0); _add(); // f1/f0-1 dpush(DELTAX); _swap(); _div(); // diffx=DELTAX/(f1/f0-1) double diffx = dpush(dpop()); // Rescue diffx for exit condition _sub(); // x1=x0-diffx ... improved x-value runs = 0; if (diffx < DELTAX && diffx > -DELTAX) { // Exit isnewnumber = isprintscreen = true; issolve = false; } else { // 3 x1 on stack _dup(); _dup(); } } } if (key != oldkey) { oldkey = key; // New valid key is old key if (key < ENDKEY) { //don(); // Wake up display (in case of doff) if (medi) { // ### Menu or Dict byte sel = menuselect(medi); if (sel < PREENDKEY) { // Item selected if (medi == MEDIMENU) { // # MENU if (issetusr) { // Save user menu entry EEPROM[EEMENU + sel] = setusrselect; issetusr = false; } else execute(EEPROM[EEMENU + sel]); // Execute selected command medi = 0; } else { // # DICT if (issetusr) { // Go on to menu setusrselect = sel; select = 0; medi = MEDIMENU; } else if (isprgdict) { // Go back to prgedit prgstepins(sel); isprgdict = false; isprgedit = true; medi = 0; } else { execute(sel); // Execute command directly medi = 0; } } } else if (sel == ENDKEY) { issetusr = false; // Escape medi = 0; } } else if (isprgedit) { // ### Program edit if (key == 0) fgm = fgm ? 0 : ISF; // # F-key toggle else if (key == 5 && fgm == ISF) { // # F-4 ... insert step via dict select = fgm = 0; medi = MEDIDICT; isprgdict = true; isprgedit = false; } else if (fgm == ISF) { // # Insert F-shifted key prgstepins(key + fgm * 16); fgm = 0; } else if (key == 4) { // # Up if (prgpos) prgpos--; ///else if (prglength) prgpos = prglength - 1; } else if (key == 8) { // # Down if (prgpos < prglength - 1) prgpos++; ///else prgpos = 0; } else if (key == 12) { // # Escape and save program to EEPROM for (byte i = 0; i < prglength; i++) EEPROM[prgaddr + i] = prgbuf[i]; EEPROM[prgaddr + prglength] = _END; isprgedit = false; } else if (key == 14) { // # Dot - Delete step if (prglength) { for (byte i = prgpos; i < prglength; i++) prgbuf[i] = prgbuf[i + 1]; prglength--; } } else prgstepins(key); // # Insert direct key } else execute(key + fgm * 16); // ### Execute key isprintscreen = true; } } } // End of evaluating key } ",16254,True,2522.7901221021807,median "class ZLNKECL_LOG definition public final create private . *""* public components of class ZLNKECL_LOG *""* do not include other source files here!!! public section. constants C_LOG_MSGTYP_ERROR type ZLNKELOG_MSGTYP_DE value 'E'. ""#EC NOTEXT constants C_LOG_MSGTYP_ABORT type ZLNKELOG_MSGTYP_DE value 'A'. ""#EC NOTEXT constants C_LOG_MSGTYP_SUCCESS type ZLNKELOG_MSGTYP_DE value 'S'. ""#EC NOTEXT constants C_LOG_MSGTYP_INFO type ZLNKELOG_MSGTYP_DE value 'I'. ""#EC NOTEXT constants C_LOG_MSGTYP_WARNING type ZLNKELOG_MSGTYP_DE value 'W'. ""#EC NOTEXT constants C_LOG_EVT_CONT_SERVER_REQ type ZLNKELOG_EVENT_DE value 'A'. ""#EC NOTEXT constants C_LOG_EVT_REQ_TO_AWS type ZLNKELOG_EVENT_DE value 'B'. ""#EC NOTEXT constants C_LOG_EVT_RESP_FROM_AWS type ZLNKELOG_EVENT_DE value 'C'. ""#EC NOTEXT constants C_LOG_EVT_BUCKET_CREATE type ZLNKELOG_EVENT_DE value 'D'. ""#EC NOTEXT constants C_LOG_EVT_BUCKET_DELETE type ZLNKELOG_EVENT_DE value 'E'. ""#EC NOTEXT constants C_LOG_EVT_BUCKET_LIFECYCLE type ZLNKELOG_EVENT_DE value 'F'. ""#EC NOTEXT constants C_LOG_EVT_USER_CREATED type ZLNKELOG_EVENT_DE value 'G'. ""#EC NOTEXT constants C_LOG_EVT_USER_EDITION type ZLNKELOG_EVENT_DE value 'H'. ""#EC NOTEXT constants C_LOG_EVT_USER_DELETED type ZLNKELOG_EVENT_DE value 'I'. ""#EC NOTEXT constants C_LOG_EVT_BUCKET_ENCRYPT type ZLNKELOG_EVENT_DE value 'J'. ""#EC NOTEXT constants C_LOG_EVT_AOBJ_ADD_BUCKET type ZLNKELOG_EVENT_DE value 'K'. ""#EC NOTEXT constants C_LOG_EVT_AOBJ_REMOVE_BUCKET type ZLNKELOG_EVENT_DE value 'L'. ""#EC NOTEXT constants C_LOG_EVT_AOBJ_EDITION type ZLNKELOG_EVENT_DE value 'M'. ""#EC NOTEXT constants C_LOG_EVT_CONT_SERVER_CX type ZLNKELOG_EVENT_DE value 'N'. ""#EC NOTEXT class-methods CLASS_CONSTRUCTOR . class-methods APPEND_LOG_CONTENT_SERVER_REQ importing !I_HTTP_REQUEST type ref to IF_HTTP_REQUEST . class-methods APPEND_LOG_CONTENT_SERVER_CX importing !I_EXCEPTION type ref to ZLNKECX_AWS_S3 . class-methods APPEND_LOG_REQ_TO_AWS importing !I_HTTP_REQUEST type ref to IF_HTTP_REQUEST !I_REQUEST type STRING . class-methods APPEND_LOG_AOBJ_ADD_BUCKET importing !I_AOBJ type OBJCT_TR01 !I_BUCKET type ZLNKEBUCKET_DE !I_ARCH_LINK type ARCH_LINK !I_STORE_FRST type ARCH_STORE !I_READARCSYS type ARCH_READ !I_USER_NAME type UNAME default SY-UNAME . class-methods APPEND_LOG_AOBJ_REMOVE_BUCKET importing !I_AOBJ type OBJCT_TR01 !I_BUCKET type ZLNKEBUCKET_DE !I_ARCH_LINK type ARCH_LINK !I_STORE_FRST type ARCH_STORE !I_READARCSYS type ARCH_READ !I_USER_NAME type UNAME default SY-UNAME . class-methods APPEND_LOG_AOBJ_EDITION importing !I_AOBJ type OBJCT_TR01 !I_BUCKET_OLD type ZLNKEBUCKET_DE !I_BUCKET_NEW type ZLNKEBUCKET_DE !I_ARCH_LINK_OLD type ARCH_LINK !I_ARCH_LINK_NEW type ARCH_LINK !I_STORE_FRST_OLD type ARCH_STORE !I_STORE_FRST_NEW type ARCH_STORE !I_READARCSYS_OLD type ARCH_READ !I_READARCSYS_NEW type ARCH_READ !I_USER_NAME type UNAME default SY-UNAME . class-methods APPEND_LOG_USER_CREATED importing !I_USER_DATA type ZLNKEUSER . class-methods APPEND_LOG_USER_DELETED importing !I_USER_DATA type ZLNKEUSER . class-methods APPEND_LOG_USER_EDITION importing !I_USER_DATA_OLD type ZLNKEUSER !I_USER_DATA_NEW type ZLNKEUSER . class-methods APPEND_LOG_RESP_FROM_AWS importing !I_HTTP_RESPONSE type ref to IF_HTTP_RESPONSE !I_XRESPONSE type XSTRING optional !I_EXCEPTION type ref to ZLNKECX_AWS_S3 optional . class-methods APPEND_LOG_CREATE_BUCKET importing !I_BUCKET_NAME type STRING !I_BUCKET_USER_NAME type ZLNKEUSERNAME_DE !I_REGION type ZLNKEREGION_DE !I_CLIENT_SIDE_ENCRYPTION type ZLNKECLIENT_SIDE_ENCRYPTION_DE !I_SERVER_SIDE_ENCRYPTION type ZLNKESERVER_SIDE_ENCRYPTION_DE !I_ZIP type ZLNKEZIPFLAG_DE !I_USER_NAME type UNAME default SY-UNAME !I_EXCEPTION type ref to ZLNKECX_AWS_S3 optional . class-methods APPEND_LOG_DELETE_BUCKET importing !I_BUCKET_NAME type STRING !I_USER_NAME type UNAME default SY-UNAME !I_EXCEPTION type ref to ZLNKECX_AWS_S3 optional . class-methods APPEND_LOG_BUCKET_LIFECYCLE importing !I_BUCKET_NAME type STRING !I_USER_NAME type UNAME default SY-UNAME !I_LIFECYCLE type ZLNKEBUCKET_LIFECYCLE_DE !I_EXCEPTION type ref to ZLNKECX_AWS_S3 optional . class-methods APPEND_LOG_BUCKET_SERV_ENCRYPT importing !I_BUCKET_NAME type STRING !I_USER_NAME type UNAME default SY-UNAME !I_SERVER_ENCRYPT_OLD type ZLNKESERVER_SIDE_ENCRYPTION_DE !I_SERVER_ENCRYPT type ZLNKESERVER_SIDE_ENCRYPTION_DE . protected section. *""* protected components of class ZLNKECL_LOG *""* do not include other source files here!!! private section. *""* private components of class ZLNKECL_LOG *""* do not include other source files here!!! type-pools ABAP . class-data ATTR_LOG_RESPONSE_FROM_AWS type ABAP_BOOL . class-data ATTR_LOG_REQ_RESP_FROM_AWS type ABAP_BOOL . class-data ATTR_LOG_CONT_SERV_REQUEST type ABAP_BOOL . class-data ATTR_KEEP_DAYS type ZLNKELOG_CFG-KEEP_DAYS . constants C_DEFAULT_DAYS_TO_KEEP type I value 10. ""#EC NOTEXT class-methods APPEND_LOGX importing !I_LOG_EVENT type ZLNKELOG_EVENT_DE !I_LOG_MSGTYP type ZLNKELOG_MSGTYP_DE !I_XSTRING type XSTRING . class-methods PURGE_LOG . class-methods READ_CONFIG . ENDCLASS. CLASS ZLNKECL_LOG IMPLEMENTATION. METHOD append_logx. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 11th April 2014 * Appends log to ZLNKElog *--------------------------------------------------------------------* DATA: l_timestampl TYPE timestampl. DATA: l_guid TYPE ZLNKEguid. DATA: ls_log TYPE ZLNKElog. GET TIME STAMP FIELD l_timestampl. CALL FUNCTION 'SYSTEM_UUID_CREATE' IMPORTING uuid = l_guid. ls_log-guid = l_guid. ls_log-timestamp = l_timestampl. ls_log-log_event = i_log_event. ls_log-log_msgtyp = i_log_msgtyp. ls_log-event_user = sy-uname. ls_log-rawdata = i_xstring. MODIFY ZLNKElog FROM ls_log. ENDMETHOD. METHOD append_log_aobj_add_bucket. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 7th May 2014 * Appends log for AOBJ Add Bucket event *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_aobj_s TYPE string, l_bucket_s TYPE string, l_arch_link_s TYPE string, l_store_frst_s TYPE string, l_readarcsys_s TYPE string, l_user_name_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_aobj_add_bucket TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element AOBJ_AddBucket lr_elem_aobj_add_bucket = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'AOBJ_AddBucket' parent = lr_ixml_document ). * Element AOBJ l_aobj_s = i_aobj. lr_ixml_document->create_simple_element( name = 'AOBJ' ""#EC NOTEXT parent = lr_elem_aobj_add_bucket value = l_aobj_s ). * Element Bucket l_bucket_s = i_bucket. lr_ixml_document->create_simple_element( name = 'Bucket' ""#EC NOTEXT parent = lr_elem_aobj_add_bucket value = l_bucket_s ). * Element ARCH_LINK IF i_arch_link = abap_true. l_arch_link_s = 'true'. ""#EC NOTEXT ELSE. l_arch_link_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'ARCH_LINK' ""#EC NOTEXT parent = lr_elem_aobj_add_bucket value = l_arch_link_s ). * Element STORE_FRST IF i_store_frst = abap_true. l_store_frst_s = 'Store Before Deleting'. ""#EC NOTEXT ELSE. l_store_frst_s = 'Delete Before Storing'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'STORE_FRST' ""#EC NOTEXT parent = lr_elem_aobj_add_bucket value = l_store_frst_s ). * Element READARCSYS IF i_readarcsys = abap_true. l_readarcsys_s = 'true'. ""#EC NOTEXT ELSE. l_readarcsys_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'STORE_FRST' ""#EC NOTEXT parent = lr_elem_aobj_add_bucket value = l_readarcsys_s ). * Element UserName l_user_name_s = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' ""#EC NOTEXT parent = lr_elem_aobj_add_bucket value = l_user_name_s ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_aobj_add_bucket i_log_msgtyp = c_log_msgtyp_success i_xstring = l_xxml. ENDMETHOD. METHOD append_log_aobj_edition. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 7th May 2014 * Appends log for AOBJ Edition event *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_aobj_s TYPE string, l_bucket_s TYPE string, l_arch_link_s TYPE string, l_store_frst_s TYPE string, l_readarcsys_s TYPE string, l_user_name_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_aobj_edition TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element AOBJ_Edition lr_elem_aobj_edition = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'AOBJ_Edition' parent = lr_ixml_document ). * Element AOBJ l_aobj_s = i_aobj. lr_ixml_document->create_simple_element( name = 'AOBJ' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_aobj_s ). IF i_bucket_old <> i_bucket_new. * Element Bucket Old l_bucket_s = i_bucket_old. lr_ixml_document->create_simple_element( name = 'Bucket_OLD' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_bucket_s ). * Element Bucket New l_bucket_s = i_bucket_new. lr_ixml_document->create_simple_element( name = 'Bucket_NEW' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_bucket_s ). ENDIF. IF i_arch_link_old <> i_arch_link_new. * Element ARCH_LINK_OLD IF i_arch_link_old = abap_true. l_arch_link_s = 'true'. ""#EC NOTEXT ELSE. l_arch_link_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'ARCH_LINK_OLD' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_arch_link_s ). * Element ARCH_LINK_NEW IF i_arch_link_new = abap_true. l_arch_link_s = 'true'. ""#EC NOTEXT ELSE. l_arch_link_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'ARCH_LINK_NEW' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_arch_link_s ). ENDIF. IF i_store_frst_old <> i_store_frst_new. * Element STORE_FRST_OLD IF i_store_frst_old = abap_true. l_store_frst_s = 'Store Before Deleting'. ""#EC NOTEXT ELSE. l_store_frst_s = 'Delete Before Storing'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'STORE_FRST_OLD' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_store_frst_s ). * Element STORE_FRST_NEW IF i_store_frst_new = abap_true. l_store_frst_s = 'Store Before Deleting'. ""#EC NOTEXT ELSE. l_store_frst_s = 'Delete Before Storing'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'STORE_FRST_NEW' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_store_frst_s ). ENDIF. IF i_readarcsys_old <> i_readarcsys_new. * Element READARCSYS_OLD IF i_readarcsys_old = abap_true. l_readarcsys_s = 'true'. ""#EC NOTEXT ELSE. l_readarcsys_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'READARCSYS_OLD' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_readarcsys_s ). * Element READARCSYS_NEW IF i_readarcsys_new = abap_true. l_readarcsys_s = 'true'. ""#EC NOTEXT ELSE. l_readarcsys_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'READARCSYS_NEW' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_readarcsys_s ). ENDIF. * Element UserName l_user_name_s = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' ""#EC NOTEXT parent = lr_elem_aobj_edition value = l_user_name_s ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_aobj_edition i_log_msgtyp = c_log_msgtyp_success i_xstring = l_xxml. ENDMETHOD. METHOD append_log_aobj_remove_bucket. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 7th May 2014 * Appends log for AOBJ Remove Bucket event *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_aobj_s TYPE string, l_bucket_s TYPE string, l_arch_link_s TYPE string, l_store_frst_s TYPE string, l_readarcsys_s TYPE string, l_user_name_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_aobj_remove_bucket TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element AOBJ_AddBucket lr_elem_aobj_remove_bucket = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'AOBJ_RemoveBucket' parent = lr_ixml_document ). * Element AOBJ l_aobj_s = i_aobj. lr_ixml_document->create_simple_element( name = 'AOBJ' ""#EC NOTEXT parent = lr_elem_aobj_remove_bucket value = l_aobj_s ). * Element Bucket l_bucket_s = i_bucket. lr_ixml_document->create_simple_element( name = 'Bucket' ""#EC NOTEXT parent = lr_elem_aobj_remove_bucket value = l_bucket_s ). * Element ARCH_LINK IF i_arch_link = abap_true. l_arch_link_s = 'true'. ""#EC NOTEXT ELSE. l_arch_link_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'ARCH_LINK' ""#EC NOTEXT parent = lr_elem_aobj_remove_bucket value = l_arch_link_s ). * Element STORE_FRST IF i_store_frst = abap_true. l_store_frst_s = 'Store Before Deleting'. ""#EC NOTEXT ELSE. l_store_frst_s = 'Delete Before Storing'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'STORE_FRST' ""#EC NOTEXT parent = lr_elem_aobj_remove_bucket value = l_store_frst_s ). * Element READARCSYS IF i_readarcsys = abap_true. l_readarcsys_s = 'true'. ""#EC NOTEXT ELSE. l_readarcsys_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'STORE_FRST' ""#EC NOTEXT parent = lr_elem_aobj_remove_bucket value = l_readarcsys_s ). * Element UserName l_user_name_s = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' ""#EC NOTEXT parent = lr_elem_aobj_remove_bucket value = l_user_name_s ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_aobj_remove_bucket i_log_msgtyp = c_log_msgtyp_success i_xstring = l_xxml. ENDMETHOD. METHOD append_log_bucket_lifecycle. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Appends log for Bucket Lifecycle event *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_log_msgtyp TYPE ZLNKElog_msgtyp_de. DATA: l_bucket_name TYPE string, l_user_name TYPE string, l_lifecycle_s TYPE string, l_message_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_bucketlifecycle TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element BucketLifecycle lr_elem_bucketlifecycle = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'BucketLifecycle' parent = lr_ixml_document ). * Element ErrorMsg IF i_exception IS NOT INITIAL. l_message_s = i_exception->get_text( ). lr_ixml_document->create_simple_element( name = 'ErrorMsg' ""#EC NOTEXT parent = lr_elem_bucketlifecycle value = l_message_s ). ENDIF. * Element BucketName l_bucket_name = i_bucket_name. lr_ixml_document->create_simple_element( name = 'BucketName' ""#EC NOTEXT parent = lr_elem_bucketlifecycle value = l_bucket_name ). * Element Lifecycle l_lifecycle_s = i_lifecycle. lr_ixml_document->create_simple_element( name = 'Lifecycle' ""#EC NOTEXT parent = lr_elem_bucketlifecycle value = l_lifecycle_s ). * Element UserName l_user_name = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' ""#EC NOTEXT parent = lr_elem_bucketlifecycle value = l_user_name ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). IF i_exception IS INITIAL. l_log_msgtyp = c_log_msgtyp_success. ELSE. l_log_msgtyp = c_log_msgtyp_error. ENDIF. CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_bucket_lifecycle i_log_msgtyp = l_log_msgtyp i_xstring = l_xxml. ENDMETHOD. METHOD append_log_bucket_serv_encrypt. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 5th May 2014 * Appends log for Bucket server side encrypt edition *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_bucket_name TYPE string, l_user_name TYPE string, l_encrypt_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_bucket_encrypt TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element BucketServerSideEncrypt lr_elem_bucket_encrypt = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'BucketServerSideEncrypt' parent = lr_ixml_document ). * Element BucketName l_bucket_name = i_bucket_name. lr_ixml_document->create_simple_element( name = 'BucketName' ""#EC NOTEXT parent = lr_elem_bucket_encrypt value = l_bucket_name ). * Element ServerSideEncryptOld IF i_server_encrypt_old = abap_true. l_encrypt_s = 'true'. ""#EC NOTEXT ELSE. l_encrypt_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'ServerSideEncryptOld' ""#EC NOTEXT parent = lr_elem_bucket_encrypt value = l_encrypt_s ). * Element ServerSideEncrypt IF i_server_encrypt = abap_true. l_encrypt_s = 'true'. ""#EC NOTEXT ELSE. l_encrypt_s = 'false'. ""#EC NOTEXT ENDIF. lr_ixml_document->create_simple_element( name = 'ServerSideEncrypt' ""#EC NOTEXT parent = lr_elem_bucket_encrypt value = l_encrypt_s ). * Element UserName l_user_name = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' ""#EC NOTEXT parent = lr_elem_bucket_encrypt value = l_user_name ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_bucket_encrypt i_log_msgtyp = c_log_msgtyp_success i_xstring = l_xxml. ENDMETHOD. METHOD append_log_content_server_cx. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 15th July 2014 * Appends log for Content Server exception *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_message_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_cont_serv_cx TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element Content Server Exception lr_elem_cont_serv_cx = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'ContentServerException' parent = lr_ixml_document ). * Element ErrorMsg IF i_exception IS NOT INITIAL. l_message_s = i_exception->get_text( ). lr_ixml_document->create_simple_element( name = 'ErrorMsg' ""#EC NOTEXT parent = lr_elem_cont_serv_cx value = l_message_s ). ENDIF. l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_cont_server_cx i_log_msgtyp = c_log_msgtyp_error i_xstring = l_xxml. ENDMETHOD. METHOD append_log_content_server_req. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 11th April 2014 * Appends log for content server request *--------------------------------------------------------------------* DATA: lt_headers TYPE tihttpnvp. DATA: l_xxml TYPE xstring. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_cont_serv_req TYPE REF TO if_ixml_element. DATA: lr_elem_headers TYPE REF TO if_ixml_element. FIELD-SYMBOLS: TYPE ihttpnvp. CHECK attr_log_cont_serv_request = abap_true. CHECK i_http_request IS NOT INITIAL. i_http_request->get_header_fields( CHANGING fields = lt_headers ). * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element Content Server request lr_elem_cont_serv_req = lr_ixml_document->create_simple_element( name = 'ContentServerRequest' parent = lr_ixml_document ). * Element Headers lr_elem_headers = lr_ixml_document->create_simple_element( name = 'Headers' ""#EC NOTEXT parent = lr_elem_cont_serv_req ). LOOP AT lt_headers ASSIGNING ""#EC NOTEXT WHERE name = '~request_method' OR name = '~request_uri' OR name = 'host'. REPLACE '~' INTO -name WITH space. CONDENSE -name NO-GAPS. lr_ixml_document->create_simple_element( name = -name parent = lr_elem_headers value = -value ). ENDLOOP. l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_cont_server_req i_log_msgtyp = c_log_msgtyp_info i_xstring = l_xxml. ENDMETHOD. METHOD append_log_create_bucket. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Appends log for Bucket Creation event *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_log_msgtyp TYPE ZLNKElog_msgtyp_de. DATA: l_bucket_name TYPE string, l_bucket_user_name TYPE string, l_user_name TYPE string, l_region TYPE string, l_server_side_encryption TYPE string, l_client_side_encryption TYPE string, l_zip TYPE string, l_message_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_createbucket TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element CreateBucket lr_elem_createbucket = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'CreateBucket' parent = lr_ixml_document ). * Element ErrorMsg IF i_exception IS NOT INITIAL. l_message_s = i_exception->get_text( ). lr_ixml_document->create_simple_element( name = 'ErrorMsg' ""#EC NOTEXT parent = lr_elem_createbucket value = l_message_s ). ENDIF. * Element BucketName l_bucket_name = i_bucket_name. lr_ixml_document->create_simple_element( name = 'BucketName' ""#EC NOTEXT parent = lr_elem_createbucket value = l_bucket_name ). * Element BucketUserName l_bucket_user_name = i_bucket_user_name. lr_ixml_document->create_simple_element( name = 'BucketUserName' ""#EC NOTEXT parent = lr_elem_createbucket value = l_bucket_user_name ). * Element Region l_region = i_region. lr_ixml_document->create_simple_element( name = 'Region' ""#EC NOTEXT parent = lr_elem_createbucket value = l_region ). * Element ClientSideEncryption IF i_client_side_encryption = abap_true. l_client_side_encryption = 'true'. ELSE. l_client_side_encryption = 'false'. ENDIF. lr_ixml_document->create_simple_element( name = 'ClientSideEncryption' ""#EC NOTEXT parent = lr_elem_createbucket value = l_client_side_encryption ). * Element ServerSideEncryption IF i_server_side_encryption = abap_true. l_server_side_encryption = 'true'. ELSE. l_server_side_encryption = 'false'. ENDIF. lr_ixml_document->create_simple_element( name = 'ServerSideEncryption' ""#EC NOTEXT parent = lr_elem_createbucket value = l_server_side_encryption ). * Element Zip IF i_zip = abap_true. l_zip = 'true'. ELSE. l_zip = 'false'. ENDIF. lr_ixml_document->create_simple_element( name = 'Zip' ""#EC NOTEXT parent = lr_elem_createbucket value = l_zip ). * Element UserName l_user_name = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' ""#EC NOTEXT parent = lr_elem_createbucket value = l_user_name ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). IF i_exception IS INITIAL. l_log_msgtyp = c_log_msgtyp_success. ELSE. l_log_msgtyp = c_log_msgtyp_error. ENDIF. CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_bucket_create i_log_msgtyp = l_log_msgtyp i_xstring = l_xxml. ENDMETHOD. METHOD append_log_delete_bucket. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Appends log for Bucket Delete event *--------------------------------------------------------------------* DATA: l_xxml TYPE xstring. DATA: l_log_msgtyp TYPE ZLNKElog_msgtyp_de. DATA: l_bucket_name TYPE string, l_user_name TYPE string, l_message_s TYPE string. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_deletebucket TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element DeleteBucket lr_elem_deletebucket = lr_ixml_document->create_simple_element( name = 'DeleteBucket' parent = lr_ixml_document ). * Element ErrorMsg IF i_exception IS NOT INITIAL. l_message_s = i_exception->get_text( ). lr_ixml_document->create_simple_element( name = 'ErrorMsg' ""#EC NOTEXT parent = lr_elem_deletebucket value = l_message_s ). ENDIF. * Element BucketName l_bucket_name = i_bucket_name. lr_ixml_document->create_simple_element( name = 'BucketName' parent = lr_elem_deletebucket value = l_bucket_name ). * Element UserName l_user_name = i_user_name. lr_ixml_document->create_simple_element( name = 'UserName' parent = lr_elem_deletebucket value = l_user_name ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). IF i_exception IS INITIAL. l_log_msgtyp = c_log_msgtyp_success. ELSE. l_log_msgtyp = c_log_msgtyp_error. ENDIF. CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_bucket_delete i_log_msgtyp = l_log_msgtyp i_xstring = l_xxml. ENDMETHOD. METHOD append_log_req_to_aws. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Appends log for Request to S3 *--------------------------------------------------------------------* DATA: lt_headers TYPE tihttpnvp. DATA: l_xxml TYPE xstring. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_req_to_s3 TYPE REF TO if_ixml_element. DATA: lr_elem_headers TYPE REF TO if_ixml_element. FIELD-SYMBOLS: TYPE ihttpnvp. CHECK attr_log_req_resp_from_aws = abap_true. CHECK i_http_request IS NOT INITIAL. i_http_request->get_header_fields( CHANGING fields = lt_headers ). * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element RequestToS3 lr_elem_req_to_s3 = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'RequestToS3' parent = lr_ixml_document ). * Element Request lr_ixml_document->create_simple_element( name = 'Request' ""#EC NOTEXT parent = lr_elem_req_to_s3 value = i_request ). * Element Headers lr_elem_headers = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'Headers' parent = lr_elem_req_to_s3 ). LOOP AT lt_headers ASSIGNING . REPLACE '~' INTO -name WITH space. CONDENSE -name NO-GAPS. lr_ixml_document->create_simple_element( name = -name parent = lr_elem_headers value = -value ). ENDLOOP. l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_req_to_aws i_log_msgtyp = c_log_msgtyp_info i_xstring = l_xxml. ENDMETHOD. METHOD append_log_resp_from_aws. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Appends log for Response from S3 *--------------------------------------------------------------------* DATA: lt_headers TYPE tihttpnvp. DATA: l_xxml TYPE xstring. DATA: l_log_msgtyp TYPE ZLNKElog_msgtyp_de. DATA: l_message_s TYPE string. DATA: l_xml TYPE string. DATA: l_response_is_xml TYPE abap_bool. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_resp_from_s3 TYPE REF TO if_ixml_element. DATA: lr_elem_headers TYPE REF TO if_ixml_element. FIELD-SYMBOLS: TYPE ihttpnvp. CHECK attr_log_req_resp_from_aws = abap_true. CHECK i_http_response IS NOT INITIAL. i_http_response->get_header_fields( CHANGING fields = lt_headers ). * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element ResponseFromS3 lr_elem_resp_from_s3 = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'ResponseFromS3' parent = lr_ixml_document ). * Element ErrorMsg IF i_exception IS NOT INITIAL. l_message_s = i_exception->get_text( ). lr_ixml_document->create_simple_element( name = 'ErrorMsg' ""#EC NOTEXT parent = lr_elem_resp_from_s3 value = l_message_s ). ENDIF. * Element Headers lr_elem_headers = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'Headers' parent = lr_elem_resp_from_s3 ). LOOP AT lt_headers ASSIGNING . IF -name = 'content-type' AND ( -value = 'application/xml' OR -value = 'text/xml' ). l_response_is_xml = abap_true. ENDIF. REPLACE '~' INTO -name WITH space. CONDENSE -name NO-GAPS. lr_ixml_document->create_simple_element( name = -name parent = lr_elem_headers value = -value ). ENDLOOP. * If configuration is marked to log xml response and * the response is XML, log it... IF attr_log_response_from_aws = abap_true AND l_response_is_xml = abap_true. TRY. CALL METHOD ZLNKEcl_string_conversions=>xstring_to_string EXPORTING input = i_xresponse IMPORTING output = l_xml. lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'Response' parent = lr_elem_resp_from_s3 value = l_xml ). CATCH cx_sy_no_handler. ""#EC NO_HANDLER * Should not happen. * In this case, we don't create element Response ENDTRY. ENDIF. l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). IF i_exception IS INITIAL. l_log_msgtyp = c_log_msgtyp_info. ELSE. l_log_msgtyp = c_log_msgtyp_error. ENDIF. CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_resp_from_aws i_log_msgtyp = l_log_msgtyp i_xstring = l_xxml. ENDMETHOD. METHOD append_log_user_created. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 24th April 2014 * Appends log for Request to S3 *--------------------------------------------------------------------* DATA: l_string TYPE string. DATA: l_xxml TYPE xstring. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_user TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element UserCreation lr_elem_user = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'UserCreation' parent = lr_ixml_document ). l_string = i_user_data-user_name. lr_ixml_document->create_simple_element( name = 'USER_NAME' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data-access_key. lr_ixml_document->create_simple_element( name = 'ACCESS_KEY' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data-secr_access_key. lr_ixml_document->create_simple_element( name = 'SECR_ACCESS_KEY' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_user_created i_log_msgtyp = c_log_msgtyp_info i_xstring = l_xxml. ENDMETHOD. METHOD append_log_user_deleted. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 24th April 2014 * Appends log for Request to S3 *--------------------------------------------------------------------* DATA: l_string TYPE string. DATA: l_xxml TYPE xstring. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_user TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element UserCreation lr_elem_user = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'UserDeletion' parent = lr_ixml_document ). l_string = i_user_data-user_name. lr_ixml_document->create_simple_element( name = 'USER_NAME' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data-access_key. lr_ixml_document->create_simple_element( name = 'ACCESS_KEY' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data-secr_access_key. lr_ixml_document->create_simple_element( name = 'SECR_ACCESS_KEY' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_user_deleted i_log_msgtyp = c_log_msgtyp_info i_xstring = l_xxml. ENDMETHOD. METHOD append_log_user_edition. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 24th April 2014 * Appends log for Request to S3 *--------------------------------------------------------------------* DATA: l_string TYPE string. DATA: l_xxml TYPE xstring. DATA: lr_ixml TYPE REF TO if_ixml. DATA: lr_ixml_document TYPE REF TO if_ixml_document. DATA: lr_elem_user TYPE REF TO if_ixml_element. * Create iXML object lr_ixml = cl_ixml=>create( ). * Create iXML document lr_ixml_document = lr_ixml->create_document( ). * Element UserCreation lr_elem_user = lr_ixml_document->create_simple_element( ""#EC NOTEXT name = 'UserEdition' parent = lr_ixml_document ). l_string = i_user_data_old-user_name. lr_ixml_document->create_simple_element( name = 'USER_NAME' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data_old-access_key. lr_ixml_document->create_simple_element( name = 'ACCESS_KEY_OLD' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data_old-secr_access_key. lr_ixml_document->create_simple_element( name = 'SECR_ACCESS_KEY_OLD' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data_new-access_key. lr_ixml_document->create_simple_element( name = 'ACCESS_KEY_NEW' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_string = i_user_data_new-secr_access_key. lr_ixml_document->create_simple_element( name = 'SECR_ACCESS_KEY_NEW' ""#EC NOTEXT parent = lr_elem_user value = l_string ). l_xxml = ZLNKEcl_xml_utils=>convert_ixml_doc_to_xstring( lr_ixml_document ). CALL METHOD ZLNKEcl_log=>append_logx EXPORTING i_log_event = c_log_evt_user_edition i_log_msgtyp = c_log_msgtyp_info i_xstring = l_xxml. ENDMETHOD. METHOD class_constructor. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Class constructor *--------------------------------------------------------------------* read_config( ). purge_log( ). ENDMETHOD. METHOD purge_log. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Deletes from log table old registers for events * c_log_evt_cont_server_req * c_log_evt_req_to_aws * c_log_evt_resp_from_aws *--------------------------------------------------------------------* DATA: l_timestamp TYPE timestamp. DATA: l_timestampl_c TYPE char21. DATA: l_datum TYPE datum. l_datum = sy-datum - attr_keep_days. l_timestampl_c(8) = l_datum. l_timestampl_c+8(6) = sy-uzeit. l_timestamp = l_timestampl_c. DELETE FROM ZLNKElog WHERE timestamp < l_timestamp AND log_event IN (c_log_evt_cont_server_req, c_log_evt_req_to_aws, c_log_evt_resp_from_aws). ENDMETHOD. METHOD read_config. *--------------------------------------------------------------------* * Company: RocketSteam * Author: Jordi Escoda, 14th April 2014 * Reads configuration *--------------------------------------------------------------------* SELECT SINGLE keep_days log_xml_resp_aws log_req_resp_aws log_contserv_req INTO (attr_keep_days, attr_log_response_from_aws, attr_log_req_resp_from_aws, attr_log_cont_serv_request) FROM ZLNKElog_cfg WHERE dummyid = space. IF sy-subrc <> 0. * Value by default attr_keep_days = c_default_days_to_keep. ENDIF. ENDMETHOD. ENDCLASS. ",11133,True,2816.0461692232006,median "/* PrintProgmem.ino AVR Architecture: Use the (Arduino compatible) u8g2 function ""print"" to draw a string, which is located in PROGMEM. For string constants use the F() macro, but this example use global strings instead. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { u8g2.begin(); } const char s[] PROGMEM = ""Progmem""; const char s1[] PROGMEM = ""ABC"" ; const char s2[] PROGMEM = ""DEF"" ; const char s3[] PROGMEM = ""GHI"" ; const char s4[] PROGMEM = ""JKL"" ; const char *a[] = { s1, s2, s3, s4 }; int i = 0; void loop(void) { u8g2.setFont(u8g2_font_ncenB14_tr); u8g2.firstPage(); do { u8g2.setCursor(0, 20); u8g2.print((class __FlashStringHelper *)s); // print a sting, located in PROGMEM u8g2.setCursor(0, 40); u8g2.print((class __FlashStringHelper *)a[i]); // print a sting (PROGMEM) via RAM array. } while ( u8g2.nextPage() ); delay(1000); i++; if ( i >= 4 ) i = 0; } ",16142,True,5041.980936878949,median "package com.akamai { import com.akamai.events.*; import flash.net.*; import flash.events.*; import flash.utils.*; import flash.system.Capabilities; import flash.media.SoundTransform; /** * Dispatched when an error condition has occurred. The event provides an error number and a verbose description * of each error: * * * * * * * * * * * * * * * *
Error NumberDescription
1Hostname cannot be empty
2Buffer length must be > 0.1
3Warning - this protocol is not supported on the Akamai network
4Warning - this port is not supported on the Akamai network
5Unable to load XML data from ident request
6Timed out while trying to connect
7Stream not found
8Cannot play, pause, seek, or resume since the stream is not defined
9Timed out trying to find the live stream
10Error requesting stream length
11Volume value out of range
12Network failure - unable to play the live stream
13Connection attempt rejected by server
* * @eventType com.akamai.events.AkamaiErrorEvent.ERROR */ [Event (name=""error"", type=""com.akamai.events.AkamaiErrorEvent"")] /** * Dispatched when a bandwidth estimate is complete. * * @eventType com.akamai.events.AkamaiNotificationEvent.BANDWIDTH */ [Event (name=""bandwidth"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the class has successfully connected to the Akamai Streaming service. * * @eventType com.akamai.events.AkamaiNotificationEvent.CONNECTED */ [Event (name=""connected"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the class has detected, by analyzing the * NetStream.netStatus events, the end of the stream. Deprecated in favor of * com.akamai.events.AkamaiStatusEvent.NETSTREAM_PLAYSTATUS * when communicating with a FMS 2.5 or higher server. * * @see com.akamai.events.AkamaiStatusEvent.NETSTREAM_PLAYSTATUS * * @eventType com.akamai.events.AkamaiNotificationEvent.END_OF_STREAM */ [Event (name=""end"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the class has completed a stream length request. * * @see #getStreamLength * * @eventType com.akamai.events.AkamaiNotificationEvent.STREAM_LENGTH */ [Event (name=""streamlength"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the the class has successfully subscribed to a live stream. * * @see #isLive * @see #play * * @eventType com.akamai.events.AkamaiNotificationEvent.SUBSCRIBED */ [Event (name=""subscribed"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the class has unsubscribed from a live stream, or when the live stream it was previously subscribed * to has ceased publication. * * @see #isLive * @see #play * @see #unsubscribe * * @eventType com.akamai.events.AkamaiNotificationEvent.UNSUBSCRIBED */ [Event (name=""unsubscribed"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the class is making a new attempt to subscribe to a live stream * * @see #isLive * @see #play * * @eventType com.akamai.events.AkamaiNotificationEvent.SUBSCRIBE_ATTEMPT */ [Event (name=""subscribeattempt"", type=""com.akamai.events.AkamaiNotificationEvent"")] /** * Dispatched when the NetStream object has changed status. * * @see #createStream * * @eventType com.akamai.events.AkamaiStatusEvent.NETSTREAM */ [Event (name=""netstream"", type=""com.akamai.events.AkamaiStatusEvent"")] /** * Dispatched when the NetConnection object has changed status. * * @see #connect * * @eventType com.akamai.events.AkamaiStatusEvent.NETCONNECTION */ [Event (name=""netconnection"", type=""com.akamai.events.AkamaiStatusEvent"")] /** * Dispatched when the class has completely played a stream or switches to a different stream in a server-side playlist. * * @see #createStream * @see #play * * @eventType com.akamai.events.AkamaiStatusEvent.NETSTREAM_PLAYSTATUS */ [Event (name=""playstatus"", type=""com.akamai.events.AkamaiStatusEvent"")] /** * Dispatched when the class receives descriptive information embedded in the * FLV file being played. * * @see #createStream * @see #play * * @eventType com.akamai.events.AkamaiStatusEvent.NETSTREAM_METADATA */ [Event (name=""metadata"", type=""com.akamai.events.AkamaiStatusEvent"")] /** * Dispatched when an embedded cue point is reached while playing an FLV file. * * @see #createStream * @see #play * * @eventType com.akamai.events.AkamaiStatusEvent.NETSTREAM_CUEPOINT */ [Event (name=""cuepoint"", type=""com.akamai.events.AkamaiStatusEvent"")] /** * Dispatched when the the class receives information about ID3 data embedded in an MP3 file. * * @see #getMp3Id3Info * * @eventType com.akamai.events.AkamaiStatusEvent.MP3_ID3 */ [Event (name=""id3"", type=""com.akamai.events.AkamaiStatusEvent"")] /** * The AkamaiConnection class manages the complexity of establishing a robust NetConnection * with the Akamai Streaming service. * It optionally creates a NetStream over that NetConnection and exposes an API to control the * playback of content over that NetStream. The AkamaiConnection class works with on-demand FLV * and MP3 playback, as well as live FLV streams. * */ public class AkamaiConnection extends EventDispatcher { // Declare private vars private var _hostName:String; private var _appName:String; private var _isLive:Boolean; private var _port:String; private var _protocol:String; private var _createStream:Boolean; private var _maxBufferLength:uint; private var _useFastStartBuffer:Boolean; private var _akLoader:URLLoader; private var _ip:String; private var _isPaused:Boolean; private var _streamLength:uint; private var _nc:AkamaiNetConnection; private var _ns:NetStream; private var _nsId3:NetStream; private var _aConnections:Array; private var _connectionTimer:Timer; private var _timeOutTimer:Timer; private var _liveStreamTimer:Timer; private var _liveStreamRetryTimer:Timer; private var _liveFCSubscribeTimer:Timer; private var _liveStreamMasterTimeout:uint; private var _connectionAttempt:uint; private var _aNC:Array; private var _aboutToStop:Boolean; private var _volume:Number; private var _panning:Number; private var _connectionEstablished:Boolean; private var _streamEstablished:Boolean; private var _pendingLiveStreamName:String; private var _playingLiveStream:Boolean; private var _successfullySubscribed:Boolean; private var _authParams:String; // Declare private constants private const TIMEOUT:uint = 15000; private const LIVE_RETRY_INTERVAL:Number = 30000; private const LIVE_ONFCSUBSCRIBE_TIMEOUT:Number = 60000; private const VERSION:String = ""1.1""; /** * Constructor. */ public function AkamaiConnection():void { NetConnection.defaultObjectEncoding = flash.net.ObjectEncoding.AMF0; initVars(); initializeTimers(); } /** * The connect method initiates a connection to the Akamai Streaming service. It accepts a single hostName parameter, which describes the host account with which * to connect. This parameter can optionally include the application name, separated by a ""/"". * Valid usage examples include:
    *
  • instance_name.connect(""cpxxxxx.edgefcs.net"");
  • *
  • instance_name.connect(""cpxxxxx.edgefcs.net/ondemand"");
  • *
  • instance_name.connect(""cpxxxxx.edgefcs.net/aliased_ondemand_app_name"");
  • *
  • instance_name.connect(""aliased.domain.name/aliased_ondemand_app_name"");
  • *
  • instance_name.connect(""cpxxxxx.live.edgefcs.net/live"");
* If the application name is not specifed, then the class will use ondemand * if isLive is false and live if isLive is true. * To connect to a cp code requiring authorization, first set the authParams * property before calling this connect method. *


* * @param The Akamai hostname to which to connect. The application name may optionally be * included in this string, separated from the hostname by a ""/"". * * @see #isLive * @see #authParams */ public function connect(hostName:String):void { if (hostName == """" ) { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,1,""Hostname cannot be empty"")); } else { _hostName = hostName.indexOf(""/"") != -1 ? hostName.slice(0,hostName.indexOf(""/"")) : hostName; _appName = hostName.indexOf(""/"") != -1 && hostName.indexOf(""/"") != hostName.length - 1 ? hostName.slice(hostName.indexOf(""/"") + 1) : isLive ? ""live"" : ""ondemand""; _connectionEstablished = false; _streamEstablished = false; // request IP address of optimum server _akLoader = new URLLoader(); _akLoader.addEventListener(""complete"",akamaiXMLLoaded); _akLoader.addEventListener(IOErrorEvent.IO_ERROR,catchIOError); _akLoader.load(new URLRequest(""http://"" + _hostName + ""/fcs/ident"")); } } /** * The last measured bandwidth value in kilobits/second. Requires that a NetConnection has been * established and that detectBandwidth() has previously been called. Since bandwidth * detection between the client and the server is an asynchronous operation, * to request the bandwidth, you must first make a call to the detectBandwidth() method * and then wait for notifcation from the AkamaiNotificationEvent.BANDWIDTH event before requesting * this property value. * * @returns bandwidth estimate in kiloBits/sec, or -1 if the NetConnection has not yet been established. * * @see #detectBandwidth */ // public function get bandwidth():Number { return _connectionEstablished ? _nc.bandwidth : -1; }; /** * The last measured latency value, in milliseconds. The latency is an estimate of the time it * takes a packet to travel from the client to the server. * Requires that a NetConnection has been established and that detectBandwidth() method has previously been * called. Since bandwidth/latency detection between the client and the server is an asynchronous operation, * to request the latency, you must first make a call to the detectBandwidth() method and then * wait for notifcation from the AkamaiNotificationEvent.BANDWIDTH event before requesting this property value. * * @returns latency estimate in milliseconds, or -1 if the NetConnection has not yet been established. * * @see #detectBandwidth * @see #bandwidth */ public function get latency():Number { return _streamEstablished ? _nc.latency : -1; }; /** * The IP address of the server to which the class connected. This parameter will only be returned if the class has managed to * successfully connect to the server. The class uses the IDENT function to locate the optimum (in terms * of physical proximity and load) server for connections. * * @returns Server IP address as a string if the connection has been made, otherwise null. * */ public function get serverIPaddress():String { return _connectionEstablished ? _ip : null; } /** * The port on which the class has connected. This parameter will only be returned if the class has managed to * successfully connect to the server. Possible port values are ""1935"", ""443"", and ""80"". This property will * differ from requestedPort if the requestedPort value was ""any"", in which case this property will return * the port that was actually used. * * @returns the port over which the connection has actually been made, otherwise null. * * @see #requestedPort */ public function get actualPort():String { return _connectionEstablished ? _nc.port : null; } /** * The name-value pairs required for invoking authorization services on the * Akamai network. Typically these include the ""auth"",""aifp"" and ""slist"" * parameters. These name-value pairs must be separated by a ""&"" and should * not commence with a ""?"", ""&"" or ""/"". An example of a valid authParams string * would be:

* * auth=dxaEaxdNbCdQceb3aLd5a34hjkl3mabbydbbx-bfPxsv-b4toa-nmtE&aifp=babufp&slist=secure/babutest * *

* These properties must be set before calling the connect method, * since authorization is checked when the connection is first established. * If the authorization parameters are rejected by the server, then error #13 * will be dispatched - ""Connection attempt rejected by server"". * * @returns the authorization name-value pairs. * * @default empty string. * */ public function get authParams():String { return _authParams; } /** * @private */ public function set authParams(ap:String):void { _authParams = ap; } /** * The port over which the class was originally requested to connect via the requestedPort property. * Possible requested port values are ""any"", ""1935"", ""443"" and ""80"". This property will * differ from actualPort if the requestedPort value was ""any"", in which case actualPort * will return the port that was actually used. * * @returns the requested port * * @default ""any"" * * @see #actualPort */ public function get requestedPort():String { return _port; } /** * @private */ public function set requestedPort(p:String):void { if (!(p.toLowerCase() == ""any"" || p == ""1935"" || p == ""80"" || p == ""443"")) { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,4,""Warning - this port is not supported on the Akamai network"")); } _port = p; } /** * The protocol over which the class has connected. This parameter will only be returned if the class has managed to * successfully connect to the server. Possible protocol values are ""rtmp"" or ""rtmpt"". This property will * differ from requestedProtocol if the requestedProtocol value was ""any"", in which case this property will return * the protocol that was actually used. * * @returns the protocol over which the connection has actually been made, otherwise null. * * @see #requestedProtocol */ public function get actualProtocol():String { return _connectionEstablished ? _nc.protocol : null; } /** * The protocol over which the class was originally requested to connect via the requestedProtocol property. * Possible requested port values are ""any"", ""rtmp"" or ""rtmpt"". This property will * differ from actualProtocol if the requestedProtocol value was ""any"", in which case actualProtocol * will return the protocol that was actually used. * * @returns the requested protocol * * @default ""any"" * * @see #actualProtocol */ public function get requestedProtocol():String { return _protocol; } /** * @private */ public function set requestedProtocol(p:String):void { if (!(p.toLowerCase() == ""any"" || p.toLowerCase() == ""rtmp"" || p.toLowerCase() == ""rtmpt"")) { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,3,""Warning - this protocol is not supported on the Akamai network"")); } _protocol = p; } /** * The version of this class. Akamai may release updates to this class and the version number * will increment with each release. * */ public function get version():String { return VERSION; } /** * The maximum buffer length set for the NetStream, in seconds. If useFastStartBuffer has * been set false (the default), then this value will be used to set the constant buffer value on the NetStream. If * useFastStartBuffer has been set true, then the NetStream buffer will alternate between 0.1 * (after a NetStream.Play.Start event) and the value set by this property. * * @default 3 * * @see #useFastStartBuffer * */ public function get maxBufferLength():Number { return _maxBufferLength; } /** * @private */ public function set maxBufferLength(length:Number):void { if (length < 0.1) { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,2,""Buffer length must be > 0.1"")); } else { _maxBufferLength = length; } } /** * The bufferTime, in seconds, currently reported by the stream. This property only returns a value if the * a NetStream has been created as a result of createStream being set true. The class will attempt * to maintain the buffer at the value defined by maxBufferLength. * * @see #createStream */ public function get bufferTime():Number { return _streamEstablished ? _ns.bufferTime : -1; } /** * Defines whether the current stream is a live stream. Playback of live streams requires a subscription process * to be managed by the class and is handled differently from on-demand streams. * * @default false */ public function get isLive():Boolean { return _isLive; } /** * @private */ public function set isLive(isLive:Boolean):void { _isLive = isLive; } /** * The maximum number of seconds the class should wait before timing out while trying to locate a live stream * on the network. This time begins decrementing the moment a play request is made against a live * stream, or after the class receives an onUnpublish event while still playing a live stream, in which case it * attempts to automatically reconnect. After this master time out has been triggered, the class will issue * an Error event #9. * * @default 3600 */ public function get liveStreamMasterTimeout():Number { return _liveStreamMasterTimeout / 1000; } /** * @private */ public function set liveStreamMasterTimeout(numOfSeconds:Number):void { _liveStreamMasterTimeout = numOfSeconds * 1000; _liveStreamTimer.delay = _liveStreamMasterTimeout; } /** * Initiates a new bandwidth measurement. Note that the player for the Apple® Mac OS® operating system has a bug when detecting bandwidth on * the latest Akamai network, so the class will call the old bandwidth detection methods when dealing with this client. * To recover the estimated bandwidth value, wait for the AkamaiNotificationEvent.BANDWIDTH event and then inspect * the bandwidth property.

* (Apple® and Mac OS® are trademarks of Apple Inc., registered in the U.S. and other countries. Use of * these marks is for information purposes only and is not intended to imply endorsement by Apple of * Akamai products or services). * * @returns true if the connection has been established, otherwise false. */ public function detectBandwidth():Boolean { if (_connectionEstablished) { if (Capabilities.version.indexOf(""MAC"") != -1) { _nc.expectBWDone = true; _nc.call(""checkBandwidth"",null); } else { // try the new bandwidth method first _nc.call(""_checkbw"",null); } } return _connectionEstablished } /** * Determines whether the class should create and manage a NetStream, in addition to establishing a NetConnection * with the Akamai Streaming service. * * @default false */ public function get createStream():Boolean { return _createStream; } /** * @private */ public function set createStream(create:Boolean):void { _createStream = create; } /** * Returns a reference to the active NetConnection object. This property will * only return a valid reference if the connection was successful. Use this property to obtain * access to NetConnection properties and methods that are not proxied by this class. * * @returns the NetConnection object, or null if the connection was unsuccessful. */ public function get netConnection():NetConnection { return _connectionEstablished ? NetConnection(_nc) : null; } /** * Returns a reference to the active NetStream object. This property will * only return a valid reference if createStream was set true prior * to connect being called. * * @returns the NetStream object, or null if the NetStream was not established. * * @see #createStream */ public function get netStream():NetStream { return _streamEstablished ? _ns : null; } /** * Returns frames per second of the current NetStream. * */ public function get fps():Number { return _streamEstablished ? _ns.currentFPS : -1; } /** * Returns the number of seconds of data in the subscribing stream's buffer in live (unbuffered) mode. * This property will only return a valid reference if createStream was set true prior * to connect being called and the stream being played is a live stream. * * @see #createStream * @see #isLive */ public function get liveDelay():Number { return (_streamEstablished && _isLive) ? _ns.liveDelay : -1; } /** * Primary method for playing content on the active NetStream, if it exists. The stream name parameter should * not include the file type extension. Examples of valid stream names include:

    *
  • myfile
  • *
  • myfolder/myfile
  • *
  • myfolder/mp3:myfile
  • *
* Examples of invalid stream names include: *
    *
  • myfile.flv
  • *
  • myfolder/myfile.flv
  • *
  • myfolder/myfile.mp3
  • *
* * @param the name of the stream to play. */ public function play(name:String):void { if (_streamEstablished) { _isPaused = false; if (_isLive) { _pendingLiveStreamName = name; _playingLiveStream = true; _successfullySubscribed = false; startLiveStream(); } else { _playingLiveStream = false; _ns.play(name,0); } } else { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,8,""Cannot play, pause, seek or resume since the stream is not defined"")); } } /** * Pauses the active netStream, if it exists. */ public function pause():void { if (_streamEstablished) { _ns.pause(); _isPaused = true; } else { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,8,""Cannot play, pause, seek or resume since the stream is not defined"")); } } /** * Resumes the active netStream, if it exists. */ public function resume():void { if (_streamEstablished) { _ns.resume(); _isPaused = false; } else { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,8,""Cannot play, pause, seek or resume since the stream is not defined"")); } } /** * Seeks the active NetStream to a specific offset, if the NetStream exists. * * @param the time value, in seconds, to which to seek. */ public function seek(offset:Number):void { if (_streamEstablished) { _ns.seek(offset); } else { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,8,""Cannot play, pause, seek or resume since the stream is not defined"")); } } /** * Initiates the process of unsubscribing from the active live NetStream. This method can only be called if * the class is currently subscribed to a live stream. Since unsubscription is an asynchronous * process, confirmation of a successful unsubscription is delivered via the AkamaiNotificationEvent.UNSUBSCRIBED event. * * @return true if previously subscribed, otherwise false. */ public function unsubscribe():Boolean { if (_successfullySubscribed) { resetAllLiveTimers(); _playingLiveStream = false; _ns.play(false); _nc.call(""FCUnsubscribe"",null,_pendingLiveStreamName); return true; } else { return false; } } /** * The volume of the current NetStream. Possible volume values lie between 0 (silent) and 1 (full volume). * * @default 1 */ public function get volume():Number { return _volume; } /** * @private */ public function set volume(vol:Number):void { if (vol < 0 || vol > 1) { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,11,""Volume value out of range"")); } else { _volume = vol; if (_streamEstablished) { _ns.soundTransform = (new SoundTransform(_volume,_panning)); } } } /** * The panning of the current NetStream. Possible volume values lie between -1 (full left) to 1 (full right). * * @default 0 */ public function get panning():Number { return _panning; } /** * @private */ public function set panning(panning:Number):void { if (panning < -1 || panning > 1) { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,11,""Invalid volume parameters(s)"")); } else { _panning = panning; if (_streamEstablished) { _ns.soundTransform = (new SoundTransform(_volume,_panning)); } } } /** * Returns the current time of the stream, in seconds. This property will only return a valid * value if the NetStream has been established. */ public function get time():Number { return _streamEstablished ? _ns.time : -1; } /** * Returns the current time of the stream, as timecode HH:MM:SS. This property will only return a valid * value if the NetStream has been established. */ public function get timeAsTimeCode():String { return _streamEstablished ? timeCode(_ns.time) : null; } /** * Initiates the server request to measure the stream length of a file. Since this measurement is an asynchronous * process, the stream length value can retrieved by calling the streamLength method after receiving * the AkamaiNotificationEvent.STREAM_LENGTH event. Note that the name of the file being measured is * decoupled from the file being played, meaning that you can request the length of one file while playing another. * * @param the name of the file for which length is to be requested. * * @see #streamLength */ public function requestStreamLength(filename:String):Boolean { if (!_connectionEstablished || _isLive || filename == """") { return false; } else { _streamLength = undefined; // if the filename includes parameters, strip them off, since the server canot handle them. _nc.call(""getStreamLength"",new Responder(onStreamLengthResult,onStreamLengthFault),filename.indexOf(""?"") != -1 ? filename.slice(0,filename.indexOf(""?"")) : filename); return true; } } /** * Returns the stream length (duration) in seconds of the file specified by the last request to requestStreamLength. * This method can only be called after the AkamaiNotificationEvent.BANDWIDTH event has been received. * * @return the length in seconds of the file */ public function get streamLength():Number { return _streamLength; } /** * Returns the stream length (duration) in timecode HH:MM:SS format, of the file specified by the last request to * requestStreamLength. This method can only be called after the * AkamaiNotificationEvent.BANDWIDTH event has been received. * * @return the length as timecode HH:MM:SS */ public function get streamLengthAsTimeCode():String { return _streamEstablished ? timeCode(_streamLength) : null; } /** * Initiates the process of extracting the ID3 information from an MP3 file. Since this process is asynchronous, * the actual ID3 metadata is retrieved by listening for the AkamaiStatusEvent.MP3_ID3 and inspecting the info parameter. * * @return false if the NetConnection has not yet defined, otherwise true. */ public function getMp3Id3Info(filename:String):Boolean { if (!_connectionEstablished) { return false; } else { if (!(_nsId3 is NetStream)) { _nsId3 = new NetStream(_nc); _nsId3.client = this; _nsId3.addEventListener(Event.ID3,onId3); } if (filename.slice(0,4) == ""mp3:"" || filename.slice(0,4) == ""id3:"") { filename = filename.slice(4); } _nsId3.play(""id3:"" + filename); return true; } } /** * Dictates whether a fast start (dual buffer) strategy should be used. A fast start buffer means that the * NetStream buffer is set to value of 0.1 seconds after a NetStream.Play.Start or NetStream.Buffer.Empty event * and then to maxBufferLength after the NetStream.Buffer.Full event is received. This gives the advantages of a * fast stream start combined with a robust buffer for long-term bandwidth. Users whose connections * are close to the bitrate of the stream may see very rapid stuttering of the stream with * this approach, so it is best deployed in situations in which each users' bandwidth is several multiples * of the streaming files' bitrate. * * @see maxBufferLength */ public function get useFastStartBuffer():Boolean { return _useFastStartBuffer; } /** * @private */ public function set useFastStartBuffer(b:Boolean):void { _useFastStartBuffer = b; if (!b) { _ns.bufferTime = _maxBufferLength; } } /** * Closes the NetConnection and NetStream instances, if they exist. * After calling this method, the API will cease to function, so this method * should be the last method that is called when interacting with the class. * */ public function close():void { if (_streamEstablished) { _ns.close(); _streamEstablished = false; } if (_connectionEstablished) { _nc.close(); _connectionEstablished = false; } } /** * Used internally by the class * @private */ public function onId3( info:Object ):void { dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.MP3_ID3,info)); } /** * Catches netstream onTranstion events * @private */ public function onTransition(info:Object,... args):void { // no action is currently taken } /** Catches netstream onPlayStatus events * @private */ public function onPlayStatus(info:Object):void { dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.NETSTREAM_PLAYSTATUS,info)); } /** Catches netstream onMetaData events * @private */ public function onMetaData(info:Object):void { dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.NETSTREAM_METADATA,info)); } /** Catches netstream cuepoint events * @private */ public function onCuePoint(info:Object):void { dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.NETSTREAM_CUEPOINT,info)); } /** Sets default values for certain variables * @private */ private function initVars():void { _createStream = false; _maxBufferLength = 3; _volume = 1; _panning = 0; _liveStreamMasterTimeout = 3600000; _useFastStartBuffer = false; _port = ""any""; _protocol = ""any""; _isLive = false; _authParams = """"; } /** Handles the responder result from a streamlength request. * @private */ private function onStreamLengthResult(streamLength:Number):void { _streamLength = streamLength; dispatchEvent(new AkamaiNotificationEvent(AkamaiNotificationEvent.STREAM_LENGTH)); } /** Handles the responder fault after a streamlength request * @private */ private function onStreamLengthFault():void { _streamLength = undefined; dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,10,""Error requesting stream length"")) } /** Catches IO errors when requesting IDENT xml * @private */ private function catchIOError(event:IOErrorEvent):void { dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,5,""Unable to load XML data from ident request"")); } /** Handles the XML return from the IDENT request * @private */ private function akamaiXMLLoaded(event:Event):void { _ip = XML(_akLoader.data).ip; buildConnectionSequence(); } /** Builds an array of connection strings and starts connecting * @private */ private function buildConnectionSequence():void { var aPortProtocol:Array = buildPortProtocolSequence(); _aConnections = new Array(); _aNC = new Array(); for (var a:uint = 0;a < aPortProtocol.length; a++) { var connectionObject:Object = new Object(); var address:String = aPortProtocol[a].protocol + ""://"" + _ip + "":"" + aPortProtocol[a].port + ""/"" + _appName + ""?_fcs_vhost="" + _hostName + (_authParams == """" ? """" : ""&"" + _authParams); connectionObject.address = address; connectionObject.port = aPortProtocol[a].port; connectionObject.protocol = aPortProtocol[a].protocol; _aConnections.push(connectionObject); } _timeOutTimer.reset(); _timeOutTimer.start(); _connectionAttempt = 0; _connectionTimer.reset(); _connectionTimer.delay = _authParams == """" ? 200 : 350; _connectionTimer.start(); tryToConnect(null); } /** Attempts to connect to FMS using a particular connection string * @private */ private function tryToConnect(evt:TimerEvent):void { _aNC[_connectionAttempt] = new AkamaiNetConnection(); _aNC[_connectionAttempt].addEventListener(NetStatusEvent.NET_STATUS,netStatus); _aNC[_connectionAttempt].addEventListener(SecurityErrorEvent.SECURITY_ERROR,netSecurityError); _aNC[_connectionAttempt].addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncError); _aNC[_connectionAttempt].addEventListener(AkamaiNotificationEvent.BANDWIDTH,bubbleNotificationEvent); _aNC[_connectionAttempt].addEventListener(AkamaiStatusEvent.FCSUBSCRIBE,onFCSubscribe); _aNC[_connectionAttempt].addEventListener(AkamaiStatusEvent.FCUNSUBSCRIBE,onFCUnsubscribe); _aNC[_connectionAttempt].client = _aNC[_connectionAttempt]; _aNC[_connectionAttempt].index = _connectionAttempt; _aNC[_connectionAttempt].expectBWDone = false; _aNC[_connectionAttempt].port = _aConnections[_connectionAttempt].port; _aNC[_connectionAttempt].protocol = _aConnections[_connectionAttempt].protocol; _aNC[_connectionAttempt].connection = this; try { _aNC[_connectionAttempt].connect(_aConnections[_connectionAttempt].address,false); } catch (error:Error) { // the connectionTimer will time out and report an error. } finally { _connectionAttempt++; if (_connectionAttempt >= _aConnections.length) { _connectionTimer.stop(); } } } /** Catches events from the AkamaiNetConnection instance and bubbles them upward. * @private */ private function bubbleNotificationEvent(e:AkamaiNotificationEvent):void { dispatchEvent(new AkamaiNotificationEvent(e.type)); } /** Handles the onFCSubscribe call from the server * @private */ private function onFCSubscribe(e:AkamaiStatusEvent):void { switch (e.info.code) { case ""NetStream.Play.Start"" : resetAllLiveTimers(); _successfullySubscribed = true; dispatchEvent(new AkamaiNotificationEvent(AkamaiNotificationEvent.SUBSCRIBED)); _ns.play(_pendingLiveStreamName,-1); if (_isPaused) { _ns.pause(); } break; case ""NetStream.Play.StreamNotFound"" : _liveStreamRetryTimer.reset(); _liveStreamRetryTimer.start(); break; } } /** Handles the onFCUnsubscribe call from the server * @private */ private function onFCUnsubscribe(e:AkamaiStatusEvent):void { switch (e.info.code) { case ""NetStream.Play.Stop"": _successfullySubscribed = false; dispatchEvent(new AkamaiNotificationEvent(AkamaiNotificationEvent.UNSUBSCRIBED)) if (_playingLiveStream) { startLiveStream(); } break; } } /** Notifies the parent that the stream has been unsubscribed * @private */ private function unsubscribedFromStream(e:AkamaiStatusEvent):void { dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.FCUNSUBSCRIBE,e.info)); } /** Handles all status events from the NetConnections * @private */ private function netStatus(event:NetStatusEvent):void { if (_connectionEstablished) { // only dispatch netconnection events once we have a good connection, otherwise // the user receives all the close() events when the parallel unused connection attempts // are shut down dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.NETCONNECTION,event.info)); } switch (event.info.code) { case ""NetConnection.Connect.Rejected"": handleRejection(); break; case ""NetConnection.Call.Failed"": if (event.info.description.indexOf(""_checkbw"") != -1) { event.target.expectBWDone = true; event.target.call(""checkBandwidth"",null); } break; case ""NetConnection.Connect.Success"": _timeOutTimer.stop(); _connectionTimer.stop(); for (var i:uint = 0;i < _aNC.length; i++) { if (i != event.target.index) { _aNC[i].close(); _aNC[i] = null; } } _nc = AkamaiNetConnection(event.target); if (_createStream) { setupStream(); } else { handleGoodConnect(); } break; } } /** Assembles the array of ports and protocols to be attempted * @private */ private function buildPortProtocolSequence():Array { var aTemp:Array = new Array(); if (_port == ""any"" && _protocol == ""any"") { aTemp.push({port:""1935"",protocol:""rtmp""}); aTemp.push({port:""80"",protocol:""rtmp""}); aTemp.push({port:""443"",protocol:""rtmp""}); aTemp.push({port:""80"",protocol:""rtmpt""}); aTemp.push({port:""1935"",protocol:""rtmpt""}); aTemp.push({port:""443"",protocol:""rtmpt""}); } else if (_port == ""any"" && _protocol != ""any"") { aTemp.push({port:""1935"",protocol:_protocol}); aTemp.push({port:""80"",protocol:_protocol}); aTemp.push({port:""443"",protocol:_protocol}); } else if (_protocol == ""any"" && _port != ""any"") { aTemp.push({port:_port,protocol:""rtmp""}); aTemp.push({port:_port,protocol:""rtmpt""}); } else { aTemp.push({port:_port,protocol:_protocol}); } return aTemp; } /** Catches the master timeout when no connections have succeeded within TIMEOUT. * @private */ private function masterTimeout(evt:Event):void { for (var i:uint = 0;i < _aNC.length; i++) { _aNC[i].close(); _aNC[i] = null; } dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,6,""Timed-out while trying to connect"")); } /** Handles the case when the server rejects the connection * @private */ private function handleRejection():void { _timeOutTimer.stop(); _connectionTimer.stop(); for (var i:uint = 0;i < _aNC.length; i++) { _aNC[i].close(); _aNC[i] = null; } dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,13,""Connection attempt rejected by server"")); } /** Catches any netconnection net security errors * @private */ private function netSecurityError(event:SecurityErrorEvent):void { // no action currently taken } /** Catches any async errors * @private */ private function asyncError(event:AsyncErrorEvent):void { } /** Creates the NetStream * @private */ private function setupStream():void { _ns = new NetStream(_nc); _ns.bufferTime = _useFastStartBuffer ? 0.1 : _maxBufferLength; _ns.addEventListener(NetStatusEvent.NET_STATUS,streamStatus); _ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncError); _ns.client = this; _ns.soundTransform = new SoundTransform(_volume,_panning); _streamEstablished = true; handleGoodConnect(); } /** Handles NetStream status events * @private */ private function streamStatus(event:NetStatusEvent):void { dispatchEvent(new AkamaiStatusEvent(AkamaiStatusEvent.NETSTREAM,event.info)); if (_useFastStartBuffer) { if (event.info.code == ""NetStream.Play.Start"" || event.info.code == ""NetStream.Buffer.Empty"") { _ns.bufferTime = 0.1; } if (event.info.code == ""NetStream.Buffer.Full"") { _ns.bufferTime = _maxBufferLength; } } switch(event.info.code) { case ""NetStream.Play.Start"": _aboutToStop = false; break; case ""NetStream.Play.Stop"": _aboutToStop = true; break; case ""NetStream.Buffer.Empty"": if (_aboutToStop) { _aboutToStop = false; handleEnd(); } break; case ""NetStream.Play.StreamNotFound"": dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,7,""Stream not found"")); break; } } /** Handles a successful connection * @private */ private function handleGoodConnect():void { _connectionEstablished = true; dispatchEvent(new AkamaiNotificationEvent(AkamaiNotificationEvent.CONNECTED)); } /** Handles the detection of the end of a stream for FCS 1.7x servers which do * not issue the NetStream.onPlayStatus.Complete event * @private */ private function handleEnd():void { dispatchEvent(new AkamaiNotificationEvent(AkamaiNotificationEvent.END_OF_STREAM)); } /** Catches the timeout when a live stream has been requested but cannot be found on the server * @private */ private function liveStreamTimeout(e:TimerEvent):void { resetAllLiveTimers(); dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,9,""Timed-out trying to find the live stream"")); } /** Utility funciton for generating time code * @private */ private function timeCode(sec:Number):String { var h:Number = Math.floor(sec / 3600); var m:Number = Math.floor((sec % 3600) / 60); var s:Number = Math.floor((sec % 3600) % 60); return (h == 0 ? """" : (h < 10 ? ""0"" + h.toString() + "":"" : h.toString() + "":"")) + (m < 10 ? ""0"" + m.toString() : m.toString()) + "":"" + (s < 10 ? ""0"" + s.toString() : s.toString()); } /** Begins subscription to a live stream * @private */ private function startLiveStream():void { resetAllLiveTimers(); _liveStreamTimer.start(); fcsubscribe(); } /** Calls FCsubscribe on the netconnection * @private */ private function fcsubscribe():void { dispatchEvent(new AkamaiNotificationEvent(AkamaiNotificationEvent.SUBSCRIBE_ATTEMPT)); _nc.call(""FCSubscribe"",null,_pendingLiveStreamName); _liveFCSubscribeTimer.reset(); _liveFCSubscribeTimer.start(); } /** Handles the FCSubscribe retry * @private */ private function retrySubscription(e:TimerEvent):void { fcsubscribe(); } /** Handles a non-responsive FCSubscribe method on the server * @private */ private function liveFCSubscribeTimeout():void { resetAllLiveTimers(); dispatchEvent(new AkamaiErrorEvent(AkamaiErrorEvent.ERROR,12,""Network failure - unable to play the live stream"")); } /** Utility method to reset all timers used in live stream subscription. * @private */ private function resetAllLiveTimers():void { _liveStreamTimer.reset(); _liveStreamRetryTimer.reset(); _liveFCSubscribeTimer.reset(); } /** Prepare all the timers that will be used by the class * @private */ private function initializeTimers():void { // Master connection timeout _timeOutTimer = new Timer(TIMEOUT,1); _timeOutTimer.addEventListener(TimerEvent.TIMER_COMPLETE,masterTimeout); // Controls the delay between each connection attempt _connectionTimer = new Timer(200); _connectionTimer.addEventListener(TimerEvent.TIMER,tryToConnect); // Master live stream timeout _liveStreamTimer = new Timer(_liveStreamMasterTimeout,1); _liveStreamTimer.addEventListener(TimerEvent.TIMER_COMPLETE,liveStreamTimeout); // Timeout when waiting for a response from FCSubscribe _liveFCSubscribeTimer = new Timer(LIVE_ONFCSUBSCRIBE_TIMEOUT,1); _liveFCSubscribeTimer.addEventListener(TimerEvent.TIMER_COMPLETE,liveFCSubscribeTimeout); // Retry interval when calling fcsubscribe _liveStreamRetryTimer = new Timer(LIVE_RETRY_INTERVAL,1); _liveStreamRetryTimer.addEventListener(TimerEvent.TIMER_COMPLETE,retrySubscription); } } }",12309,False,2339.6648727251886,median "CLASS zcl_abapgit_repo DEFINITION PUBLIC ABSTRACT CREATE PUBLIC . PUBLIC SECTION. METHODS bind_listener IMPORTING !ii_listener TYPE REF TO zif_abapgit_repo_listener . METHODS deserialize_checks RETURNING VALUE(rs_checks) TYPE zif_abapgit_definitions=>ty_deserialize_checks RAISING zcx_abapgit_exception . METHODS delete_checks RETURNING VALUE(rs_checks) TYPE zif_abapgit_definitions=>ty_delete_checks RAISING zcx_abapgit_exception . METHODS constructor IMPORTING !is_data TYPE zif_abapgit_persistence=>ty_repo . METHODS get_key RETURNING VALUE(rv_key) TYPE zif_abapgit_persistence=>ty_value . METHODS get_name RETURNING VALUE(rv_name) TYPE string RAISING zcx_abapgit_exception . METHODS get_files_local IMPORTING !ii_log TYPE REF TO zif_abapgit_log OPTIONAL !it_filter TYPE zif_abapgit_definitions=>ty_tadir_tt OPTIONAL RETURNING VALUE(rt_files) TYPE zif_abapgit_definitions=>ty_files_item_tt RAISING zcx_abapgit_exception . METHODS get_local_checksums_per_file RETURNING VALUE(rt_checksums) TYPE zif_abapgit_definitions=>ty_file_signatures_tt . METHODS get_files_remote RETURNING VALUE(rt_files) TYPE zif_abapgit_definitions=>ty_files_tt RAISING zcx_abapgit_exception . METHODS get_package RETURNING VALUE(rv_package) TYPE zif_abapgit_persistence=>ty_repo-package . METHODS get_dot_abapgit RETURNING VALUE(ro_dot_abapgit) TYPE REF TO zcl_abapgit_dot_abapgit . METHODS set_dot_abapgit IMPORTING !io_dot_abapgit TYPE REF TO zcl_abapgit_dot_abapgit RAISING zcx_abapgit_exception . METHODS get_dot_apack RETURNING VALUE(ro_dot_apack) TYPE REF TO zcl_abapgit_apack_reader . METHODS deserialize IMPORTING !is_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . METHODS refresh IMPORTING !iv_drop_cache TYPE abap_bool DEFAULT abap_false RAISING zcx_abapgit_exception . METHODS update_local_checksums IMPORTING !it_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . METHODS rebuild_local_checksums RAISING zcx_abapgit_exception . METHODS find_remote_dot_abapgit RETURNING VALUE(ro_dot) TYPE REF TO zcl_abapgit_dot_abapgit RAISING zcx_abapgit_exception . METHODS find_remote_dot_apack RETURNING VALUE(ro_dot) TYPE REF TO zcl_abapgit_apack_reader RAISING zcx_abapgit_exception . METHODS is_offline RETURNING VALUE(rv_offline) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS set_files_remote IMPORTING !it_files TYPE zif_abapgit_definitions=>ty_files_tt . METHODS get_local_settings RETURNING VALUE(rs_settings) TYPE zif_abapgit_persistence=>ty_repo-local_settings . METHODS set_local_settings IMPORTING !is_settings TYPE zif_abapgit_persistence=>ty_repo-local_settings RAISING zcx_abapgit_exception . METHODS has_remote_source ABSTRACT RETURNING VALUE(rv_yes) TYPE abap_bool . METHODS status IMPORTING !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RETURNING VALUE(rt_results) TYPE zif_abapgit_definitions=>ty_results_tt RAISING zcx_abapgit_exception . METHODS switch_repo_type IMPORTING !iv_offline TYPE abap_bool RAISING zcx_abapgit_exception . METHODS create_new_log IMPORTING !iv_title TYPE string OPTIONAL RETURNING VALUE(ri_log) TYPE REF TO zif_abapgit_log . METHODS get_log RETURNING VALUE(ri_log) TYPE REF TO zif_abapgit_log . METHODS reset_log . METHODS refresh_local_object IMPORTING !iv_obj_type TYPE tadir-object !iv_obj_name TYPE tadir-obj_name RAISING zcx_abapgit_exception . METHODS refresh_local_objects RAISING zcx_abapgit_exception . METHODS reset_status . METHODS validate ABSTRACT RAISING zcx_abapgit_exception . METHODS reset ABSTRACT RAISING zcx_abapgit_exception . PROTECTED SECTION. DATA mt_local TYPE zif_abapgit_definitions=>ty_files_item_tt . DATA mt_remote TYPE zif_abapgit_definitions=>ty_files_tt . DATA mv_request_local_refresh TYPE abap_bool . DATA ms_data TYPE zif_abapgit_persistence=>ty_repo . DATA mv_request_remote_refresh TYPE abap_bool . DATA mt_status TYPE zif_abapgit_definitions=>ty_results_tt . DATA mi_log TYPE REF TO zif_abapgit_log . METHODS set_dot_apack IMPORTING !io_dot_apack TYPE REF TO zcl_abapgit_apack_reader RAISING zcx_abapgit_exception . METHODS set IMPORTING !it_checksums TYPE zif_abapgit_persistence=>ty_local_checksum_tt OPTIONAL !iv_url TYPE zif_abapgit_persistence=>ty_repo-url OPTIONAL !iv_branch_name TYPE zif_abapgit_persistence=>ty_repo-branch_name OPTIONAL !iv_head_branch TYPE zif_abapgit_persistence=>ty_repo-head_branch OPTIONAL !iv_offline TYPE zif_abapgit_persistence=>ty_repo-offline OPTIONAL !is_dot_abapgit TYPE zif_abapgit_persistence=>ty_repo-dot_abapgit OPTIONAL !is_local_settings TYPE zif_abapgit_persistence=>ty_repo-local_settings OPTIONAL !iv_deserialized_at TYPE zif_abapgit_persistence=>ty_repo-deserialized_at OPTIONAL !iv_deserialized_by TYPE zif_abapgit_persistence=>ty_repo-deserialized_by OPTIONAL !iv_switched_origin TYPE zif_abapgit_persistence=>ty_repo-switched_origin OPTIONAL RAISING zcx_abapgit_exception . METHODS reset_remote . PRIVATE SECTION. DATA mi_listener TYPE REF TO zif_abapgit_repo_listener. DATA mo_apack_reader TYPE REF TO zcl_abapgit_apack_reader. METHODS get_local_checksums RETURNING VALUE(rt_checksums) TYPE zif_abapgit_persistence=>ty_local_checksum_tt . METHODS notify_listener IMPORTING !is_change_mask TYPE zif_abapgit_persistence=>ty_repo_meta_mask RAISING zcx_abapgit_exception . METHODS build_dotabapgit_file RETURNING VALUE(rs_file) TYPE zif_abapgit_definitions=>ty_file RAISING zcx_abapgit_exception . METHODS build_apack_manifest_file RETURNING VALUE(rs_file) TYPE zif_abapgit_definitions=>ty_file RAISING zcx_abapgit_exception . METHODS update_last_deserialize RAISING zcx_abapgit_exception . METHODS check_for_restart . ENDCLASS. CLASS ZCL_ABAPGIT_REPO IMPLEMENTATION. METHOD bind_listener. mi_listener = ii_listener. ENDMETHOD. METHOD build_apack_manifest_file. DATA: lo_manifest_reader TYPE REF TO zcl_abapgit_apack_reader, ls_descriptor TYPE zif_abapgit_apack_definitions=>ty_descriptor, lo_manifest_writer TYPE REF TO zcl_abapgit_apack_writer. lo_manifest_reader = zcl_abapgit_apack_reader=>create_instance( ms_data-package ). IF lo_manifest_reader->has_manifest( ) = abap_true. ls_descriptor = lo_manifest_reader->get_manifest_descriptor( ). lo_manifest_writer = zcl_abapgit_apack_writer=>create_instance( ls_descriptor ). rs_file-path = zif_abapgit_definitions=>c_root_dir. rs_file-filename = zif_abapgit_apack_definitions=>c_dot_apack_manifest. rs_file-data = zcl_abapgit_convert=>string_to_xstring_utf8( lo_manifest_writer->serialize( ) ). rs_file-sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-blob iv_data = rs_file-data ). ENDIF. ENDMETHOD. METHOD build_dotabapgit_file. rs_file-path = zif_abapgit_definitions=>c_root_dir. rs_file-filename = zif_abapgit_definitions=>c_dot_abapgit. rs_file-data = get_dot_abapgit( )->serialize( ). rs_file-sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-blob iv_data = rs_file-data ). ENDMETHOD. METHOD check_for_restart. CONSTANTS: lc_abapgit_prog TYPE progname VALUE `ZABAPGIT`. "" If abapGit was used to update itself, then restart to avoid LOAD_PROGRAM_&_MISMATCH dumps "" because abapGit code was changed at runtime IF zcl_abapgit_ui_factory=>get_gui_functions( )->gui_is_available( ) = abap_true AND zcl_abapgit_url=>is_abapgit_repo( ms_data-url ) = abap_true AND sy-batch = abap_false AND sy-cprog = lc_abapgit_prog. MESSAGE 'abapGit was updated and will restart itself' TYPE 'I'. SUBMIT (sy-cprog). ENDIF. ENDMETHOD. METHOD constructor. ASSERT NOT is_data-key IS INITIAL. ms_data = is_data. mv_request_remote_refresh = abap_true. ENDMETHOD. METHOD create_new_log. CREATE OBJECT mi_log TYPE zcl_abapgit_log. mi_log->set_title( iv_title ). ri_log = mi_log. ENDMETHOD. METHOD delete_checks. DATA: li_package TYPE REF TO zif_abapgit_sap_package. li_package = zcl_abapgit_factory=>get_sap_package( get_package( ) ). rs_checks-transport-required = li_package->are_changes_recorded_in_tr_req( ). ENDMETHOD. METHOD deserialize. DATA: lt_updated_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt, lx_error TYPE REF TO zcx_abapgit_exception. deserialize_checks( ). IF is_checks-requirements-met = zif_abapgit_definitions=>gc_no AND is_checks-requirements-decision IS INITIAL. zcx_abapgit_exception=>raise( 'Requirements not met and undecided' ). ENDIF. IF is_checks-dependencies-met = zif_abapgit_definitions=>gc_no. zcx_abapgit_exception=>raise( 'APACK dependencies not met' ). ENDIF. IF is_checks-transport-required = abap_true AND is_checks-transport-transport IS INITIAL. zcx_abapgit_exception=>raise( |No transport request was supplied| ). ENDIF. TRY. lt_updated_files = zcl_abapgit_objects=>deserialize( io_repo = me is_checks = is_checks ii_log = ii_log ). CATCH zcx_abapgit_exception INTO lx_error. * ensure to reset default transport request task zcl_abapgit_default_transport=>get_instance( )->reset( ). RAISE EXCEPTION lx_error. ENDTRY. APPEND get_dot_abapgit( )->get_signature( ) TO lt_updated_files. CLEAR: mt_local. update_local_checksums( lt_updated_files ). update_last_deserialize( ). reset_status( ). COMMIT WORK AND WAIT. check_for_restart( ). ENDMETHOD. METHOD deserialize_checks. DATA: lt_requirements TYPE zif_abapgit_dot_abapgit=>ty_requirement_tt, lt_dependencies TYPE zif_abapgit_apack_definitions=>tt_dependencies, lv_master_language TYPE spras, lv_logon_language TYPE spras. find_remote_dot_abapgit( ). find_remote_dot_apack( ). lv_master_language = get_dot_abapgit( )->get_master_language( ). lv_logon_language = sy-langu. IF get_local_settings( )-write_protected = abap_true. zcx_abapgit_exception=>raise( 'Cannot deserialize. Local code is write-protected by repo config' ). ELSEIF lv_master_language <> lv_logon_language. zcx_abapgit_exception=>raise( |Current login language | && |'{ zcl_abapgit_convert=>conversion_exit_isola_output( lv_logon_language ) }'| && | does not match master language | && |'{ zcl_abapgit_convert=>conversion_exit_isola_output( lv_master_language ) }'.| && | Run 'Advanced' > 'Open in master language'| ). ENDIF. rs_checks = zcl_abapgit_objects=>deserialize_checks( me ). lt_requirements = get_dot_abapgit( )->get_data( )-requirements. rs_checks-requirements-met = zcl_abapgit_requirement_helper=>is_requirements_met( lt_requirements ). lt_dependencies = get_dot_apack( )->get_manifest_descriptor( )-dependencies. rs_checks-dependencies-met = zcl_abapgit_apack_helper=>are_dependencies_met( lt_dependencies ). ENDMETHOD. METHOD find_remote_dot_abapgit. FIELD-SYMBOLS: LIKE LINE OF mt_remote. get_files_remote( ). READ TABLE mt_remote ASSIGNING WITH KEY path = zif_abapgit_definitions=>c_root_dir filename = zif_abapgit_definitions=>c_dot_abapgit. IF sy-subrc = 0. ro_dot = zcl_abapgit_dot_abapgit=>deserialize( -data ). set_dot_abapgit( ro_dot ). COMMIT WORK AND WAIT. "" to release lock ELSEIF lines( mt_remote ) > 3. "" Less files means it's a new repo (with just readme and license, for example) which is ok zcx_abapgit_exception=>raise( |Cannot find .abapgit.xml - Is this an abapGit repo?| ). ENDIF. ENDMETHOD. METHOD find_remote_dot_apack. FIELD-SYMBOLS: LIKE LINE OF mt_remote. get_files_remote( ). READ TABLE mt_remote ASSIGNING WITH KEY path = zif_abapgit_definitions=>c_root_dir filename = zif_abapgit_apack_definitions=>c_dot_apack_manifest. IF sy-subrc = 0. ro_dot = zcl_abapgit_apack_reader=>deserialize( iv_package_name = ms_data-package iv_xstr = -data ). set_dot_apack( ro_dot ). ENDIF. ENDMETHOD. METHOD get_dot_abapgit. CREATE OBJECT ro_dot_abapgit EXPORTING is_data = ms_data-dot_abapgit. ENDMETHOD. METHOD get_dot_apack. IF mo_apack_reader IS NOT BOUND. mo_apack_reader = zcl_abapgit_apack_reader=>create_instance( ms_data-package ). ENDIF. ro_dot_apack = mo_apack_reader. ENDMETHOD. METHOD get_files_local. DATA: lo_filter TYPE REF TO zcl_abapgit_repo_filter, lt_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt, lo_serialize TYPE REF TO zcl_abapgit_serialize, lt_found LIKE rt_files, lv_force TYPE abap_bool, ls_apack_file TYPE zif_abapgit_definitions=>ty_file. FIELD-SYMBOLS: LIKE LINE OF rt_files. "" Serialization happened before and no refresh request IF lines( mt_local ) > 0 AND mv_request_local_refresh = abap_false. rt_files = mt_local. RETURN. ENDIF. APPEND INITIAL LINE TO rt_files ASSIGNING . -file = build_dotabapgit_file( ). ls_apack_file = build_apack_manifest_file( ). IF ls_apack_file IS NOT INITIAL. APPEND INITIAL LINE TO rt_files ASSIGNING . -file = ls_apack_file. ENDIF. lt_tadir = zcl_abapgit_factory=>get_tadir( )->read( iv_package = get_package( ) iv_ignore_subpackages = get_local_settings( )-ignore_subpackages iv_only_local_objects = get_local_settings( )-only_local_objects io_dot = get_dot_abapgit( ) ii_log = ii_log ). CREATE OBJECT lo_filter EXPORTING iv_package = get_package( ). lo_filter->apply( EXPORTING it_filter = it_filter CHANGING ct_tadir = lt_tadir ). CREATE OBJECT lo_serialize EXPORTING iv_serialize_master_lang_only = ms_data-local_settings-serialize_master_lang_only. * if there are less than 10 objects run in single thread * this helps a lot when debugging, plus performance gain * with low number of objects does not matter much lv_force = boolc( lines( lt_tadir ) < 10 ). lt_found = lo_serialize->serialize( it_tadir = lt_tadir iv_language = get_dot_abapgit( )->get_master_language( ) ii_log = ii_log iv_force_sequential = lv_force ). APPEND LINES OF lt_found TO rt_files. mt_local = rt_files. mv_request_local_refresh = abap_false. "" Fulfill refresh ENDMETHOD. METHOD get_files_remote. rt_files = mt_remote. ENDMETHOD. METHOD get_key. rv_key = ms_data-key. ENDMETHOD. METHOD get_local_checksums. rt_checksums = ms_data-local_checksums. ENDMETHOD. METHOD get_local_checksums_per_file. FIELD-SYMBOLS LIKE LINE OF ms_data-local_checksums. LOOP AT ms_data-local_checksums ASSIGNING . "" Check if item exists READ TABLE mt_local TRANSPORTING NO FIELDS WITH KEY item = -item. IF sy-subrc = 0. APPEND LINES OF -files TO rt_checksums. ENDIF. ENDLOOP. ENDMETHOD. METHOD get_local_settings. rs_settings = ms_data-local_settings. ENDMETHOD. METHOD get_log. ri_log = mi_log. ENDMETHOD. METHOD get_name. rv_name = ms_data-local_settings-display_name. ENDMETHOD. METHOD get_package. rv_package = ms_data-package. ENDMETHOD. METHOD is_offline. rv_offline = ms_data-offline. ENDMETHOD. METHOD notify_listener. DATA ls_meta_slug TYPE zif_abapgit_persistence=>ty_repo_xml. IF mi_listener IS BOUND. MOVE-CORRESPONDING ms_data TO ls_meta_slug. mi_listener->on_meta_change( iv_key = ms_data-key is_meta = ls_meta_slug is_change_mask = is_change_mask ). ENDIF. ENDMETHOD. METHOD rebuild_local_checksums. DATA: lt_local TYPE zif_abapgit_definitions=>ty_files_item_tt, ls_last_item TYPE zif_abapgit_definitions=>ty_item, lt_checksums TYPE zif_abapgit_persistence=>ty_local_checksum_tt. FIELD-SYMBOLS: LIKE LINE OF lt_checksums, LIKE LINE OF -files, LIKE LINE OF lt_local. lt_local = get_files_local( ). DELETE lt_local "" Remove non-code related files except .abapgit WHERE item IS INITIAL AND NOT ( file-path = zif_abapgit_definitions=>c_root_dir AND file-filename = zif_abapgit_definitions=>c_dot_abapgit ). SORT lt_local BY item. LOOP AT lt_local ASSIGNING . IF ls_last_item <> -item OR sy-tabix = 1. "" First or New item reached ? APPEND INITIAL LINE TO lt_checksums ASSIGNING . -item = -item. ls_last_item = -item. ENDIF. APPEND INITIAL LINE TO -files ASSIGNING . MOVE-CORRESPONDING -file TO . ENDLOOP. set( it_checksums = lt_checksums ). reset_status( ). ENDMETHOD. METHOD refresh. mv_request_local_refresh = abap_true. reset_remote( ). CLEAR mi_log. IF iv_drop_cache = abap_true. CLEAR: mt_local. ENDIF. ENDMETHOD. METHOD refresh_local_object. DATA: ls_tadir TYPE zif_abapgit_definitions=>ty_tadir, lt_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt, lt_new_local_files TYPE zif_abapgit_definitions=>ty_files_item_tt, lo_serialize TYPE REF TO zcl_abapgit_serialize. lt_tadir = zcl_abapgit_factory=>get_tadir( )->read( iv_package = ms_data-package io_dot = get_dot_abapgit( ) ). DELETE mt_local WHERE item-obj_type = iv_obj_type AND item-obj_name = iv_obj_name. READ TABLE lt_tadir INTO ls_tadir WITH KEY object = iv_obj_type obj_name = iv_obj_name. IF sy-subrc <> 0 OR ls_tadir-delflag = abap_true. "" object doesn't exist anymore, nothing todo here RETURN. ENDIF. CLEAR lt_tadir. INSERT ls_tadir INTO TABLE lt_tadir. CREATE OBJECT lo_serialize. lt_new_local_files = lo_serialize->serialize( lt_tadir ). INSERT LINES OF lt_new_local_files INTO TABLE mt_local. ENDMETHOD. METHOD refresh_local_objects. mv_request_local_refresh = abap_true. get_files_local( ). ENDMETHOD. METHOD reset_log. CLEAR mi_log. ENDMETHOD. METHOD reset_remote. CLEAR mt_remote. mv_request_remote_refresh = abap_true. reset_status( ). ENDMETHOD. METHOD reset_status. CLEAR mt_status. ENDMETHOD. METHOD set. * TODO: refactor, maybe use zcl_abapgit_string_map ? DATA: ls_mask TYPE zif_abapgit_persistence=>ty_repo_meta_mask. ASSERT it_checksums IS SUPPLIED OR iv_url IS SUPPLIED OR iv_branch_name IS SUPPLIED OR iv_head_branch IS SUPPLIED OR iv_offline IS SUPPLIED OR is_dot_abapgit IS SUPPLIED OR is_local_settings IS SUPPLIED OR iv_deserialized_by IS SUPPLIED OR iv_deserialized_at IS SUPPLIED OR iv_switched_origin IS SUPPLIED. IF it_checksums IS SUPPLIED. ms_data-local_checksums = it_checksums. ls_mask-local_checksums = abap_true. ENDIF. IF iv_url IS SUPPLIED. ms_data-url = iv_url. ls_mask-url = abap_true. ENDIF. IF iv_branch_name IS SUPPLIED. ms_data-branch_name = iv_branch_name. ls_mask-branch_name = abap_true. ENDIF. IF iv_head_branch IS SUPPLIED. ms_data-head_branch = iv_head_branch. ls_mask-head_branch = abap_true. ENDIF. IF iv_offline IS SUPPLIED. ms_data-offline = iv_offline. ls_mask-offline = abap_true. ENDIF. IF is_dot_abapgit IS SUPPLIED. ms_data-dot_abapgit = is_dot_abapgit. ls_mask-dot_abapgit = abap_true. ENDIF. IF is_local_settings IS SUPPLIED. ms_data-local_settings = is_local_settings. ls_mask-local_settings = abap_true. ENDIF. IF iv_deserialized_at IS SUPPLIED OR iv_deserialized_by IS SUPPLIED. ms_data-deserialized_at = iv_deserialized_at. ms_data-deserialized_by = iv_deserialized_by. ls_mask-deserialized_at = abap_true. ls_mask-deserialized_by = abap_true. ENDIF. IF iv_switched_origin IS SUPPLIED. ms_data-switched_origin = iv_switched_origin. ls_mask-switched_origin = abap_true. ENDIF. notify_listener( ls_mask ). ENDMETHOD. METHOD set_dot_abapgit. set( is_dot_abapgit = io_dot_abapgit->get_data( ) ). ENDMETHOD. METHOD set_dot_apack. get_dot_apack( ). mo_apack_reader->set_manifest_descriptor( io_dot_apack->get_manifest_descriptor( ) ). ENDMETHOD. METHOD set_files_remote. mt_remote = it_files. mv_request_remote_refresh = abap_false. ENDMETHOD. METHOD set_local_settings. set( is_local_settings = is_settings ). ENDMETHOD. METHOD status. IF lines( mt_status ) = 0. mt_status = zcl_abapgit_file_status=>status( io_repo = me ii_log = ii_log ). ENDIF. rt_results = mt_status. ENDMETHOD. METHOD switch_repo_type. IF iv_offline = ms_data-offline. zcx_abapgit_exception=>raise( |Cannot switch_repo_type, offline already = ""{ ms_data-offline }""| ). ENDIF. IF iv_offline = abap_true. "" On-line -> OFFline set( iv_url = zcl_abapgit_url=>name( ms_data-url ) iv_branch_name = '' iv_head_branch = '' iv_offline = abap_true ). ELSE. "" OFFline -> On-line set( iv_offline = abap_false ). ENDIF. ENDMETHOD. METHOD update_last_deserialize. DATA: lv_deserialized_at TYPE zif_abapgit_persistence=>ty_repo-deserialized_at, lv_deserialized_by TYPE zif_abapgit_persistence=>ty_repo-deserialized_by. GET TIME STAMP FIELD lv_deserialized_at. lv_deserialized_by = sy-uname. set( iv_deserialized_at = lv_deserialized_at iv_deserialized_by = lv_deserialized_by ). ENDMETHOD. METHOD update_local_checksums. "" ASSUMTION: SHA1 in param is actual and correct. "" Push fills it from local files before pushing, deserialize from remote "" If this is not true that there is an error somewhere but not here DATA: lt_checksums TYPE zif_abapgit_persistence=>ty_local_checksum_tt, lt_files_idx TYPE zif_abapgit_definitions=>ty_file_signatures_tt, lt_local TYPE zif_abapgit_definitions=>ty_files_item_tt, lv_chks_row TYPE i, lv_file_row TYPE i. FIELD-SYMBOLS: LIKE LINE OF lt_checksums, LIKE LINE OF -files, LIKE LINE OF lt_local, LIKE LINE OF it_files. lt_checksums = get_local_checksums( ). lt_files_idx = it_files. SORT lt_files_idx BY path filename. "" Sort for binary search "" Loop through current chacksum state, update sha1 for common files LOOP AT lt_checksums ASSIGNING . lv_chks_row = sy-tabix. LOOP AT -files ASSIGNING . lv_file_row = sy-tabix. READ TABLE lt_files_idx ASSIGNING WITH KEY path = -path filename = -filename BINARY SEARCH. CHECK sy-subrc = 0. "" Missing in param table, skip IF -sha1 IS INITIAL. "" Empty input sha1 is a deletion marker DELETE -files INDEX lv_file_row. ELSE. -sha1 = -sha1. "" Update sha1 CLEAR -sha1. "" Mark as processed ENDIF. ENDLOOP. IF lines( -files ) = 0. "" Remove empty objects DELETE lt_checksums INDEX lv_chks_row. ENDIF. ENDLOOP. DELETE lt_files_idx WHERE sha1 IS INITIAL. "" Remove processed IF lines( lt_files_idx ) > 0. lt_local = get_files_local( ). SORT lt_local BY file-path file-filename. "" Sort for binary search ENDIF. "" Add new files - not deleted and not marked as processed above LOOP AT lt_files_idx ASSIGNING . READ TABLE lt_local ASSIGNING WITH KEY file-path = -path file-filename = -filename BINARY SEARCH. IF sy-subrc <> 0. * if the deserialization fails, the local file might not be there CONTINUE. ENDIF. READ TABLE lt_checksums ASSIGNING "" TODO Optimize WITH KEY item = -item. IF sy-subrc > 0. APPEND INITIAL LINE TO lt_checksums ASSIGNING . -item = -item. ENDIF. APPEND TO -files. ENDLOOP. SORT lt_checksums BY item. set( it_checksums = lt_checksums ). ENDMETHOD. ENDCLASS. ",6757,False,1359.5988625344798,median "/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package Box2D.Dynamics{ import Box2D.Collision.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Contacts.*; import Box2D.Dynamics.Controllers.b2Controller; import Box2D.Dynamics.Controllers.b2ControllerEdge; import Box2D.Dynamics.Joints.*; use namespace b2internal; /** * The world class manages all physics entities, dynamic simulation, * and asynchronous queries. */ public class b2World { // Construct a world object. /** * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ public function b2World(gravity:b2Vec2, doSleep:Boolean){ m_destructionListener = null; m_debugDraw = null; m_bodyList = null; m_contactList = null; m_jointList = null; m_controllerList = null; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_controllerCount = 0; m_warmStarting = true; m_continuousPhysics = true; m_allowSleep = doSleep; m_gravity = gravity; m_inv_dt0 = 0.0; m_contactManager.m_world = this; var bd:b2BodyDef = new b2BodyDef(); m_groundBody = CreateBody(bd); } /** * Destruct the world. All physics entities are destroyed and all heap memory is released. */ //~b2World(); /** * Register a destruction listener. */ public function SetDestructionListener(listener:b2DestructionListener) : void{ m_destructionListener = listener; } /** * Register a contact filter to provide specific control over collision. * Otherwise the default filter is used (b2_defaultFilter). */ public function SetContactFilter(filter:b2ContactFilter) : void{ m_contactManager.m_contactFilter = filter; } /** * Register a contact event listener */ public function SetContactListener(listener:b2ContactListener) : void{ m_contactManager.m_contactListener = listener; } /** * Register a routine for debug drawing. The debug draw functions are called * inside the b2World::Step method, so make sure your renderer is ready to * consume draw commands when you call Step(). */ public function SetDebugDraw(debugDraw:b2DebugDraw) : void{ m_debugDraw = debugDraw; } /** * Use the given object as a broadphase. * The old broadphase will not be cleanly emptied. * @warning It is not recommended you call this except immediately after constructing the world. * @warning This function is locked during callbacks. */ public function SetBroadPhase(broadPhase:IBroadPhase) : void { var oldBroadPhase:IBroadPhase = m_contactManager.m_broadPhase; m_contactManager.m_broadPhase = broadPhase; for (var b:b2Body = m_bodyList; b; b = b.m_next) { for (var f:b2Fixture = b.m_fixtureList; f; f = f.m_next) { f.m_proxy = broadPhase.CreateProxy(oldBroadPhase.GetFatAABB(f.m_proxy), f); } } } /** * Perform validation of internal data structures. */ public function Validate() : void { m_contactManager.m_broadPhase.Validate(); } /** * Get the number of broad-phase proxies. */ public function GetProxyCount() : int { return m_contactManager.m_broadPhase.GetProxyCount(); } /** * Create a rigid body given a definition. No reference to the definition * is retained. * @warning This function is locked during callbacks. */ public function CreateBody(def:b2BodyDef) : b2Body{ //b2Settings.b2Assert(m_lock == false); if (IsLocked() == true) { return null; } //void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); var b:b2Body = new b2Body(def, this); // Add to world doubly linked list. b.m_prev = null; b.m_next = m_bodyList; if (m_bodyList) { m_bodyList.m_prev = b; } m_bodyList = b; ++m_bodyCount; return b; } /** * Destroy a rigid body given a definition. No reference to the definition * is retained. This function is locked during callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ public function DestroyBody(b:b2Body) : void{ //b2Settings.b2Assert(m_bodyCount > 0); //b2Settings.b2Assert(m_lock == false); if (IsLocked() == true) { return; } // Delete the attached joints. var jn:b2JointEdge = b.m_jointList; while (jn) { var jn0:b2JointEdge = jn; jn = jn.next; if (m_destructionListener) { m_destructionListener.SayGoodbyeJoint(jn0.joint); } DestroyJoint(jn0.joint); } // Detach controllers attached to this body var coe:b2ControllerEdge = b.m_controllerList; while (coe) { var coe0:b2ControllerEdge = coe; coe = coe.nextController; coe0.controller.RemoveBody(b); } // Delete the attached contacts. var ce:b2ContactEdge = b.m_contactList; while (ce) { var ce0:b2ContactEdge = ce; ce = ce.next; m_contactManager.Destroy(ce0.contact); } b.m_contactList = null; // Delete the attached fixtures. This destroys broad-phase // proxies. var f:b2Fixture = b.m_fixtureList; while (f) { var f0:b2Fixture = f; f = f.m_next; if (m_destructionListener) { m_destructionListener.SayGoodbyeFixture(f0); } f0.DestroyProxy(m_contactManager.m_broadPhase); f0.Destroy(); //f0->~b2Fixture(); //m_blockAllocator.Free(f0, sizeof(b2Fixture)); } b.m_fixtureList = null; b.m_fixtureCount = 0; // Remove world body list. if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == m_bodyList) { m_bodyList = b.m_next; } --m_bodyCount; //b->~b2Body(); //m_blockAllocator.Free(b, sizeof(b2Body)); } /** * Create a joint to constrain bodies together. No reference to the definition * is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. */ public function CreateJoint(def:b2JointDef) : b2Joint{ //b2Settings.b2Assert(m_lock == false); var j:b2Joint = b2Joint.Create(def, null); // Connect to the world list. j.m_prev = null; j.m_next = m_jointList; if (m_jointList) { m_jointList.m_prev = j; } m_jointList = j; ++m_jointCount; // Connect to the bodies' doubly linked lists. j.m_edgeA.joint = j; j.m_edgeA.other = j.m_bodyB; j.m_edgeA.prev = null; j.m_edgeA.next = j.m_bodyA.m_jointList; if (j.m_bodyA.m_jointList) j.m_bodyA.m_jointList.prev = j.m_edgeA; j.m_bodyA.m_jointList = j.m_edgeA; j.m_edgeB.joint = j; j.m_edgeB.other = j.m_bodyA; j.m_edgeB.prev = null; j.m_edgeB.next = j.m_bodyB.m_jointList; if (j.m_bodyB.m_jointList) j.m_bodyB.m_jointList.prev = j.m_edgeB; j.m_bodyB.m_jointList = j.m_edgeB; var bodyA:b2Body = def.bodyA; var bodyB:b2Body = def.bodyB; // If the joint prevents collisions, then flag any contacts for filtering. if (def.collideConnected == false ) { var edge:b2ContactEdge = bodyB.GetContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.FlagForFiltering(); } edge = edge.next; } } // Note: creating a joint doesn't wake the bodies. return j; } /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ public function DestroyJoint(j:b2Joint) : void{ //b2Settings.b2Assert(m_lock == false); var collideConnected:Boolean = j.m_collideConnected; // Remove from the doubly linked list. if (j.m_prev) { j.m_prev.m_next = j.m_next; } if (j.m_next) { j.m_next.m_prev = j.m_prev; } if (j == m_jointList) { m_jointList = j.m_next; } // Disconnect from island graph. var bodyA:b2Body = j.m_bodyA; var bodyB:b2Body = j.m_bodyB; // Wake up connected bodies. bodyA.SetAwake(true); bodyB.SetAwake(true); // Remove from body 1. if (j.m_edgeA.prev) { j.m_edgeA.prev.next = j.m_edgeA.next; } if (j.m_edgeA.next) { j.m_edgeA.next.prev = j.m_edgeA.prev; } if (j.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = j.m_edgeA.next; } j.m_edgeA.prev = null; j.m_edgeA.next = null; // Remove from body 2 if (j.m_edgeB.prev) { j.m_edgeB.prev.next = j.m_edgeB.next; } if (j.m_edgeB.next) { j.m_edgeB.next.prev = j.m_edgeB.prev; } if (j.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = j.m_edgeB.next; } j.m_edgeB.prev = null; j.m_edgeB.next = null; b2Joint.Destroy(j, null); //b2Settings.b2Assert(m_jointCount > 0); --m_jointCount; // If the joint prevents collisions, then flag any contacts for filtering. if (collideConnected == false) { var edge:b2ContactEdge = bodyB.GetContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.FlagForFiltering(); } edge = edge.next; } } } /** * Add a controller to the world list */ public function AddController(c:b2Controller) : b2Controller { c.m_next = m_controllerList; c.m_prev = null; m_controllerList = c; c.m_world = this; m_controllerCount++; return c; } public function RemoveController(c:b2Controller) : void { //TODO: Remove bodies from controller if (c.m_prev) c.m_prev.m_next = c.m_next; if (c.m_next) c.m_next.m_prev = c.m_prev; if (m_controllerList == c) m_controllerList = c.m_next; m_controllerCount--; } public function CreateController(controller:b2Controller):b2Controller { if (controller.m_world != this) throw new Error(""Controller can only be a member of one world""); controller.m_next = m_controllerList; controller.m_prev = null; if (m_controllerList) m_controllerList.m_prev = controller; m_controllerList = controller; ++m_controllerCount; controller.m_world = this; return controller; } public function DestroyController(controller:b2Controller):void { //b2Settings.b2Assert(m_controllerCount > 0); controller.Clear(); if (controller.m_next) controller.m_next.m_prev = controller.m_prev; if (controller.m_prev) controller.m_prev.m_next = controller.m_next; if (controller == m_controllerList) m_controllerList = controller.m_next; --m_controllerCount; } /** * Enable/disable warm starting. For testing. */ public function SetWarmStarting(flag: Boolean) : void { m_warmStarting = flag; } /** * Enable/disable continuous physics. For testing. */ public function SetContinuousPhysics(flag: Boolean) : void { m_continuousPhysics = flag; } /** * Get the number of bodies. */ public function GetBodyCount() : int { return m_bodyCount; } /** * Get the number of joints. */ public function GetJointCount() : int { return m_jointCount; } /** * Get the number of contacts (each may have 0 or more contact points). */ public function GetContactCount() : int { return m_contactCount; } /** * Change the global gravity vector. */ public function SetGravity(gravity: b2Vec2): void { m_gravity = gravity; } /** * Get the global gravity vector. */ public function GetGravity():b2Vec2{ return m_gravity; } /** * The world provides a single static ground body with no collision shapes. * You can use this to simplify the creation of joints and static shapes. */ public function GetGroundBody() : b2Body{ return m_groundBody; } private static var s_timestep2:b2TimeStep = new b2TimeStep(); /** * Take a time step. This performs collision detection, integration, * and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public function Step(dt:Number, velocityIterations:int, positionIterations:int) : void{ if (m_flags & e_newFixture) { m_contactManager.FindNewContacts(); m_flags &= ~e_newFixture; } m_flags |= e_locked; var step:b2TimeStep = s_timestep2; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0) { step.inv_dt = 1.0 / dt; } else { step.inv_dt = 0.0; } step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; // Update contacts. m_contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.dt > 0.0) { Solve(step); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0) { SolveTOI(step); } if (step.dt > 0.0) { m_inv_dt0 = step.inv_dt; } m_flags &= ~e_locked; } /** * Call this after you are done with time steps to clear the forces. You normally * call this after each call to Step, unless you are performing sub-steps. */ public function ClearForces() : void { for (var body:b2Body = m_bodyList; body; body = body.m_next) { body.m_force.SetZero(); body.m_torque = 0.0; } } static private var s_xf:b2Transform = new b2Transform(); /** * Call this to draw shapes and other debug draw data. */ public function DrawDebugData() : void{ if (m_debugDraw == null) { return; } m_debugDraw.m_sprite.graphics.clear(); var flags:uint = m_debugDraw.GetFlags(); var i:int; var b:b2Body; var f:b2Fixture; var s:b2Shape; var j:b2Joint; var bp:IBroadPhase; var invQ:b2Vec2 = new b2Vec2; var x1:b2Vec2 = new b2Vec2; var x2:b2Vec2 = new b2Vec2; var xf:b2Transform; var b1:b2AABB = new b2AABB(); var b2:b2AABB = new b2AABB(); var vs:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()]; // Store color here and reuse, to reduce allocations var color:b2Color = new b2Color(0, 0, 0); if (flags & b2DebugDraw.e_shapeBit) { for (b = m_bodyList; b; b = b.m_next) { xf = b.m_xf; for (f = b.GetFixtureList(); f; f = f.m_next) { s = f.GetShape(); if (b.IsActive() == false) { color.Set(0.5, 0.5, 0.3); DrawShape(s, xf, color); } else if (b.GetType() == b2Body.b2_staticBody) { color.Set(0.5, 0.9, 0.5); DrawShape(s, xf, color); } else if (b.GetType() == b2Body.b2_kinematicBody) { color.Set(0.5, 0.5, 0.9); DrawShape(s, xf, color); } else if (b.IsAwake() == false) { color.Set(0.6, 0.6, 0.6); DrawShape(s, xf, color); } else { color.Set(0.9, 0.7, 0.7); DrawShape(s, xf, color); } } } } if (flags & b2DebugDraw.e_jointBit) { for (j = m_jointList; j; j = j.m_next) { DrawJoint(j); } } if (flags & b2DebugDraw.e_controllerBit) { for (var c:b2Controller = m_controllerList; c; c = c.m_next) { c.Draw(m_debugDraw); } } if (flags & b2DebugDraw.e_pairBit) { color.Set(0.3, 0.9, 0.9); for (var contact:b2Contact = m_contactManager.m_contactList; contact; contact = contact.GetNext()) { var fixtureA:b2Fixture = contact.GetFixtureA(); var fixtureB:b2Fixture = contact.GetFixtureB(); var cA:b2Vec2 = fixtureA.GetAABB().GetCenter(); var cB:b2Vec2 = fixtureB.GetAABB().GetCenter(); m_debugDraw.DrawSegment(cA, cB, color); } } if (flags & b2DebugDraw.e_aabbBit) { bp = m_contactManager.m_broadPhase; vs = [new b2Vec2(),new b2Vec2(),new b2Vec2(),new b2Vec2()]; for (b= m_bodyList; b; b = b.GetNext()) { if (b.IsActive() == false) { continue; } for (f = b.GetFixtureList(); f; f = f.GetNext()) { var aabb:b2AABB = bp.GetFatAABB(f.m_proxy); vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); m_debugDraw.DrawPolygon(vs, 4, color); } } } if (flags & b2DebugDraw.e_centerOfMassBit) { for (b = m_bodyList; b; b = b.m_next) { xf = s_xf; xf.R = b.m_xf.R; xf.position = b.GetWorldCenter(); m_debugDraw.DrawTransform(xf); } } } /** * Query the world for all fixtures that potentially overlap the * provided AABB. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @param aabb the query box. */ public function QueryAABB(callback:Function, aabb:b2AABB):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { return callback(broadPhase.GetUserData(proxy)); } broadPhase.Query(WorldQueryWrapper, aabb); } /** * Query the world for all fixtures that precisely overlap the * provided transformed shape. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @asonly */ public function QueryShape(callback:Function, shape:b2Shape, transform:b2Transform = null):void { if (transform == null) { transform = new b2Transform(); transform.SetIdentity(); } var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { var fixture:b2Fixture = broadPhase.GetUserData(proxy) as b2Fixture if(b2Shape.TestOverlap(shape, transform, fixture.GetShape(), fixture.GetBody().GetTransform())) return callback(fixture); return true; } var aabb:b2AABB = new b2AABB(); shape.ComputeAABB(aabb, transform); broadPhase.Query(WorldQueryWrapper, aabb); } /** * Query the world for all fixtures that contain a point. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @asonly */ public function QueryPoint(callback:Function, p:b2Vec2):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { var fixture:b2Fixture = broadPhase.GetUserData(proxy) as b2Fixture if(fixture.TestPoint(p)) return callback(fixture); return true; } // Make a small box. var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(p.x - b2Settings.b2_linearSlop, p.y - b2Settings.b2_linearSlop); aabb.upperBound.Set(p.x + b2Settings.b2_linearSlop, p.y + b2Settings.b2_linearSlop); broadPhase.Query(WorldQueryWrapper, aabb); } /** * Ray-cast the world for all fixtures in the path of the ray. Your callback * Controls whether you get the closest point, any point, or n-points * The ray-cast ignores shapes that contain the starting point * @param callback A callback function which must be of signature: * function Callback(fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection * normal:b2Vec2, // The normal vector at the point of intersection * fraction:Number // The fractional length along the ray of the intersection * ):Number * * Callback should return the new length of the ray as a fraction of the original length. * By returning 0, you immediately terminate. * By returning 1, you continue with the original ray. * By returning the current fraction, you proceed to find the closest point. * @param point1 the ray starting point * @param point2 the ray ending point */ public function RayCast(callback:Function, point1:b2Vec2, point2:b2Vec2):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; var output:b2RayCastOutput = new b2RayCastOutput; function RayCastWrapper(input:b2RayCastInput, proxy:*):Number { var userData:* = broadPhase.GetUserData(proxy); var fixture:b2Fixture = userData as b2Fixture; var hit:Boolean = fixture.RayCast(output, input); if (hit) { var fraction:Number = output.fraction; var point:b2Vec2 = new b2Vec2( (1.0 - fraction) * point1.x + fraction * point2.x, (1.0 - fraction) * point1.y + fraction * point2.y); return callback(fixture, point, output.normal, fraction); } return input.maxFraction; } var input:b2RayCastInput = new b2RayCastInput(point1, point2); broadPhase.RayCast(RayCastWrapper, input); } public function RayCastOne(point1:b2Vec2, point2:b2Vec2):b2Fixture { var result:b2Fixture; function RayCastOneWrapper(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number { result = fixture; return fraction; } RayCast(RayCastOneWrapper, point1, point2); return result; } public function RayCastAll(point1:b2Vec2, point2:b2Vec2):Vector. { var result:Vector. = new Vector.(); function RayCastAllWrapper(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number { result[result.length] = fixture; return 1; } RayCast(RayCastAllWrapper, point1, point2); return result; } /** * Get the world body list. With the returned body, use b2Body::GetNext to get * the next body in the world list. A NULL body indicates the end of the list. * @return the head of the world body list. */ public function GetBodyList() : b2Body{ return m_bodyList; } /** * Get the world joint list. With the returned joint, use b2Joint::GetNext to get * the next joint in the world list. A NULL joint indicates the end of the list. * @return the head of the world joint list. */ public function GetJointList() : b2Joint{ return m_jointList; } /** * Get the world contact list. With the returned contact, use b2Contact::GetNext to get * the next contact in the world list. A NULL contact indicates the end of the list. * @return the head of the world contact list. * @warning contacts are */ public function GetContactList():b2Contact { return m_contactList; } /** * Is the world locked (in the middle of a time step). */ public function IsLocked():Boolean { return (m_flags & e_locked) > 0; } //--------------- Internals Below ------------------- // Internal yet public to make life easier. // Find islands, integrate and solve constraints, solve position constraints private var s_stack:Vector. = new Vector.(); b2internal function Solve(step:b2TimeStep) : void{ var b:b2Body; // Step all controllers for(var controller:b2Controller= m_controllerList;controller;controller=controller.m_next) { controller.Step(step); } // Size the island for the worst case. var island:b2Island = m_island; island.Initialize(m_bodyCount, m_contactCount, m_jointCount, null, m_contactManager.m_contactListener, m_contactSolver); // Clear all the island flags. for (b = m_bodyList; b; b = b.m_next) { b.m_flags &= ~b2Body.e_islandFlag; } for (var c:b2Contact = m_contactList; c; c = c.m_next) { c.m_flags &= ~b2Contact.e_islandFlag; } for (var j:b2Joint = m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } // Build and simulate all awake islands. var stackSize:int = m_bodyCount; //b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); var stack:Vector. = s_stack; for (var seed:b2Body = m_bodyList; seed; seed = seed.m_next) { if (seed.m_flags & b2Body.e_islandFlag ) { continue; } if (seed.IsAwake() == false || seed.IsActive() == false) { continue; } // The seed can be dynamic or kinematic. if (seed.GetType() == b2Body.b2_staticBody) { continue; } // Reset island and stack. island.Clear(); var stackCount:int = 0; stack[stackCount++] = seed; seed.m_flags |= b2Body.e_islandFlag; // Perform a depth first search (DFS) on the constraint graph. while (stackCount > 0) { // Grab the next body off the stack and add it to the island. b = stack[--stackCount]; //b2Assert(b.IsActive() == true); island.AddBody(b); // Make sure the body is awake. if (b.IsAwake() == false) { b.SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b.GetType() == b2Body.b2_staticBody) { continue; } var other:b2Body; // Search all contacts connected to this body. for (var ce:b2ContactEdge = b.m_contactList; ce; ce = ce.next) { // Has this contact already been added to an island? if (ce.contact.m_flags & b2Contact.e_islandFlag) { continue; } // Is this contact solid and touching? if (ce.contact.IsSensor() == true || ce.contact.IsEnabled() == false || ce.contact.IsTouching() == false) { continue; } island.AddContact(ce.contact); ce.contact.m_flags |= b2Contact.e_islandFlag; //var other:b2Body = ce.other; other = ce.other; // Was the other body already added to this island? if (other.m_flags & b2Body.e_islandFlag) { continue; } //b2Settings.b2Assert(stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= b2Body.e_islandFlag; } // Search all joints connect to this body. for (var jn:b2JointEdge = b.m_jointList; jn; jn = jn.next) { if (jn.joint.m_islandFlag == true) { continue; } other = jn.other; // Don't simulate joints connected to inactive bodies. if (other.IsActive() == false) { continue; } island.AddJoint(jn.joint); jn.joint.m_islandFlag = true; if (other.m_flags & b2Body.e_islandFlag) { continue; } //b2Settings.b2Assert(stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= b2Body.e_islandFlag; } } island.Solve(step, m_gravity, m_allowSleep); // Post solve cleanup. for (var i:int = 0; i < island.m_bodyCount; ++i) { // Allow static bodies to participate in other islands. b = island.m_bodies[i]; if (b.GetType() == b2Body.b2_staticBody) { b.m_flags &= ~b2Body.e_islandFlag; } } } //m_stackAllocator.Free(stack); for (i = 0; i < stack.length;++i) { if (!stack[i]) break; stack[i] = null; } // Synchronize fixutres, check for out of range bodies. for (b = m_bodyList; b; b = b.m_next) { if (b.IsAwake() == false || b.IsActive() == false) { continue; } if (b.GetType() == b2Body.b2_staticBody) { continue; } // Update fixtures (for broad-phase). b.SynchronizeFixtures(); } // Look for new contacts. m_contactManager.FindNewContacts(); } private static var s_backupA:b2Sweep = new b2Sweep(); private static var s_backupB:b2Sweep = new b2Sweep(); private static var s_timestep:b2TimeStep = new b2TimeStep(); private static var s_queue:Vector. = new Vector.(); // Find TOI contacts and solve them. b2internal function SolveTOI(step:b2TimeStep) : void{ var b:b2Body; var fA:b2Fixture; var fB:b2Fixture; var bA:b2Body; var bB:b2Body; var cEdge:b2ContactEdge; var j:b2Joint; // Reserve an island and a queue for TOI island solution. var island:b2Island = m_island; island.Initialize(m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, b2Settings.b2_maxTOIJointsPerIsland, null, m_contactManager.m_contactListener, m_contactSolver); //Simple one pass queue //Relies on the fact that we're only making one pass //through and each body can only be pushed/popped one. //To push: // queue[queueStart+queueSize++] = newElement; //To pop: // poppedElement = queue[queueStart++]; // --queueSize; var queue:Vector. = s_queue; for (b = m_bodyList; b; b = b.m_next) { b.m_flags &= ~b2Body.e_islandFlag; b.m_sweep.t0 = 0.0; } var c:b2Contact; for (c = m_contactList; c; c = c.m_next) { // Invalidate TOI c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag); } for (j = m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } // Find TOI events and solve them. for (;;) { // Find the first TOI. var minContact:b2Contact = null; var minTOI:Number = 1.0; for (c = m_contactList; c; c = c.m_next) { // Can this contact generate a solid TOI contact? if (c.IsSensor() == true || c.IsEnabled() == false || c.IsContinuous() == false) { continue; } // TODO_ERIN keep a counter on the contact, only respond to M TOIs per contact. var toi:Number = 1.0; if (c.m_flags & b2Contact.e_toiFlag) { // This contact has a valid cached TOI. toi = c.m_toi; } else { // Compute the TOI for this contact. fA = c.m_fixtureA; fB = c.m_fixtureB; bA = fA.m_body; bB = fB.m_body; if ((bA.GetType() != b2Body.b2_dynamicBody || bA.IsAwake() == false) && (bB.GetType() != b2Body.b2_dynamicBody || bB.IsAwake() == false)) { continue; } // Put the sweeps onto the same time interval. var t0:Number = bA.m_sweep.t0; if (bA.m_sweep.t0 < bB.m_sweep.t0) { t0 = bB.m_sweep.t0; bA.m_sweep.Advance(t0); } else if (bB.m_sweep.t0 < bA.m_sweep.t0) { t0 = bA.m_sweep.t0; bB.m_sweep.Advance(t0); } //b2Settings.b2Assert(t0 < 1.0f); // Compute the time of impact. toi = c.ComputeTOI(bA.m_sweep, bB.m_sweep); b2Settings.b2Assert(0.0 <= toi && toi <= 1.0); // If the TOI is in range ... if (toi > 0.0 && toi < 1.0) { // Interpolate on the actual range. //toi = Math.min((1.0 - toi) * t0 + toi, 1.0); toi = (1.0 - toi) * t0 + toi; if (toi > 1) toi = 1; } c.m_toi = toi; c.m_flags |= b2Contact.e_toiFlag; } if (Number.MIN_VALUE < toi && toi < minTOI) { // This is the minimum TOI found so far. minContact = c; minTOI = toi; } } if (minContact == null || 1.0 - 100.0 * Number.MIN_VALUE < minTOI) { // No more TOI events. Done! break; } // Advance the bodies to the TOI. fA = minContact.m_fixtureA; fB = minContact.m_fixtureB; bA = fA.m_body; bB = fB.m_body; s_backupA.Set(bA.m_sweep); s_backupB.Set(bB.m_sweep); bA.Advance(minTOI); bB.Advance(minTOI); // The TOI contact likely has some new contact points. minContact.Update(m_contactManager.m_contactListener); minContact.m_flags &= ~b2Contact.e_toiFlag; // Is the contact solid? if (minContact.IsSensor() == true || minContact.IsEnabled() == false) { // Restore the sweeps bA.m_sweep.Set(s_backupA); bB.m_sweep.Set(s_backupB); bA.SynchronizeTransform(); bB.SynchronizeTransform(); continue; } // Did numerical issues prevent;,ontact pointjrom being generated if (minContact.IsTouching() == false) { // Give up on this TOI continue; } // Build the TOI island. We need a dynamic seed. var seed:b2Body = bA; if (seed.GetType() != b2Body.b2_dynamicBody) { seed = bB; } // Reset island and queue. island.Clear(); var queueStart:int = 0; //start index for queue var queueSize:int = 0; //elements in queue queue[queueStart + queueSize++] = seed; seed.m_flags |= b2Body.e_islandFlag; // Perform a breadth first search (BFS) on the contact graph. while (queueSize > 0) { // Grab the next body off the stack and add it to the island. b = queue[queueStart++]; --queueSize; island.AddBody(b); // Make sure the body is awake. if (b.IsAwake() == false) { b.SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static or kinematic bodies. if (b.GetType() != b2Body.b2_dynamicBody) { continue; } // Search all contacts connected to this body. for (cEdge = b.m_contactList; cEdge; cEdge = cEdge.next) { // Does the TOI island still have space for contacts? if (island.m_contactCount == island.m_contactCapacity) { break; } // Has this contact already been added to an island? if (cEdge.contact.m_flags & b2Contact.e_islandFlag) { continue; } // Skip sperate, sensor, or disabled contacts. if (cEdge.contact.IsSensor() == true || cEdge.contact.IsEnabled() == false || cEdge.contact.IsTouching() == false) { continue; } island.AddContact(cEdge.contact); cEdge.contact.m_flags |= b2Contact.e_islandFlag; // Update other body. var other:b2Body = cEdge.other; // Was the other body already added to this island? if (other.m_flags & b2Body.e_islandFlag) { continue; } // Synchronize the connected body. if (other.GetType() != b2Body.b2_staticBody) { other.Advance(minTOI); other.SetAwake(true); } //b2Settings.b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other.m_flags |= b2Body.e_islandFlag; } for (var jEdge:b2JointEdge = b.m_jointList; jEdge; jEdge = jEdge.next) { if (island.m_jointCount == island.m_jointCapacity) continue; if (jEdge.joint.m_islandFlag == true) continue; other = jEdge.other; if (other.IsActive() == false) { continue; } island.AddJoint(jEdge.joint); jEdge.joint.m_islandFlag = true; if (other.m_flags & b2Body.e_islandFlag) continue; // Synchronize the connected body. if (other.GetType() != b2Body.b2_staticBody) { other.Advance(minTOI); other.SetAwake(true); } //b2Settings.b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other.m_flags |= b2Body.e_islandFlag; } } var subStep:b2TimeStep = s_timestep; subStep.warmStarting = false; subStep.dt = (1.0 - minTOI) * step.dt; subStep.inv_dt = 1.0 / subStep.dt; subStep.dtRatio = 0.0; subStep.velocityIterations = step.velocityIterations; subStep.positionIterations = step.positionIterations; island.SolveTOI(subStep); var i:int; // Post solve cleanup. for (i = 0; i < island.m_bodyCount; ++i) { // Allow bodies to participate in future TOI islands. b = island.m_bodies[i]; b.m_flags &= ~b2Body.e_islandFlag; if (b.IsAwake() == false) { continue; } if (b.GetType() != b2Body.b2_dynamicBody) { continue; } // Update fixtures (for broad-phase). b.SynchronizeFixtures(); // Invalidate all contact TOIs associated with this body. Some of these // may not be in the island because they were not touching. for (cEdge = b.m_contactList; cEdge; cEdge = cEdge.next) { cEdge.contact.m_flags &= ~b2Contact.e_toiFlag; } } for (i = 0; i < island.m_contactCount; ++i) { // Allow contacts to participate in future TOI islands. c = island.m_contacts[i]; c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag); } for (i = 0; i < island.m_jointCount;++i) { // Allow joints to participate in future TOI islands j = island.m_joints[i]; j.m_islandFlag = false; } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. m_contactManager.FindNewContacts(); } //m_stackAllocator.Free(queue); } static private var s_jointColor:b2Color = new b2Color(0.5, 0.8, 0.8); // b2internal function DrawJoint(joint:b2Joint) : void{ var b1:b2Body = joint.GetBodyA(); var b2:b2Body = joint.GetBodyB(); var xf1:b2Transform = b1.m_xf; var xf2:b2Transform = b2.m_xf; var x1:b2Vec2 = xf1.position; var x2:b2Vec2 = xf2.position; var p1:b2Vec2 = joint.GetAnchorA(); var p2:b2Vec2 = joint.GetAnchorB(); //b2Color color(0.5f, 0.8f, 0.8f); var color:b2Color = s_jointColor; switch (joint.m_type) { case b2Joint.e_distanceJoint: m_debugDraw.DrawSegment(p1, p2, color); break; case b2Joint.e_pulleyJoint: { var pulley:b2PulleyJoint = (joint as b2PulleyJoint); var s1:b2Vec2 = pulley.GetGroundAnchorA(); var s2:b2Vec2 = pulley.GetGroundAnchorB(); m_debugDraw.DrawSegment(s1, p1, color); m_debugDraw.DrawSegment(s2, p2, color); m_debugDraw.DrawSegment(s1, s2, color); } break; case b2Joint.e_mouseJoint: m_debugDraw.DrawSegment(p1, p2, color); break; default: if (b1 != m_groundBody) m_debugDraw.DrawSegment(x1, p1, color); m_debugDraw.DrawSegment(p1, p2, color); if (b2 != m_groundBody) m_debugDraw.DrawSegment(x2, p2, color); } } b2internal function DrawShape(shape:b2Shape, xf:b2Transform, color:b2Color) : void{ switch (shape.m_type) { case b2Shape.e_circleShape: { var circle:b2CircleShape = (shape as b2CircleShape); var center:b2Vec2 = b2Math.MulX(xf, circle.m_p); var radius:Number = circle.m_radius; var axis:b2Vec2 = xf.R.col1; m_debugDraw.DrawSolidCircle(center, radius, axis, color); } break; case b2Shape.e_polygonShape: { var i:int; var poly:b2PolygonShape = (shape as b2PolygonShape); var vertexCount:int = poly.GetVertexCount(); var localVertices:Vector. = poly.GetVertices(); var vertices:Vector. = new Vector.(vertexCount); for (i = 0; i < vertexCount; ++i) { vertices[i] = b2Math.MulX(xf, localVertices[i]); } m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color); } break; case b2Shape.e_edgeShape: { var edge: b2EdgeShape = shape as b2EdgeShape; m_debugDraw.DrawSegment(b2Math.MulX(xf, edge.GetVertex1()), b2Math.MulX(xf, edge.GetVertex2()), color); } break; } } b2internal var m_flags:int; b2internal var m_contactManager:b2ContactManager = new b2ContactManager(); // These two are stored purely for efficiency purposes, they don't maintain // any data outside of a call to Step private var m_contactSolver:b2ContactSolver = new b2ContactSolver(); private var m_island:b2Island = new b2Island(); b2internal var m_bodyList:b2Body; private var m_jointList:b2Joint; b2internal var m_contactList:b2Contact; private var m_bodyCount:int; b2internal var m_contactCount:int; private var m_jointCount:int; private var m_controllerList:b2Controller; private var m_controllerCount:int; private var m_gravity:b2Vec2; private var m_allowSleep:Boolean; b2internal var m_groundBody:b2Body; private var m_destructionListener:b2DestructionListener; private var m_debugDraw:b2DebugDraw; // This is used to compute the time step ratio to support a variable time step. private var m_inv_dt0:Number; // This is for debugging the solver. static private var m_warmStarting:Boolean; // This is for debugging the solver. static private var m_continuousPhysics:Boolean; // m_flags public static const e_newFixture:int = 0x0001; public static const e_locked:int = 0x0002; }; } ",12189,False,2253.738151767163,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.rpc.xml { import flash.utils.ByteArray; import flash.utils.Dictionary; import mx.utils.Base64Encoder; import mx.utils.Base64Decoder; import mx.utils.HexEncoder; import mx.utils.HexDecoder; import mx.utils.StringUtil; [ExcludeClass] /** * FIXME: Derivations and restrictions need to be considered in addition * to base schema types * * @private */ public class SchemaMarshaller //implements IXMLTypeMarshaller { public function SchemaMarshaller(constants:SchemaConstants, datatypes:SchemaDatatypes) { super(); this.constants = constants; this.datatypes = datatypes; registerMarshallers(); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * Determines whether this marshaller will throw errors for input that * violates the specified format or restrictions for the associated type. * Type errors are still thrown for unexpected input types. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get validating():Boolean { return _validating; } public function set validating(value:Boolean):void { _validating = value; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * This function converts an ActionScript value to a String for XML * simple content based on a built-in XML Schema type. If a type is not * provided, the anyType is assumed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshall(value:*, type:QName = null, restriction:XML = null):* { if (type == null) type = datatypes.anyTypeQName; var marshaller:Function = marshallers[type.localName]; var result:*; if (marshaller != null) result = marshaller(value, type, restriction); else throw new TypeError(""Cannot marshall type '"" + type + ""' to simple content.""); return result; } /** * This function converts XML simple content (formatted based on a built-in * XML Schema type) to an ActionScript value. If a type is not provided, * the anyType is assumed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function unmarshall(value:*, type:QName = null, restriction:XML = null):* { // First, get the simple content as a String var rawValue:String; if (value is XML) { var xml:XML = value as XML; if (xml.nodeKind() == ""element"") { var nilAttribute:String = xml.attribute(constants.nilQName).toString(); if (nilAttribute == ""true"") rawValue = null; else rawValue = xml.text().toString(); } else { rawValue = xml.toString(); } } else if (value is XMLList) { var list:XMLList = value as XMLList; rawValue = list.text().toString(); } else if (value != null) { rawValue = value.toString(); } if (type == null) type = datatypes.anyTypeQName; var unmarshaller:Function = unmarshallers[type.localName]; if (unmarshaller != null) value = unmarshaller(rawValue, type, restriction); else throw new TypeError(""Cannot unmarshall type '"" + type + ""' from XML.""); return value; } /** * In the case of XML Schema ur-types such as anyType and * anySimpleType we try to guess what the equivalent XML Schema * simple datatype should be based on the ActionScript type. As a last * resort, the string datatype is used. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallAny(value:*, type:QName = null, restriction:XML = null):* { if (value === undefined) return undefined; else if (value == null) return null; var localName:String = guessSimpleType(value); if (type != null) type = new QName(type.uri, localName); else type = new QName(constants.xsdURI, localName); var marshaller:Function = marshallers[type.localName]; if (marshaller != null) { return marshaller(value, type); } else { throw new TypeError(""Cannot marshall type '"" + type + ""' to simple content.""); } } public function marshallBase64Binary(value:*, type:QName = null, restriction:XML = null):String { var ba:ByteArray = value as ByteArray; var result:String; if (ba != null) { var encoder:Base64Encoder = new Base64Encoder(); encoder.insertNewLines = false; encoder.encodeBytes(ba); result = encoder.drain(); } else { return null; } return result; } /** * The boolean schema type allows the string values 'true' or * '1' for true values and 'false' or '0' for false values. This * marshaller, by default, represents values using 'true' or false. * If a String value of '1' or '0' is passed, however, it is preserved. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallBoolean(value:*, type:QName = null, restriction:XML = null):String { var result:String; if (value != null) { if (value is Boolean) { result = (value as Boolean) ? ""true"" : ""false""; } else if (value is Number) { result = (value == 1) ? ""true"" : ""false""; } else if (value is Object) { var s:String = Object(value).toString(); if (s == ""true"" || s == ""false"" || s == ""1"" || s == ""0"") result = s; else throw new Error(""String '"" + value + ""' is not a Boolean.""); } } return result; } public function marshallDatetime(value:*, type:QName = null, restriction:XML = null):String { var result:String; var date:Date; if (value is Number) { date = new Date(); date.time = value as Number; value = date; } if (value is Date) { var n:Number; date = value as Date; result = """"; if (type == datatypes.dateTimeQName || type == datatypes.dateQName) { // Year result = result.concat(date.getUTCFullYear(), ""-""); // Month n = date.getUTCMonth() + 1; // ActionScript UTC month starts from 0 if (n < 10) result = result.concat(""0""); result = result.concat(n, ""-""); // Day n = date.getUTCDate(); if (n < 10) result = result.concat(""0""); result = result.concat(n); } if (type == datatypes.dateTimeQName) { result = result.concat(""T""); } // Time if (type == datatypes.dateTimeQName || type == datatypes.timeQName) { n = date.getUTCHours(); if (n < 10) result = result.concat(""0""); result = result.concat(n, "":""); n = date.getUTCMinutes(); if (n < 10) result = result.concat(""0""); result = result.concat(n, "":""); n = date.getUTCSeconds(); if (n < 10) result = result.concat(""0""); result = result.concat(n); // Milliseconds are optional so we write them if > 0 n = date.getUTCMilliseconds(); if (n > 0) { result = result.concat("".""); if (n < 10) result = result.concat(""00""); else if (n < 100) result = result.concat(""0""); result = result.concat(n); } } // Always send dates, times and dateTimes in UTC from the player. result = result.concat(""Z""); } else if (value is String) { result = value as String; } return result; } /** * FIXME: Handle precision and exponent restrictions. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallDecimal(value:*, type:QName = null, restriction:XML = null):String { var result:String; var number:Number; if (value is Number) { number = value as Number; } else { var str:String = whitespaceCollapse(value); number = Number(str); } // Check for Infinity, -Infinity and NaN as these are not valid // values for the XML Schema decimal type. result = specialNumber(number); if (result != null) { if (validating) { throw new Error(""Invalid decimal value '"" + value + ""'.""); } else { // As a last resort, we just go with the original input result = whitespaceCollapse(value); } } else { // We have a normal number result = number.toString(); } return result; } /** * FIXME: Handle precision and exponent restrictions. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallDouble(value:*, type:QName = null, restriction:XML = null):String { var result:String; var number:Number = Number(value); // Check for Infinity, -Infinity and NaN result = specialNumber(number); if (result == null) result = number.toString(); return result; } public function marshallDuration(value:*, type:QName = null, restriction:XML = null):String { return whitespaceCollapse(value); } /** * FIXME: Handle precision and exponent restrictions. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallFloat(value:*, type:QName = null, restriction:XML = null):String { var result:String; // First, check that we have a suitable input for Number var number:Number; if (value is Number) { number = value as Number; } else { var str:String = whitespaceCollapse(value); number = Number(str); } // Check for Infinity, -Infinity and NaN result = specialNumber(number); if (result == null) { if (validating) { if (number > 0) { if (number > FLOAT_MAX_VALUE) throw new RangeError(""The value '"" + value + ""' is too large for a single-precision floating point value.""); else if (number < FLOAT_MIN_VALUE) throw new RangeError(""The value '"" + value + ""' is too small for a single-precision floating point value.""); } else { if (-number > FLOAT_MAX_VALUE) throw new RangeError(""The absolute value of '"" + value + ""' is too large for a single-precision floating point value.""); else if (-number < FLOAT_MIN_VALUE) throw new RangeError(""The absolute value of '"" + value + ""' is too small for a single-precision floating point value.""); } } result = number.toString(); } return result; } public function marshallGregorian(value:*, type:QName = null, restriction:XML = null):String { var date:Date; var n:Number; if (value is Date) date = value as Date; else if (value is Number) n = value as Number; else value = whitespaceCollapse(value); var result:String = """"; var hyphen:int; // Year if (type == datatypes.gYearMonthQName || type == datatypes.gYearQName) { var year:String; if (value is Date) { n = date.getUTCFullYear(); } else if (value is String) { year = value as String; // We may have CCYY, -CCYY, CCYY-MM or -CCYY-MM hyphen = year.indexOf(""-"", 1); if (hyphen > 0) year = year.substring(0, hyphen); n = parseInt(year); } // Check for NaN or 0000 as these are not valid years. if (isNaN(n) || n == 0) { if (validating) { throw new Error(""Invalid year supplied for type "" + type.localName + "" in value "" + value); } else { // Abort trying to process this value return whitespaceCollapse(value); } } else { // Get a String representation of the year, though this value // is potentially unbounded so we use Number.toFixed instead // of int(). year = n.toFixed(0); // Pad early years with leading 0s up to 000x but // we keep in mind that negative years such as -894 are valid. if (year.indexOf(""-"") == 0) { while (year.length < 5) year = year.substring(0, 1) + ""0"" + year.substring(1); } else { while (year.length < 4) year = ""0"" + year; } result = result.concat(year); } if (type != datatypes.gYearQName) result = result.concat(""-""); } // Month if (type == datatypes.gYearMonthQName || type == datatypes.gMonthDayQName || type == datatypes.gMonthQName) { if (type != datatypes.gYearMonthQName) result = result.concat(""--""); var month:String; if (value is Date) n = date.getUTCMonth() + 1; // ActionScript UTC month starts at 0 else { month = value.toString(); if (type == datatypes.gMonthDayQName) { // We must have --MM-DD hyphen = month.indexOf(""--"", 0); if (hyphen == 0) month = month.substring(2, 4); else if (validating) throw new Error(""Invalid month supplied for "" + type.localName + "" in value "" + value + "". The format must be '--MM-DD'.""); else { // Abort trying to process this value return whitespaceCollapse(value); } } else if (type == datatypes.gYearMonthQName) { hyphen = month.indexOf(""-"", 1); // We must have CCYY-MM or -CCYY-MM if (hyphen > 0) month = month.substring(hyphen + 1, hyphen + 3); else if (validating) throw new Error(""Invalid month supplied for "" + type.localName + "" in value "" + value + "". The format must be '--CCYY-MM'.""); else { // Abort trying to process this value return whitespaceCollapse(value); } } else { // We may have --MM-- (but we allow just MM too) hyphen = month.indexOf(""--"", 0); if (hyphen > 0) month = month.substring(2, 4); } n = parseInt(month); } // Check for NaN or values not in the range of 1 to 12 // as these are not valid months if (isNaN(n) || n <= 0 || n > 12) { if (validating) throw new Error(""Invalid month supplied for type "" + type.localName + "" in value "" + value); else { // Abort trying to process this value return whitespaceCollapse(value); } } else { n = int(n); if (n < 10) result = result.concat(""0""); result = result.concat(n); } if (type == datatypes.gMonthDayQName) { result = result.concat(""-""); } } // Day if (type == datatypes.gMonthDayQName || type == datatypes.gDayQName) { if (type == datatypes.gDayQName) result = result.concat(""---""); if (value is Date) n = date.getUTCDate(); else if (value is String) { var day:String = value as String; if (type == datatypes.gMonthDayQName) { //We must have --MM-DD hyphen = day.indexOf(""--"", 0); if (hyphen == 0) day = day.substring(5, 7); else if (validating) throw new Error(""Invalid day supplied for gMonthDay in value "" + value + "". The format must be '--MM-DD'.""); else { // Abort trying to process this value return whitespaceCollapse(value); } } else { //We might have ---DD (but we allow just DD too) hyphen = day.indexOf(""---"", 0); if (hyphen == 0) day = day.substring(3, 5); } n = parseInt(day); } // Check for NaN or values not in the range of 1 to 31 // as these are not valid days if (isNaN(n) || n <= 0 || n > 31) { if (validating) throw new Error(""Invalid day supplied for type "" + type.localName + "" in value "" + value); else // Abort trying to process this value return whitespaceCollapse(value); } else { n = int(n); if (n < 10) result = result.concat(""0""); result = result.concat(n); } } return result; } /** * The schema type hexBinary represents arbitrary hex-encoded binary data. * Each binary octet is encoded as a character tuple consisting of two * hexadecimal digits (which is treated case insensitively although * capital letters A-F are always used on encoding). These tuples are * added to a String to serialize the binary data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallHexBinary(value:*, type:QName = null, restriction:XML = null):String { var ba:ByteArray = value as ByteArray; var valueString:String; if (ba != null) { var encoder:HexEncoder = new HexEncoder(); encoder.encode(ba); valueString = encoder.drain(); } else { throw new Error(""Cannot marshall value as hex binary.""); } return valueString; } /** * The schema type integer is dervied from the decimal type via restrictions * by fixing the value of fractionDigits to be 0 and disallowing the * trailing decimal point. The schema types long, int, short, byte are * derived from integer by restricting the maxInclusive and minInclusive * properties. Other types such as nonPositiveInteger, negativeInteger, * nonNegativeInteger, positiveInteger, unsignedLong, unsignedInt, * unsignedShort and unsignedByte are also dervied from integer through * similar restrictions. * * This method first calls parses the value as a Number. It * then uses Math.floor() on the number to remove any fraction * digits and then checks that the result is within the specified * min and max for the type. Note that decimal * values are not rounded. This method handles integers longer than 32-bit * so ActionScript int or uint types are not used internally. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function marshallInteger(value:*, type:QName = null, restriction:XML = null):String { var result:String; var number:Number; if (value is Number) number = value as Number else number = Number(whitespaceCollapse(value)); var min:Number = -Number.MAX_VALUE; var max:Number = Number.MAX_VALUE; if (type == datatypes.longQName) { min = LONG_MIN_VALUE max = LONG_MAX_VALUE; } else if (type == datatypes.intQName) { min = int.MIN_VALUE; max = int.MAX_VALUE; } else if (type == datatypes.shortQName) { min = SHORT_MIN_VALUE max = SHORT_MAX_VALUE; } else if (type == datatypes.byteQName) { min = BYTE_MIN_VALUE max = BYTE_MAX_VALUE; } else if (type == datatypes.unsignedLongQName) { min = 0; max = ULONG_MAX_VALUE; } else if (type == datatypes.unsignedIntQName) { min = 0; max = uint.MAX_VALUE; } else if (type == datatypes.unsignedShortQName) { min = 0; max = USHORT_MAX_VALUE; } else if (type == datatypes.unsignedByteQName) { min = 0; max = UBYTE_MAX_VALUE; } else if (type == datatypes.positiveIntegerQName) { min = 1; max = Number.MAX_VALUE; } else if (type == datatypes.nonNegativeIntegerQName) { min = 0; max = Number.MAX_VALUE; } else if (type == datatypes.negativeIntegerQName) { min = -Number.MAX_VALUE; max = -1; } else if (type == datatypes.nonPositiveIntegerQName) { min = -Number.MAX_VALUE; max = 0; } else if (type == datatypes.integerQName) { min = -Number.MAX_VALUE; max = Number.MAX_VALUE; } var integer:Number = Math.floor(number); if (integer >= min) { if (integer > max) { if (validating) { throw new RangeError(""The value '"" + value + ""' is too large for "" + type.localName); } else { // As a last resort, we just go with the original input return whitespaceCollapse(value); } } } else { if (validating) { throw new RangeError(""The value '"" + value + ""' is too small for "" + type.localName); } else { // As a last resort, we just go with the original input return whitespaceCollapse(value); } } result = integer.toString(); return result; } public function marshallString(value:*, type:QName = null, restriction:XML = null):String { if (value != null) { if (value is XML || value is XMLList) { // for XML and XMLList objects, use toXMLString() to include the // root tag for xml instances with simple content (toString() would // only return the simple content inside the tag). return value.toXMLString(); } else if (value is Object) { return Object(value).toString(); } } return null; } public function unmarshallAny(value:*, type:QName = null, restriction:XML = null):* { if (value === undefined) return undefined; else if (value == null) return null; var result:*; var unmarshaller:Function; var s:String = whitespaceCollapse(value); if (s == """") { unmarshaller = unmarshallers[datatypes.stringQName.localName]; } else if (isNaN(Number(s)) || (s.charAt(0) == '0') || ((s.charAt(0) == '-') && (s.charAt(1) == '0')) || s.charAt(s.length - 1) == 'E') { var lowerS:String = s.toLowerCase(); if (lowerS == ""true"" || lowerS == ""false"") { unmarshaller = unmarshallers[datatypes.booleanQName.localName]; } else { unmarshaller = unmarshallers[datatypes.stringQName.localName]; } } else { unmarshaller = unmarshallers[datatypes.doubleQName.localName]; } result = unmarshaller(value, type, restriction); return result; } public function unmarshallBase64Binary(value:*, type:QName = null, restriction:XML = null):ByteArray { if (value == null) return null; var data:String = whitespaceCollapse(value); var decoder:Base64Decoder = new Base64Decoder(); decoder.decode(data); return decoder.drain(); } public function unmarshallBoolean(value:*, type:QName = null, restriction:XML = null):Boolean { if (value == null) return false; var bool:String = whitespaceCollapse(value).toLowerCase(); if (bool == ""true"" || bool == ""1"") return true; return false; } public function unmarshallDate(value:*, type:QName = null, restriction:XML = null):Object { if (value == null) return null; var date:Date; var index:int; var datePart:String = whitespaceCollapse(value); if (datePart != null) { // dateLexicalRep ::= yearFrag '-' monthFrag '-' dayFrag timezoneFrag? // yearFrag ::= '-'? (([1-9] digit digit digit+)) | ('0' digit digit digit)) index = datePart.indexOf(""-"", 1); var year:uint = uint(datePart.substring(0, index++)); // monthFrag ::= ('0' [1-9]) | ('1' [0-2]) var month:uint = uint(datePart.substring(index, index + 2)); index += 3; // dayFrag ::= (0 [1-9]) | ([12] digit) | ('3' [01]) var day:uint = uint(datePart.substring(index, index + 2)); index += 2; // timezoneFrag ::= 'Z' | (('+' | '-') ('0' digit | '1' [0-4]) ':' minuteFrag) if (datePart.charAt(index) == ""Z"") // UTC. { date = new Date(Date.UTC(year, month - 1, day)); } else if (datePart.length > 10) // UTC offset. { // Start at UTC. date = new Date(Date.UTC(year, month - 1, day)); // (('+' | '-') ('0' digit | '1' [0-4]) ':' minuteFrag) var offsetDirection:String = datePart.charAt(index++); var hours:int = int(datePart.substring(index, index + 2)); index += 3; // minuteFrag ::= [0-5] digit var minutes:int = int(datePart.substring(index, index + 2)); // Done with parse; apply offset. var millis:Number = (hours * 3600000) + (minutes * 60000); if (offsetDirection == ""+"") { date.time -= millis; } else // ""-"" { date.time += millis; } } else // Treat as local time. { date = new Date(year, month - 1, day); } } return date; } /** * Handles dateTime and time types. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function unmarshallDatetime(value:*, type:QName = null, restriction:XML = null):Object { if (value == null) return null; var date:Date; var rawValue:String = whitespaceCollapse(value); var datePart:String; var timePart:String; var utc:Boolean; var offset:Boolean; var index:int; var sep:int = rawValue.indexOf(""T""); if (sep != -1) { datePart = rawValue.substring(0, sep); timePart = rawValue.substring(sep + 1); } else // It's a time (no date part). { timePart = rawValue; } // Parse the time first to get the timezone/offset. E.g. 24:00:00.000 // timeLexicalRep ::= ((hourFrag ':' minuteFrag ':' secondFrag) | endOfDayFrag) timezoneFrag? // hourFrag ::= ([01] digit) | ('2' [0-3]) var hours:int = int(timePart.substring(0, 2)); // minuteFrag ::= [0-5] digit var minutes:int = int(timePart.substring(3, 5)); // secondFrag ::= ([0-5] digit) ('.' digit+)? var millisStart:int = timePart.indexOf(""."", 6); var seconds:int = int(timePart.substring(6, 8)); // Handle millis and timezone next. // timezoneFrag ::= 'Z' | (('+' | '-') ('0' digit | '1' [0-4]) ':' minuteFrag) var tzIndex:int = timePart.indexOf(""Z"", 8); var offsetDirection:int; var offsetMillis:Number; if (tzIndex == -1) { if ((tzIndex = timePart.indexOf(""+"", 8)) != -1) offsetDirection = 1; // Positive. else if ((tzIndex = timePart.indexOf(""-"", 8)) != -1) offsetDirection = -1; // Negative. if (tzIndex != -1) { index = tzIndex + 1; var offsetHours:int = int(timePart.substring(index, index + 2)); index += 3; var offsetMinutes:int = int(timePart.substring(index, index + 2)); offsetMillis = (offsetHours * 3600000) + (offsetMinutes * 60000); utc = true; offset = true; } } else { utc = true; } var millis:int = 0; if (millisStart != -1) { var fractionalSecond:Number; if (tzIndex != -1) fractionalSecond = Number(timePart.substring(millisStart, tzIndex)); else fractionalSecond = Number(timePart.substring(millisStart)); millis = int(Math.floor(fractionalSecond*1000)); } // Now parse the datePart if it exists. if (datePart != null) { // dateLexicalRep ::= yearFrag '-' monthFrag '-' dayFrag timezoneFrag? // yearFrag ::= '-'? (([1-9] digit digit digit+)) | ('0' digit digit digit)) index = datePart.indexOf(""-"", 1); var year:uint = uint(datePart.substring(0, index++)); // monthFrag ::= ('0' [1-9]) | ('1' [0-2]) var month:uint = uint(datePart.substring(index, index + 2)); index += 3; // dayFrag ::= (0 [1-9]) | ([12] digit) | ('3' [01]) var day:uint = uint(datePart.substring(index, index + 2)); if (utc) date = new Date(Date.UTC(year, month - 1, day)); else date = new Date(year, month - 1, day); } else { if (utc) { var now:Date = new Date(); date = new Date(Date.UTC(now.fullYearUTC, now.monthUTC, now.dateUTC)); } else { date = new Date(); } } // Apply the time part. if (utc) { date.setUTCHours(hours, minutes, seconds, millis); if (offset) { if (offsetDirection > 0) date.time -= offsetMillis; else date.time += offsetMillis; } } else { date.setHours(hours, minutes, seconds, millis); } return date; } public function unmarshallDecimal(value:*, type:QName = null, restriction:XML = null):Number { return unmarshallDouble(value, type); } public function unmarshallDouble(value:*, type:QName = null, restriction:XML = null):Number { var result:Number; if (value != null) { var s:String = whitespaceCollapse(value); if (s == ""INF"") { result = Number.POSITIVE_INFINITY; } else if (s == ""-INF"") { result = Number.NEGATIVE_INFINITY; } else { result = Number(s); } } return result; } public function unmarshallDuration(value:*, type:QName = null, restriction:XML = null):* { return whitespaceCollapse(value); } public function unmarshallFloat(value:*, type:QName = null, restriction:XML = null):Number { return unmarshallDouble(value, type, restriction); } // FIXME: Should we always return String for all gregorian types? public function unmarshallGregorian(value:*, type:QName = null, restriction:XML = null):* { var rawValue:String = whitespaceCollapse(value); var result:* = rawValue; // FIXME: Consider timezone, if provided, for gregorian date info if (type == datatypes.gYearQName) { result = uint(rawValue.substring(0, 4)); } /* // FIXME: Should we leave YearMonth and MonthDay as String? else if (type == datatypes.gYearMonthQName) { result = rawValue.substring(0, 7); } else if (type == datatypes.gMonthDayQName) { result = rawValue.substring(2, 5); } */ else if (type == datatypes.gMonthQName) { result = uint(rawValue.substring(2, 4)); } else if (type == datatypes.gDayQName) { result = uint(rawValue.substring(3, 5)); } return result; } public function unmarshallHexBinary(value:*, type:QName = null, restriction:XML = null):ByteArray { if (value != null) { var data:String = whitespaceCollapse(value); var decoder:HexDecoder = new HexDecoder(); decoder.decode(data); return decoder.drain(); } return null; } public function unmarshallInteger(value:*, type:QName = null, restriction:XML = null):Number { return parseInt(value); } public function unmarshallString(value:*, type:QName = null, restriction:XML = null):String { var result:String; if (value != null) { result = value.toString(); } return result; } public static function guessSimpleType(value:*):* { var localName:String = ""string""; if (value is uint) { localName = ""unsignedInt""; } else if (value is int) { localName = ""int""; } else if (value is Number) { localName = ""double""; } else if (value is Boolean) { localName = ""boolean""; } else if (value is String) { localName = ""string""; } else if (value is ByteArray) { if (byteArrayAsBase64Binary) localName = ""base64Binary""; else localName = ""hexBinary""; } else if (value is Date) { localName = ""dateTime""; } return localName; } private static function specialNumber(value:Number):String { if (value == Number.NEGATIVE_INFINITY) return ""-INF""; else if (value == Number.POSITIVE_INFINITY) return ""INF""; else if (isNaN(value)) return ""NaN""; else return null; } /** * For simple types with the whitespace restriction collapse * all occurrences of #x9 (tab), #xA (line feed) and #xD (carriage return) * are replaced with #x20 (space), then consecutive spaces are collapsed * to a single space, then finally the leading and trailing spaces are * trimmed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private static function whitespaceCollapse(value:*):String { if (value == null) return null; var s:String = value.toString(); s = s.replace(whitespaceCollapsePattern, "" ""); s = s.replace(whitespaceTrimPattern, """"); return s; } /** * For simple types with the whitespace restriction replace * all occurrences of #x9 (tab), #xA (line feed) and #xD (carriage return) * are replaced with #x20 (space). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private static function whitespaceReplace(value:*):String { if (value == null) return null; var s:String = value.toString(); s = s.replace(whitespaceReplacePattern, "" ""); return s; } private function registerMarshallers():void { marshallers = {}; marshallers[datatypes.booleanQName.localName] = marshallBoolean; // Special built-in schema datatypes marshallers[datatypes.anyTypeQName.localName] = marshallAny; marshallers[datatypes.anySimpleTypeQName.localName] = marshallAny; marshallers[datatypes.anyAtomicTypeQName.localName] = marshallAny; // Primitive datatypes marshallers[datatypes.stringQName.localName] = marshallString; marshallers[datatypes.booleanQName.localName] = marshallBoolean; marshallers[datatypes.decimalQName.localName] = marshallDecimal; marshallers[datatypes.precisionDecimal.localName] = marshallDecimal; marshallers[datatypes.floatQName.localName] = marshallFloat; marshallers[datatypes.doubleQName.localName] = marshallDouble; marshallers[datatypes.durationQName.localName] = marshallDuration; marshallers[datatypes.dateTimeQName.localName] = marshallDatetime; marshallers[datatypes.timeQName.localName] = marshallDatetime; marshallers[datatypes.dateQName.localName] = marshallDatetime; marshallers[datatypes.gYearMonthQName.localName] = marshallGregorian; marshallers[datatypes.gYearQName.localName] = marshallGregorian; marshallers[datatypes.gMonthDayQName.localName] = marshallGregorian; marshallers[datatypes.gDayQName.localName] = marshallGregorian; marshallers[datatypes.gMonthQName.localName] = marshallGregorian; marshallers[datatypes.hexBinaryQName.localName] = marshallHexBinary; marshallers[datatypes.base64BinaryQName.localName] = marshallBase64Binary; marshallers[datatypes.anyURIQName.localName] = marshallString; marshallers[datatypes.QNameQName.localName] = marshallString; marshallers[datatypes.NOTATIONQName.localName] = marshallString; // Other built-in datatypes marshallers[datatypes.normalizedStringQName.localName] = marshallString; marshallers[datatypes.tokenQName.localName] = marshallString; marshallers[datatypes.languageQName.localName] = marshallString; marshallers[datatypes.NMTOKENQName.localName] = marshallString; marshallers[datatypes.NMTOKENSQName.localName] = marshallString; marshallers[datatypes.NameQName.localName] = marshallString; marshallers[datatypes.NCNameQName.localName] = marshallString; marshallers[datatypes.IDQName.localName] = marshallString; marshallers[datatypes.IDREF.localName] = marshallString; marshallers[datatypes.IDREFS.localName] = marshallString; marshallers[datatypes.ENTITY.localName] = marshallString; marshallers[datatypes.ENTITIES.localName] = marshallString; marshallers[datatypes.integerQName.localName] = marshallInteger; marshallers[datatypes.nonPositiveIntegerQName.localName] = marshallInteger; marshallers[datatypes.negativeIntegerQName.localName] = marshallInteger; marshallers[datatypes.longQName.localName] = marshallInteger; marshallers[datatypes.intQName.localName] = marshallInteger; marshallers[datatypes.shortQName.localName] = marshallInteger; marshallers[datatypes.byteQName.localName] = marshallInteger; marshallers[datatypes.nonNegativeIntegerQName.localName] = marshallInteger; marshallers[datatypes.unsignedLongQName.localName] = marshallInteger; marshallers[datatypes.unsignedIntQName.localName] = marshallInteger; marshallers[datatypes.unsignedShortQName.localName] = marshallInteger; marshallers[datatypes.unsignedByteQName.localName] = marshallInteger; marshallers[datatypes.positiveIntegerQName.localName] = marshallInteger; marshallers[datatypes.yearMonthDurationQName.localName] = marshallDatetime; marshallers[datatypes.dayTimeDurationQName.localName] = marshallDatetime; // 1999 if (datatypes.timeInstantQName != null) marshallers[datatypes.timeInstantQName.localName] = marshallDatetime; unmarshallers = {}; unmarshallers[datatypes.booleanQName.localName] = unmarshallBoolean; // Special built-in schema datatypes unmarshallers[datatypes.anyTypeQName.localName] = unmarshallAny; unmarshallers[datatypes.anySimpleTypeQName.localName] = unmarshallAny; unmarshallers[datatypes.anyAtomicTypeQName.localName] = unmarshallAny; // Primitive datatypes unmarshallers[datatypes.stringQName.localName] = unmarshallString; unmarshallers[datatypes.booleanQName.localName] = unmarshallBoolean; unmarshallers[datatypes.decimalQName.localName] = unmarshallDecimal; unmarshallers[datatypes.precisionDecimal.localName] = unmarshallDecimal; unmarshallers[datatypes.floatQName.localName] = unmarshallFloat; unmarshallers[datatypes.doubleQName.localName] = unmarshallDouble; unmarshallers[datatypes.durationQName.localName] = unmarshallDuration; unmarshallers[datatypes.dateTimeQName.localName] = unmarshallDatetime; unmarshallers[datatypes.timeQName.localName] = unmarshallDatetime; unmarshallers[datatypes.dateQName.localName] = unmarshallDate; unmarshallers[datatypes.gYearMonthQName.localName] = unmarshallGregorian; unmarshallers[datatypes.gYearQName.localName] = unmarshallGregorian; unmarshallers[datatypes.gMonthDayQName.localName] = unmarshallGregorian; unmarshallers[datatypes.gDayQName.localName] = unmarshallGregorian; unmarshallers[datatypes.gMonthQName.localName] = unmarshallGregorian; unmarshallers[datatypes.hexBinaryQName.localName] = unmarshallHexBinary; unmarshallers[datatypes.base64BinaryQName.localName] = unmarshallBase64Binary; unmarshallers[datatypes.anyURIQName.localName] = unmarshallString; unmarshallers[datatypes.QNameQName.localName] = unmarshallString; unmarshallers[datatypes.NOTATIONQName.localName] = unmarshallString; // Other built-in datatypes unmarshallers[datatypes.normalizedStringQName.localName] = unmarshallString; unmarshallers[datatypes.tokenQName.localName] = unmarshallString; unmarshallers[datatypes.languageQName.localName] = unmarshallString; unmarshallers[datatypes.NMTOKENQName.localName] = unmarshallString; unmarshallers[datatypes.NMTOKENSQName.localName] = unmarshallString; unmarshallers[datatypes.NameQName.localName] = unmarshallString; unmarshallers[datatypes.NCNameQName.localName] = unmarshallString; unmarshallers[datatypes.IDQName.localName] = unmarshallString; unmarshallers[datatypes.IDREF.localName] = unmarshallString; unmarshallers[datatypes.IDREFS.localName] = unmarshallString; unmarshallers[datatypes.ENTITY.localName] = unmarshallString; unmarshallers[datatypes.ENTITIES.localName] = unmarshallString; unmarshallers[datatypes.integerQName.localName] = unmarshallInteger; unmarshallers[datatypes.nonPositiveIntegerQName.localName] = unmarshallInteger; unmarshallers[datatypes.negativeIntegerQName.localName] = unmarshallInteger; unmarshallers[datatypes.longQName.localName] = unmarshallInteger; unmarshallers[datatypes.intQName.localName] = unmarshallInteger; unmarshallers[datatypes.shortQName.localName] = unmarshallInteger; unmarshallers[datatypes.byteQName.localName] = unmarshallInteger; unmarshallers[datatypes.nonNegativeIntegerQName.localName] = unmarshallInteger; unmarshallers[datatypes.unsignedLongQName.localName] = unmarshallInteger; unmarshallers[datatypes.unsignedIntQName.localName] = unmarshallInteger; unmarshallers[datatypes.unsignedShortQName.localName] = unmarshallInteger; unmarshallers[datatypes.unsignedByteQName.localName] = unmarshallInteger; unmarshallers[datatypes.positiveIntegerQName.localName] = unmarshallInteger; unmarshallers[datatypes.yearMonthDurationQName.localName] = unmarshallDatetime; unmarshallers[datatypes.dayTimeDurationQName.localName] = unmarshallDatetime; // 1999 if (datatypes.timeInstantQName != null) unmarshallers[datatypes.timeInstantQName.localName] = unmarshallDatetime; } /** * A Boolean flag to determines whether ActionScript ByteArrays should be * serialized as base64Binary or hexBinary when specific XML Schema type * information has not been provided. The default is true meaning * base64Binary. * * @see flash.utils.ByteArray * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static var byteArrayAsBase64Binary:Boolean = true; /** * A RegEx pattern to help replace all whitespace characters in the content * of certain simple types with #x20 (space) characters. The XML Schema * specification defines whitespace as #x9 (tab), #xA (line feed) and * #xD (carriage return). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static var whitespaceReplacePattern:RegExp = new RegExp(""[\\t\\r\\n]"", ""g""); /** * A RegEx pattern to help collapse all consecutive whitespace characters in * the content of certain simple types to a single #x20 (space) character. * The XML Schema specification defines whitespace as #x9 (tab), * #xA (line feed) and #xD (carriage return). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static var whitespaceCollapsePattern:RegExp = new RegExp(""[ \\t\\r\\n]+"", ""g""); /** * A RegEx pattern to help trim all leading and trailing spaces in the * content of certain simple types. For whitespace collapse, * this RegEx is executed after the whitespaceCollapsePattern RegEx has * been executed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static var whitespaceTrimPattern:RegExp = new RegExp(""^[ ]+|[ ]+$"", ""g""); public static const FLOAT_MAX_VALUE:Number = (Math.pow(2, 24) - 1) * Math.pow(2, 104); public static const FLOAT_MIN_VALUE:Number = Math.pow(2, -149); public static const LONG_MAX_VALUE:Number = 9223372036854775807; public static const LONG_MIN_VALUE:Number = -9223372036854775808; public static const SHORT_MAX_VALUE:Number = 32767; public static const SHORT_MIN_VALUE:Number = -32768; public static const BYTE_MAX_VALUE:Number = 127; public static const BYTE_MIN_VALUE:Number = -128; public static const ULONG_MAX_VALUE:Number = 18446744073709551615; public static const USHORT_MAX_VALUE:Number = 65535; public static const UBYTE_MAX_VALUE:Number = 255; private var marshallers:Object; private var unmarshallers:Object; private var constants:SchemaConstants; private var datatypes:SchemaDatatypes; private var _validating:Boolean; } }",12041,False,2402.940755884536,median "#define VERSION 24 // BOF preprocessor bug prevent - insert me on top of your arduino-code #if 1 __asm volatile (""nop""); #endif // set according to the baudrate of your serial console. used for debugging output #define BAUDRATE 115200 /* Fairytale Main program --------------------------------------------------------------------------------------- This programm will play albums (audiobooks or music) stored on the SD card inserted into the Adafruit Music Maker Shield. Selection of the album/audiobook to play is done by placing corresponding NFC Tags on the NFC Reader. There are two pissibilities on how the connection between an NFC Tag and the corresponding album on the SD card can be setup: 1. An NDEF Message written to the tag in the form of: en [directory name] 2. Via the so called TrackDB - txt-files for each album in the directory trackdb0 NDEF Implementation --------------------------------------------------------------------------------------- This implementation is based on the Speedmaster PN532 and Don's NDEF Library. Upon detection of an NFC Tag placed on the reader it will check if there is at least one NDEF Message written to the RFID tag. This message must be of the form en [directory name] for example, the audiobook ""Finding Nemo"", stored in files in the directory /findnemo would have an NDEF message on the tag which reads as en findnemo There may also be a second NDEF message for the track to start playback with and this would be in the form of en 1 for the first track. To use this implementation you have to activate the configuration option NFCNDEF below and you will have to write the NDEF Messages with the directory name. This can be done with the program staticNFCWriter.ino from this repository. There is a downside to this implementation. It lacks a usable update of the track to start playback with - I simply could not get it to work. Secondly the implementation lacks a reliable way of detecting the absence of a tag. Therefore the playback can only be stopped by turning the box off. The third problem is with the used progmem. The two libraries consume way too much progmem as opposed to the Adafruit PN532 library therefore I switched to: TrackDB-Implementation: --------------------------------------------------------------------------------------- Upon detection of an NFC Tag, the program will retrieve the tag's UID and use this to scan what I call the TrackDB to find a matching directory to play. The TrackDB is a list of files in a special directory (TRACKDB0) on the SD card. The TrackDB files are named after the directory of the album and their respective content is of the form: taguid:directory:track For example, the audiobook ""Finding Dorie"" is stored in the directory /findorie on the SD Card. The corresponding TrackDB file is stored at /trackdb0/findorie.txt It contains exactly one line: 46722634231761290:findorie:1 This line connects the Tag UID with the aformentioned directory plus the number of the track with which to start playback: 46722634231761290 the UID of the NFC Tag findorie the directory from which to play the files 1 the number of the track with which to start playback - here the 1st To use this implementation you need to activate the configuration NFCTRACKDB You will also need to create the necessary TrackDb files. This can be done with the program createTrackDb.ino from this repository. Playback and controls --------------------------------------------------------------------------------------- Regardless of the way the program retrieved the information on which directory to play (NDEF message or TrackDB), it will store this in the global var plrCurrentFolder and then start a for-loop beginning with the provided first track until all consecutive numbered tracks are played - for this it counts the number of files in the given dierctory. While the album (or file) is played an operations light is fading up and down in intensity. After playback of all files is finished, the program will resume it's main loop, delay operation for roughly 15 seconds (to give the user the chance to remove the just used Tag from the reader) and then wait until it detects the next tag. While advancing through the files in the directory, the program will update the TrackDB-File with the number of the currently played track. Doing so allows for interrupted playbacks - tag is removed and later put back on when the playback will start with the last track in playback. Restrictions --------------------------------------------------------------------------------------- For this to work, a couple of restrictions are in place: 1. All filenames must be in the format trackXXX.mp3, where XXX is a numbering from 001 to 127 2. Follows from 1: You can have a maximum of 127 files per directory. I use a char to count the files in a directory to preserve memory and need the ability to return -1 in case of an error 3. All directory names must be exactly 8 chars long. You may use any combination of a-z and 0-9 chars for the directory name though 4. if a file is missing in a consecutive order, you may get a glitch in the sound 5. As the Adafruit Music Maker Shield library does not support to jump to a specific position within a file, the box can always only start from the beginning of a track. Warnings and errors --------------------------------------------------------------------------------------- On warnings or errors a warning or error light is lit up respectively. There are 3 different warning or error conditions: 1) Missing information for playback warning 2) Low Battery warning 3) Missing hardware error Errors shown via the error light (also cause the system to halt): - Music Maker Shield not found - Music Maker shield not on an interrupt enabled pin - SD card not found - NFC Reader not found Warnings shown via a light (Arduino can stay turned on): - Low battery warning (surely the arduino will turn off but until then it will operate) - no directory found for the NFC Tag (aka TrackDB is missing an entry for the Tag) - no directory found on the SD card that match the NFC Tag TrackDB record - no files in the provided directory - a missing file in a consecutive list of ordered files in the directory this may happen in case the files are not numerically ordered without a gap: track001.mp3 exist, track002.mp3 is missing but track003.mp3 exists again Additionally to the warning or error lights certain messages are spoken through the music . maker shield. Voiced errors and warnings are: - Low Battery warning - no directory found for the NFC Tag (aka TrackDB is missing an entry for the Tag) - no directory found on the SD card that match the NFC Tag TrackDB record - no file(s) in the directory on the SD card Controls --------------------------------------------------------------------------------------- 4 buttons are included: - Previous Track - play the previous track in a consecurtive list of ordered files - Next Track - play the next track in a consecurtive list of ordered files - Pause / Resume - pauses the playback or unpauses a paused playback - Light on / off - turn the operations light fader on or off The box is capable of being controlled by a remote control with the following functions - Volume Up - increase volume by 5 per click - Volume Down - decrease volume by 5 per click - Previous Track - play the previous track in a consecurtive list of ordered files - Next Track - play the next track in a consecurtive list of ordered files - Pause / Resume - pauses the playback or unpauses a paused playback - Light on / off - turn the operations light fader on or off Used Pins: --------------------------------------------------------------------------------------- NAME PIN USAGE - CLK / PN532_SCK 13 SPI Clock shared with VS1053, SD card and NFC breakout board - MISO / PN532_MISO 12 Input data from VS1053, SD card and NFC breakout board - MOSI / PN532_MOSI 11 Output data to VS1053, SD card and NFC breakout board - SHIELD_CS 7 VS1053 chip select pin (output) - SHIELD_DCS 6 VS1053 Data/command select pin (output) - DREQ 3 VS1053 Data request, ideally an Interrupt pin - CARDCS 4 SD Card chip select pin - PN532_SS 10 NFC breakout board chip select pin - infoLedPin 5 the pin to which the operation led is connected to - warnLedPin 8 the pin to which the warning led is connected to - errorLedPin 9 the pin to which the error led is connected to e.g. used for LBO of powerboost 1000c - volPotPin A0 the analog input pin that we use for the potentiometer - btnLinePin A1 pin to which the button line (4 buttons) is connected to - lowBatPin A2 the pin on which the powerboost 1000c indicates a low baterry - not functional - iRRemotePin A3 the pin on which the IR Remote Receiver is connected to - programming A4 the pin the program button is connected to. The program button changes the functionality of the overall program in that (if pressed) the code will register a new tag for use with an album directory currently not connected to a tag Functionality yet to come! Configuration --------------------------------------------------------------------------------------- Some features (as e.g. Remote Control, Buttons or operation LED etc.) can be turned off or on via #define switches in the code below. #define IRREMOTE enables the IR Remote Control option #define BUTTONS enables the 4 control buttons #define VOLUMEPOT enables the volume potentiometer #define LOWBAT enables the low battery warning with light and voice #define OPRLIGHT enables the operations light on the front of the box #define OPRLIGHTTIME enables time based operations light - turns off the light after 30 Minutes #define NFCNDEF enables the use of NDEF messages to get the directory for a tag #define NFCTRACKDB enables the use of the TrackDB to get the directiry for a tag #define ALBUMNFC enables a special file albumnfc.tdb in which all album <-> nfc connections are stored - additional to the TrackDb files #define RESUMELAST enables the option to resume last played album upon startup. This is achieved via a file in the TrackDB and works without a tag but uses the pause/resume button instead */ // // CCCCC OOOOOO NN NN FFFFFF // CC OO OO NNN NN FF // CC OO OO NN NN NN FFFF // CC OO OO NN NNN FF // CCCCC OOOOOO NN NN FF // // make sure to comment this out before uploading in production as it turns on lots and lots of serial messages // if it is not define, no Serial.print is possible, as also Serial.begin() is omitted #define DEBUG 1 // to enable periodic output of free RAM during playBack, uncomment the following line. //#define RAMCHECK 1 // // turn ON / OFF certain hardware/software features // // to enable the IR Remote Control option uncomment the following line - does not work currently //#define IRREMOTE 1 // to enable the 4 control buttons uncomment the following line #define BUTTONS 1 // to enable the volume potentiometer uncomment the follwing line #define VOLUMEPOT 1 // to enable the low battery warning with light and voice uncomment the follwing line //#define LOWBAT 1 // to enable the operations light on the front of the box, uncomment the following line #define OPRLIGHT 1 // to enable time based operations light - turns off the light after 30 Minutes - uncomment the following line //#define OPRLIGHTTIME 1 // Define the NFC <-> Album implementation // ONLY ONE of the these two options can be chosen // to use NDEF to get the album directory uncomment the following line #define NFCNDEF 1 // to use the Adafruit NFC library to get the Tag UID and retrieve the directory from the trackDb // uncomment the following line. //#define NFCTRACKDB 1 // uncomment to enable a special file albumnfc.tdb in which all album <-> nfc connections are stored // this is an additional storage to the individual TrackDb files and requires NFCTRACKDB //#define ALBUMNFC 1 // uncomment the next line to enable resuming the last played album on switch on // this is achieved via a special file on the SD card and works without a tag but uses the pause/resume button instead //#define RESUMELAST 1 // uncomment the next line to activate the VS1053 Component on the Music Maker Shield - aka the MP3 Player #define VS1053 1 // uncomment the next line to activate the SD-CARD component on the Music Maker Shield #define SDCARD 1 // // II NN NN CCCCC LL UU UU DDDDDD EEEEEE SSSSSS // II NNN NN CC LL UU UU DD DD EE SS // II NN NN NN CC LL UU UU DD DD EEEE SSSS // II NN NNN CC LL UU UU DD DD EE SS // II NN NN CCCCC LLLLLL UUUUUU DDDDDD EEEEEE SSSSSS // // DDDDDD EEEEEE FFFFFF II NN NN EEEEEE SSSSSS // DD DD EE FF II NNN NN EE SS // DD DD EEEE FFFF II NN NN NN EEEE SSSS // DD DD EE FF II NN NNN EE SS // DDDDDD EEEEEE FF II NN NN EEEEEE SSSSSS // // include SPI and SD libraries // #include #include // These are the SPI pins shared among all components #define CLK 13 // SPI Clock shared with VS1053, SD card and NFC breakout board #define MISO 12 // Input data from VS1053, SD card and NFC breakout board #define MOSI 11 // Output data to VS1053, SD card and NFC breakout board // // SETUP MUSIC MAKER SHIELD // #include // These are the pins used for the music maker shield #define SHIELD_RESET -1 // VS1053 reset pin (unused!) #define SHIELD_CS 7 // VS1053 chip select pin (output) #define SHIELD_DCS 6 // VS1053 Data/command select pin (output) // // SETUP SD CARD // // These are common pins between breakout and shield #define CARDCS 4 // Card chip select pin // DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt #define DREQ 3 // VS1053 Data request, ideally an Interrupt pin // Create shield object Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS); // // SETUP NFC ADAPTER // // this implementation uses the Speedmaster Library and Don's NDEF library to read NFC Tags and // get the album directory that is stored as an NDEF Message on the tag. That means, it does NOT // use the decribed TrackDB. It is also much heavier (in Progmem size than the Adafruit PN532 // implementation below and does NOT support recognition of a removed track. Furthermore the user // has to turn off the box before she can listen to the next album :-( #ifdef NFCNDEF // these includes are sued for the NDEF implementation #include #include #include #define PN532_SCK 13 // SPI Clock shared with VS1053, SD card and NFC breakout board #define PN532_MISO 12 // Input data from VS1053, SD card and NFC breakout board #define PN532_MOSI 11 // Output data to VS1053, SD card and NFC breakout board #define PN532_SS 10 // NFC breakout board chip select pin PN532_SPI pn532spi(SPI, PN532_SS); NfcAdapter nfc = NfcAdapter(pn532spi); #endif // this implementation uses the Adafruit PN532 library alone - it is way smaller and preferrable // as it allows for tag removal recognition and does not enforce the user to turn off the box // after an album was played, as the above implementation does. #ifdef NFCTRACKDB // INCLUDE Adafruit NFC LIbrary here #include #include //#define PN532_SCK 13 // SPI Clock shared with VS1053, SD card and NFC breakout board //#define PN532_MISO 12 // Input data from VS1053, SD card and NFC breakout board //#define PN532_MOSI 11 // Output data to VS1053, SD card and NFC breakout board #define PN532_SS 10 // NFC breakout board chip select pin //Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS); Adafruit_PN532 nfc(SCK, MISO, MOSI, PN532_SS); #endif // // include IR Remote Control // #ifdef IRREMOTE #include #endif // VV VV Y RRRRR // VV VV AAA RR RR // VV VV AA AA RRRRRR // VV VV AAAAAAA RR RR // V AA AA RR RR // // mp3 player variables char plrCurrentFolder[] = ""system00""; // directory containing the currently played tracks char filename[] = ""/system00/track001.mp3""; // path and filename of the track to play byte firstTrackToPlay = 1; // the track number to play (used for the loop) char nextTrackToPlay = 1; // the track number to play next (or -1 in case of an error) // file to hold the last played album (aka directory) name - from here we may retrieve other data from the trackDb #ifdef RESUMELAST const char resumeLastFile[] = ""/trackdb0/LASTPLAY.TDB""; #endif // trackDb on the SD card - this is where we store the NFC TAG <-> Directory connection and the track to start playback with // and is the complementary implementation to the NDEF messages on the NFC Tag - see option NFCNDEF #ifdef NFCTRACKDB const char trackDbDir[] = ""/trackdb0""; // where do we store the TrackDB files for each album char trackDbFile[23]; // path to the file with uid, directory and track char trackDbEntry[35]; // will hold a nfc <-> album info connection // in the form of [NFC Tag UID]:[album]:[Track] e.g.: 43322634231761291:larsrent:1 #ifdef ALBUMNFC // a special file that additionally holds the connection between an NFC tag UID and the corresponding directory const char albumNfcFile[] = ""/trackdb0/albumnfc.tdb""; #endif // NFC Tag data byte uid[] = { 0, 0, 0, 0, 0, 0, 0 };// Buffer to store the returned UID char charUid[22]; // char representation of the UID byte uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) #endif // volume control variables for the analog poti #ifdef VOLUMEPOT const byte volPotPin = A0; // the analog input pin that we use for the potentiometer word lastVolSensorValue = 0; // keeps the last read sensor value #endif // control buttons definition #ifdef BUTTONS const byte btnLinePin = A1; // pin on which the button line (4 buttons) is connected word btnVal; // stores the value we receive on the btnLinePin for comparance with the predefined analog reads for the 4 buttons const byte btnValDrift = 5; // maximum allowed difference + and - the predefined value for each button we allow const word btnPressDelay = 500; // delay in milliseconds to prevent double press detection unsigned long btnPressTime = 0; // time in millis() when the button was pressed const word btnLightValue = 1021; // 33 Ohm - The value we receive from analog input if the Light On/Off Button is pressed const word btnPauseValue = 933; // 1K Ohm - The value we receive from analog input if the Pause Button is pressed const word btnNextValue = 1002; // 220 Ohm - The value we receive from analog input if the Next (aka Fast Forward) Button is pressed const word btnPrevValue = 991; // 330 Ohm - The value we receive from analog input if the Previos (aka Prev or Rewind) Button is pressed const word minBtnValue = 800; // we use this value to determine, whether or not to check the buttons. Set to lower val than smallest of buttons #endif // IR remote control #ifdef IRREMOTE const byte iRRemotePin = A3; // the pin the IR remote control diode (receiver) is connected to // IR Remote control // to reduce PROGMEM size I decided to not use the whole decimal value for each button on the remote control but instead do a calculation // which reduces the needed size of the variable to hold the value but still creates different values for each button // Function Original code Minus DIV code I use // right: 2011291898 - 2011000000) / 100 = 2919 // left: 2011238650 - 2011000000) / 100 = 2387 // Up: 2011287802 - 2011000000) / 100 = 2878 // Down: 2011279610 - 2011000000) / 100 = 2796 // Middle: 2011282170 - 2011000000) / 100 = 2822 // Pause: 2011265786 - 2011000000) / 100 = 2658 // Menu: 2011250938 - 2011000000) / 100 = 2509 const uint16_t nextVal = 2919; // decoded value if button NEXT is pressed on remote const uint16_t prevVal = 2387; // decoded value if button PREV is pressed on remote const uint16_t volUpVal = 2878; // decoded value if button UP is pressed on remote const uint16_t volDwnVal = 2796; // decoded value if button DOWN is pressed on remote const uint16_t lightVal = 2822; // decoded value if button HOME is pressed on remote const uint16_t pauseVal = 2658; // decoded value if button PAUSE is pressed on remote const uint16_t menuVal = 2509; // decoded value if button MENU is pressed on remote IRrecv irrecv(iRRemotePin); // define an object to read infrared sensor on pin A4 decode_results results; // make sure decoded values from IR are stored #endif // battery control #ifdef LOWBAT const byte lowBatPin = A2; // pin on which the Adafruit PowerBoost will indicate a low battery // this pin will usually be pulled high but when the charger detects // a low voltage (under 3.2V) the pin will drop down to 0V (LOW) unsigned long lowBatCheckTime = 0; // used to throttle low battery messages to every 5 minutes #endif // LIGHT EFFECTS #ifdef OPRLIGHT #ifdef OPRLIGHTTIME unsigned long lightStartUpTime = 0; // millis() the operations light started #endif const byte infoLedPin = 5; // the pin to which the operation led is connected to boolean lightOn = true; // if true, the operations light fader is active. switched via a button, // set to false after a maxLightTime (in case of OPRLIGHTTIME) is reached #endif const byte warnLedPin = 8; // the pin to which the warning led is connected to const byte errorLedPin = 9; // the pin to which the error led is connected to // // PPPPPP RRRRR OOOOOO TTTTTTTT OOOOOO TTTTTTTT YY YY PPPPPP EEEEE SSSSS // PP PP RR RR OO OO TT OO OO TT YY YY PP PP EE SS // PPPPPPP RRRRRRR OO OO TT OO OO TT YYYY PPPPPPP EEEE SSSSS // PP RR RR OO OO TT OO OO TT YY PP EE SS // PP RR RR OOOOOO TT OOOOOO TT YY PP EEEEEE SSSSS // // these are the prototypes to retrieve and set directory and track to play - aka work on the tagdb static boolean getDirAndTrackToPlay(boolean); // retrieves the directory and track number static boolean writeTrackDbEntry(void); // store Tag UID, plrCurrentFolder and firstTrackToPlay in the trackDb (files on SD) // prototype for NFC check for tag presence #ifdef NFCTRACKDB static boolean checkTag(void); // check if the tag is still on the reader - returns true or falce #endif // prototype for volume control via potentiometer #ifdef VOLUMEPOT static void plrAdjustVolume(void); // function to check for changes on the volume control and adjust volume accrodingly #endif // these are the prototypes for the mp3 player controller static void plrStop(void); // stops the player static void plrTogglePause(void); // pause and unpause the player static char playAlbum(uint8_t); // plays the album from plrCurrentFolder: returns -1 for error or a higher // calls playTrack to actually play a track and check if that was successful and which // track number to play next static char playTrack(uint8_t); // plays a track as defined by the global var filename. // returns -1 for error, 0 for success and track number to play next // this can either be provided char+1 or char-1 // prototype for warning static void issueWarning(const char[], const char[], boolean); // the new warning method // these are the prototypes to work on files and general helpers static uint8_t countFiles(File); // return the number of files in a directory passed as a File descriptor // helper functions to set global vars static boolean setFileNameToPlay(byte); // sets filename of the track to play from global vars plrCurrentFolder and plrCurrentFile and returns true if it exists static void setTrackDbEntry(void); // these are the prototypes for the led #ifdef OPRLIGHT // switch the boolean var lightOn from true to false and vice versa // - in case light is lightOn is set to true, lightStartUpTime is set to millis() static void switchLightState(void); #endif // // SSSSSS EEEEEE TTTTTTTT UU UU PPPPP // SS EE TT UU UU PP PP // SSSSS EEEE TT UU UU PPPPPP // SS EE TT UU UU PP // SSSSSS EEEEEE TT UUUUU PP // void setup() { // SETUP SERIAL CONSOLE #ifdef DEBUG // in case we want debug output Serial.begin(BAUDRATE); #endif #ifdef RAMCHECK // or at least print out available RAM Serial.begin(38400); #endif // DEFINE INPUT PINs #ifdef VOLUMEPOT pinMode(volPotPin, INPUT); // connects to the potentiometer that shall control the volume #endif #ifdef BUTTONS pinMode(btnLinePin, INPUT); // connects to the 4 buttons with different resistors (set the value down in function playTrack()) #endif #ifdef LOWBAT pinMode(lowBatPin, INPUT); // connects to the LBO pin of the Adafruit PowerBoost 1000c #endif #ifdef IRREMOTE pinMode(iRRemotePin, INPUT); // connects to the output port of the remote control (decoded values for each button in function playTrack()) #endif // DEFINE OUPUT PINs #ifdef OPRLIGHT pinMode(infoLedPin, OUTPUT); // connect to blue LED #endif pinMode(warnLedPin, OUTPUT); // connect to orange LED pinMode(errorLedPin, OUTPUT); // connect to a red LED // INITIALIZE THE MUSIC PLAYER #ifdef VS1053 if (!musicPlayer.begin()) { #ifdef DEBUG Serial.println(F(""VS1053 Not found"")); #endif // flash the red light to indicate we have an error for (;;) { digitalWrite(errorLedPin, HIGH); } } // This option uses a pin interrupt. No timers required! But DREQ // must be on an interrupt pin. For Uno/Duemilanove/Diecimilla // that's Digital #2 or #3 // See http://arduino.cc/en/Reference/attachInterrupt for other pins if (! musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT)) { #ifdef DEBUG Serial.println(F(""No interrupt on DREQ pin"")); #endif for (;;) { digitalWrite(errorLedPin, HIGH); } } #endif // INITIALIZE THE SD CARD #ifdef SDCARD if (!SD.begin(CARDCS)) { #ifdef DEBUG Serial.println(F(""SD-Card Not found"")); #endif // flash the red light to indicate we have an error for (;;) { digitalWrite(errorLedPin, HIGH); } } #endif // PLAY THE WELCOME SOUND #ifdef VOLUMEPOT plrAdjustVolume(); // initiallly adjust volume #endif if (playTrack(1) == -1) { // play the welcome sound issueWarning(""HELLO error"", """", false); } // START THE NFC READER #ifdef NFCNDEF // either use the simple one with NDEF support to get the tag <-> album directory connection nfc.begin(); #endif #ifdef NFCTRACKDB // or use the Adafruit implementation, which allows for resume and rescan etc. // but needs the trackDB to get the album directory for a tag as no NDEF messages are supported nfc.begin(); // make sure to comment this out after PN532 is working as it takes approx 290 bytes from progmem uint32_t versiondata = nfc.getFirmwareVersion(); if (! versiondata) { #ifdef DEBUG Serial.print(""Didn't find PN53x board""); #endif for (;;) { digitalWrite(errorLedPin, HIGH); } } #ifdef DEBUG // Got ok data, print it out! Serial.print(F(""Found chip PN5"")); Serial.println((versiondata>>24) & 0xFF, HEX); Serial.print(F(""Firmware ver. "")); Serial.print((versiondata>>16) & 0xFF, DEC); Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); #endif // configure board to read RFID tags nfc.setPassiveActivationRetries(0xFF); nfc.SAMConfig(); #endif // ALL DONE delay(100); // wait some time for everything to settle #ifdef OPRLIGHT digitalWrite(infoLedPin, LOW); // turn off the info led delay(100); // wait some time for everything to settle digitalWrite(infoLedPin, HIGH); // turn off the info led delay(100); // wait some time for everything to settle digitalWrite(infoLedPin, LOW); // turn off the info led delay(100); // wait some time for everything to settle digitalWrite(infoLedPin, HIGH); // turn off the info led delay(100); // wait some time for everything to settle digitalWrite(infoLedPin, LOW); // turn off the info led #endif // check our current time, so we know when to stop //startUpTime = millis(); #ifdef DEBUG Serial.print(F(""fairytale V""));Serial.print(VERSION);Serial.print(F("" - waiting "")); #endif } // // LL OOOOOO OOOOOO PPPPPPP // LL OO OO OO OO PP PP // LL OO OO OO OO PPPPPPP // LL OO OO OO OO PP // LLLLLL OOOOOO OOOOOO PP // void loop() { boolean weHaveATag = false; // set true if a tag is present and false boolean resumeLast = false; // set true when pause button (also on IR Remote) is pressed boolean loopWarningMessageNoAlbumInfos = true; // make sure we get the ""no album info on tag"" message at least once boolean loopWarningMessageNoFilesInDir = true; // make sure we get the ""no files in dir"" message at least once #ifdef DEBUG Serial.print(F(""."")); #endif // check for tag presence #ifdef NFCNDEF // this implementation uses the Speedmaster Library and Don's NDEF lib weHaveATag = nfc.tagPresent(1000); #endif #ifdef NFCTRACKDB // this implementation uses the Adafruit PN532 library alone weHaveATag = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); #endif // this allows for the pause/resume button to be pressed without a tag being present // in this case the last played album is resumed - given there was one. #ifdef RESUMELAST // Of course works only when we have the Buttons #ifdef BUTTONS btnVal = analogRead(btnLinePin); if (btnVal > minBtnValue && (millis()-btnPressTime) > btnPressDelay) if ( ((btnVal - btnValDrift) < btnPauseValue) && ((btnVal + btnValDrift) > btnPauseValue) ) resumeLast = true; #endif // ... or the IR Remote Control implementation #ifdef IRREMOTE if (irrecv.decode(&results)) if ( ((results.value-2011000000)/100) == pauseVal ) resumeLast = true; #endif #endif // if a tag is found or the pause button is pressed without a tag, we continue if (weHaveATag || resumeLast) { #ifdef DEBUG if (weHaveATag) Serial.println(F("" tag found!"")); else Serial.println(F("" resume last album"")); #endif // read data from tag: directory, track number and playing order. if (!getDirAndTrackToPlay(weHaveATag)) { // if we don't get at least a directory we can't start playback and inform the user if (loopWarningMessageNoAlbumInfos) { loopWarningMessageNoAlbumInfos = false; issueWarning(""no album info"", ""/system00/nodirtag.mp3"", true); } } else { // we may start playing as it seems // now let's get the number of files in the album directory uint8_t numberOfFiles = countFiles(SD.open(plrCurrentFolder)); // there is no file in the folder indicate this as a minor error if (numberOfFiles < 1) { if (loopWarningMessageNoFilesInDir) { loopWarningMessageNoFilesInDir = false; // set loop warning message so we don't show this warning in the next loop issueWarning(""no files found"", ""/system00/nofilesd.mp3"", true); } } else { char retVal = playAlbum(numberOfFiles); retVal = nextTrackToPlay; if (retVal < 0) { issueWarning(""playback failed"", ""/system00/playfail.mp3"", true); } else { #ifdef DEBUG Serial.println(F(""\\nplayback end"")); #endif digitalWrite(warnLedPin, LOW); } } // end of check if at least 1 file was found } // end of directory plus track retrieved from nfc tag // finally turn off the info led #ifdef OPRLIGHT if (lightOn) digitalWrite(infoLedPin, LOW); #endif // RESET THE NFC READER #ifdef NFCNDEF // this now clears the NFC reader so it will recognize a new tag again nfc.begin(); #endif } // end of tag is present delay(1000); // throttle the loop for 1 second // check if the battery is still good #ifdef LOWBAT if (digitalRead(lowBatPin == LOW)) { if ((millis()-lowBatCheckTime > 300000)) { digitalWrite(errorLedPin, HIGH); issueWarning(""BATTERY LOW"", ""/system00/lowbat01.mp3"", true); lowBatCheckTime = millis(); } } #endif } // end of loop // // VV VV OOOOOO LL // VV VV OO OO LL // VV VV OO OO LL // VVVV OO OO LL // VV OOOOOO LLLLLL // // BELOW THIS LINE THE MP3 PLAYER CONTROL IS DEFINED // // included in while loop of playTrack() for checks for volume changes #ifdef VOLUMEPOT static void plrAdjustVolume() { // volume control functions const byte volSensorDrift = 7; // difference to last received sensor value that must be exceeded to activate a change in the volume word volCompareValue = 0; // just a convenience variable to make comparison easier // read the input on analog pin 0 and check if we have a change in volume. const word volSensorValue = analogRead(volPotPin); if (lastVolSensorValue > volSensorValue) { volCompareValue = lastVolSensorValue - volSensorValue; } else { volCompareValue = volSensorValue - lastVolSensorValue; } // If we have a high enough difference in the sensor reading, calculate it so we may set it on the player if (volCompareValue > volSensorDrift) { const byte soundVolume = volSensorValue / 10; // map the sensor value to a sound volume #ifdef DEBUG Serial.print(F(""old sensor: "")); Serial.print(lastVolSensorValue); Serial.print(F("", new sensor: "")); Serial.print(volSensorValue); Serial.print(F("", vol: -"")); Serial.println(soundVolume); #endif lastVolSensorValue = volSensorValue; musicPlayer.setVolume(soundVolume, soundVolume); } // end of change sound volume } #endif // // MM MM PPPPPP 33333 // MMMM MMMM PP PP 33 // MM MM MM PP PP 3333 // MM MM PPPPPP 33 // MM MM PP 33333 // // BELOW THIS LINE THE MP3 PLAYER CONTROL IS DEFINED // // stop playback static void plrStop(void) { musicPlayer.stopPlaying(); } // toggle pause static void plrTogglePause(void) { if (!musicPlayer.paused()) { #ifdef DEBUG Serial.println(F(""Playback pause"")); #endif musicPlayer.pausePlaying(true); } else { #ifdef DEBUG Serial.println(F(""Playback resume"")); #endif musicPlayer.pausePlaying(false); } } // iterates through al files in an album directory and calls playTrack for each track number iteratively static char playAlbum(uint8_t numberOfFiles) { boolean loopWarningMessageFileNotFound = true;// make sure file not found warning message is shown at least once #ifdef DEBUG Serial.print(F(""Folder: "")); Serial.print(plrCurrentFolder); Serial.print(F("" / Files: "")); Serial.println(numberOfFiles); #endif #ifdef OPRLIGHTTIME lightStartUpTime = millis(); // store the time in millis when the playback-for-loop started, so we can later check, whether or not the light shall continue to be on #endif for (byte curTrack = firstTrackToPlay; curTrack <= numberOfFiles; curTrack++) { digitalWrite(warnLedPin, LOW); // in each for-loop, we make sure that the warning LED is NOT lit up // set the filename we want to play in the global variable so the playTrack() function knows what to play if (!setFileNameToPlay(curTrack)) { // set filename does not exit on SD card :-( if (loopWarningMessageFileNotFound) { loopWarningMessageFileNotFound = false; // set loop warning message so we don't show this warning in the next loop issueWarning(""file not found"", ""/system00/filnotfn.mp3"", true); } break; // try the filename - we break the for loop and skip to next number } #ifdef DEBUG Serial.print(F(""Track "")); Serial.print(curTrack); Serial.print(F(""/""));Serial.print(numberOfFiles);Serial.print(F("": ""));Serial.println(filename); #endif // make sure we remember the just started track to be the new track, in case player is stopped // this works only with the NFC TrackDb and not with the NFC NDEF implementation #ifdef NFCTRACKDB if (curTrack != firstTrackToPlay) { // in case we are on the last track, choose the first track, so we start playback all from the beginning. if (curTrack == numberOfFiles) firstTrackToPlay = 1; else firstTrackToPlay = curTrack; // now store this new first track in the TrackDB // first create the new trackDb entry: setTrackDbEntry(); // second store this entry in the TrackDb files, plus optional in the albumnfc.tdb file if (!writeTrackDbEntry()) { issueWarning(""trackdb update error"", """", false); } } #endif // play the track on the music maker shield and retrieve the nextTrackToPlay from global variable (it is set by playTrack()) // -1 errors trying to play the file (like file not found) // 0 success - the file was played // 1-127 any positive number for the next track to play // from an album standpoint this can also be a previous track on the album to play next playTrack(curTrack); if (nextTrackToPlay == -1) { issueWarning(""playback failed"", ""/system00/playfail.mp3"", false); break; } else if (nextTrackToPlay == 1) { curTrack = 1; } else { curTrack = nextTrackToPlay; } if (curTrack == numberOfFiles) return(0); } // end of loop through files return(0); } // play a single track within an album - is called by playAlbum() or by issueWarning() static char playTrack(uint8_t trackNo) { #ifdef OPRLIGHTTIME const unsigned long maxLightTime = 1800000L;// how long shall the light stay on while nothing is playing - 1800000L = 30 Minutes #endif const unsigned int checkInterval = 10000L; // time in milliseconds between checks for battery status, tag presence and max light time /* #ifdef BUTTONS // the 4 control buttons - defined in global section word btnVal; // stores the value we receive on the btnLinePin for comparance with the predefined analog reads for the 4 buttons const byte btnValDrift = 5; // maximum allowed difference + and - the predefined value for each button we allow const word btnPressDelay = 500; // delay in milliseconds to prevent double press detection unsigned long btnPressTime = 0; // time in millis() when the button was pressed const word btnLightValue = 1021; // 33 Ohm - The value we receive from analog input if the Light On/Off Button is pressed const word btnPauseValue = 933; // 1K Ohm - The value we receive from analog input if the Pause Button is pressed const word btnNextValue = 1002; // 220 Ohm - The value we receive from analog input if the Next (aka Fast Forward) Button is pressed const word btnPrevValue = 991; // 330 Ohm - The value we receive from analog input if the Previos (aka Prev or Rewind) Button is pressed const word minBtnValue = 800; // we use this value to determine, whether or not to check the buttons. Set to lower val than smallest of buttons #endif #ifdef IRREMOTE // IR Remote control - defined in global section // to reduce PROGMEM size I decided to not use the whole decimal value for each button on the remote control but instead do a calculation // which reduces the needed size of the variable to hold the value but still creates different values for each button // Function Original code Minus DIV code I use // right: 2011291898 - 2011000000) / 100 = 2919 // left: 2011238650 - 2011000000) / 100 = 2387 // Up: 2011287802 - 2011000000) / 100 = 2878 // Down: 2011279610 - 2011000000) / 100 = 2796 // Middle: 2011282170 - 2011000000) / 100 = 2822 // Pause: 2011265786 - 2011000000) / 100 = 2658 // Menu: 2011250938 - 2011000000) / 100 = 2509 const uint16_t nextVal = 2919; // decoded value if button NEXT is pressed on remote const uint16_t prevVal = 2387; // decoded value if button PREV is pressed on remote const uint16_t volUpVal = 2878; // decoded value if button UP is pressed on remote const uint16_t volDwnVal = 2796; // decoded value if button DOWN is pressed on remote const uint16_t lightVal = 2822; // decoded value if button HOME is pressed on remote const uint16_t pauseVal = 2658; // decoded value if button PAUSE is pressed on remote const uint16_t menuVal = 2509; // decoded value if button MENU is pressed on remote #endif */ if (!musicPlayer.startPlayingFile(filename)) { nextTrackToPlay = -1; return (nextTrackToPlay); } unsigned long checkTime = millis(); // // LETS PLAY THE TRACK // while (musicPlayer.playingMusic || musicPlayer.paused()) { // file is now playing in the 'background' so now's a good time // to do something else like handling LEDs or buttons :) #ifdef OPRLIGHT // fade the light if (lightOn && musicPlayer.paused()) analogWrite(infoLedPin, 5); if (lightOn && !musicPlayer.paused()) analogWrite(infoLedPin, 128 + 127 * cos(2 * PI / 20000 * millis())); #endif // every ten seconds we do some checks if ((millis()-checkTime) > checkInterval) { #ifdef RAMCHECK Serial.print(F(""free RAM: "")); Serial.println(freeRam()); #endif // check if we shall still fade the info light - depends on max light time and light startup time and also on the light button state #ifdef OPRLIGHTTIME if (((millis()-lightStartUpTime) > maxLightTime) && lightOn) { #ifdef DEBUG //Serial.println(F(""Max Light Time reached, turn light off"")); #endif switchLightState(); } #endif // check if the battery is still good #ifdef LOWBAT if (digitalRead(lowBatPin == LOW)) digitalWrite(errorLedPin, HIGH); #endif // check if we can still read the tag and if not, stop/pause the playback #ifdef NFCTRACKDB if (!checkTag()) plrTogglePause(); #endif checkTime = millis(); // reset checktime so we can wait another 10 seconds aka 10000 ms } // check for changes to volume and adjust accordingly #ifdef VOLUMEPOT plrAdjustVolume(); #endif // check for button presses to pause, play next or previous track or turn lights on/off #ifdef BUTTONS btnVal = analogRead(btnLinePin); if (btnVal > minBtnValue && (millis()-btnPressTime) > btnPressDelay) { btnPressTime = millis(); #ifdef DEBUG // Serial.print(F(""VALUE: ""));Serial.print(btnVal - btnValDrift); // Serial.print(F("" < "")); Serial.print(btnVal); Serial.print(F("" < "")); Serial.print(btnVal + btnValDrift); #endif // // Button Layout on the box: // // +-------+ +-------+ +-------+ +-------+ // | PAUSE | | | | LIGHT | // +-------+ +-------+ +-------+ +-------+ // // PAUSE if ( ((btnVal - btnValDrift) < btnPauseValue) && ((btnVal + btnValDrift) > btnPauseValue) ) { plrTogglePause(); //musicPlayer.sineTest(0x42, 100); // Make a tone to indicate button press } // PREV if ( ((btnVal - btnValDrift) < btnPrevValue) && ((btnVal + btnValDrift) > btnPrevValue) ) { plrStop(); if (trackNo > 2) nextTrackToPlay = trackNo - 2; else nextTrackToPlay = 0; #ifdef DEBUG Serial.print(F(""Prev track ""));Serial.print(nextTrackToPlay);Serial.println(F("" set"")); #endif musicPlayer.sineTest(0x42, 100); // Make a tone to indicate button press return(nextTrackToPlay); } // NEXT if ( ((btnVal - btnValDrift) < btnNextValue) && ((btnVal + btnValDrift) > btnNextValue) ) { plrStop(); nextTrackToPlay = trackNo; #ifdef DEBUG Serial.print(F(""Next track ""));Serial.print(nextTrackToPlay);Serial.println(F("" set"")); #endif musicPlayer.sineTest(0x42, 100); // Make a tone to indicate button press return(nextTrackToPlay); } // LIGHT #ifdef OPRLIGHT if ( ((btnVal - btnValDrift) < btnLightValue) && ((btnVal + btnValDrift) > btnLightValue) ) { switchLightState(); //musicPlayer.sineTest(0x40, 100); // Make a tone to indicate button press } #endif } #endif #ifdef IRREMOTE // IR Remote Control Layout // +-------+ // | UP | // +-------+ // +-------+ +-------+ +-------+ // | LEFT | | HOME | | RIGHT | // +-------+ +-------+ +-------+ // +-------+ // | DOWN | // +-------+ // +-------+ +-------+ // | PAUSE | | MENU | // +-------+ +-------+ // // check for IR Remote Control action if (irrecv.decode(&results)) { // get data from IR Remote switch ((results.value-2011000000)/100) { // PREV case prevVal: #ifdef DEBUG Serial.print(F(""Prev track ""));Serial.print(nextTrackToPlay);Serial.println(F("" set"")); #endif plrStop(); musicPlayer.sineTest(0x42, 100); // Make a tone to indicate button press if (trackNo > 2) nextTrackToPlay = trackNo - 2; else nextTrackToPlay = 0; return(nextTrackToPlay); break; // NEXT case nextVal: #ifdef DEBUG Serial.print(F(""Next track ""));Serial.print(nextTrackToPlay);Serial.println(F("" set"")); #endif plrStop(); musicPlayer.sineTest(0x42, 100); // Make a tone to indicate button press nextTrackToPlay = trackNo; return(nextTrackToPlay); break; // PAUSE case pauseVal: plrTogglePause(); break; // LIGHT #ifdef OPRLIGHT case lightVal: switchLightState(); break; #endif // VOL UP case volUpVal: #ifdef DEBUG Serial.println(F(""Volume Up"")); #endif break; // VOL DOWN case volDwnVal: #ifdef DEBUG Serial.println(F(""Volume Down"")); #endif break; // MENU // CURRENTLY NO FUNCTION FOR MENU //case menuVal: // #ifdef DEBUG // Serial.println(F("" - Menu Button Pressed"")); // #endif // break; default: break; } delay(50); irrecv.resume(); } #endif // check if the player is still playing our sounds and is NOT paused - otherwise we return a 0 to indicate successfull end of playback if (!musicPlayer.playingMusic && !musicPlayer.paused()) { nextTrackToPlay = trackNo; return (nextTrackToPlay); } } // end of while playing music nextTrackToPlay = trackNo; return (nextTrackToPlay); } // // TTTTTTTTTT RRRRRR AA CCCCC KK KK DDDDDD BBBBBB // TT RR RR AAAA CC KK KK DD DD BB BB // TT RRRRRR AA AA CC KKKK DD DD BBBBBB // TT RR RR AAAAAAAA CC KK KK DD DD BB BB // TT RR RR AA AA CCCCC KK KK DDDDDD BBBBBB // // sets the directpry to play (plrCurrentFolder) and the track to start playback with (firstTrackToPlay) static boolean getDirAndTrackToPlay(boolean readFromTag) { boolean plrStartPlaying = false; if (readFromTag) { #ifdef NFCNDEF // GET ALBUM DIRECTORY TO PLAY FROM TAG NDEF MESSAGES NfcTag tag = nfc.read(); #ifdef DEBUG Serial.print(F(""Tag Type: "")); Serial.println(tag.getTagType()); Serial.print(F(""UID: "")); Serial.println(tag.getUidString()); #endif if (tag.hasNdefMessage()) { NdefMessage message = tag.getNdefMessage(); // If you have more than 1 Message then it will cycle through them for (byte i = 0; i < message.getRecordCount(); i++) { NdefRecord record = message.getRecord(i); byte payloadLength = record.getPayloadLength(); // get length of record byte payload[payloadLength]; // initialise payload variable to store content of record record.getPayload(payload); // extract the payload of this record char* p; // this is where we store the result of strtok() p = strtok((char *)payload, "" ""); // separate payload on space-delimiter as it's form is like this: en bluemc99 or equivalent p = strtok(NULL, "" ""); // we only need the second entry and strtok() expects NULL for string on subsequent calls switch (i) { case 0: plrStartPlaying = true; memset(plrCurrentFolder, 0, sizeof(plrCurrentFolder)); memcpy(plrCurrentFolder, p, 8); // copy directory from tag into global player var - so we know which dir to play files from break; case 1: byte i; i = atoi(p); firstTrackToPlay = i; // copy track number to firstTrackToPlay - so we know where to start the playback break; default: break; } } //return (plrStartPlaying); } #endif #ifdef NFCTRACKDB // GET ALBUM DIRECTORY TO PLAY FROM TRACKDB #endif } else { // GET FROM LAST PLAYED SESSION FILE } return (plrStartPlaying); } // write the created trackDbEntry into the Track DB on SD #ifdef NFCTRACKDB static boolean writeTrackDbEntry() { boolean success = true; byte bytesWritten; #ifdef DEBUG Serial.print(F(""saving nfc <-> album: ""));Serial.println(trackDbEntry); #endif // FIRST (if set) write the AlbumNFC file --> ALBUMNFC.TDB #ifdef ALBUMNFC File file = SD.open(albumNfcFile, FILE_WRITE); bytesWritten = file.write(trackDbEntry, sizeof(trackDbEntry)); file.close(); // and make sure everything is clean and save // now check if the write was successful - means we wrote the number of bytes of the trackDb entry to the file if (bytesWritten == sizeof(albumNfcFile)) { #ifdef DEBUG Serial.print(F("" ok. ""));Serial.print(bytesWritten);Serial.print(F("" byte(s) written to ""));Serial.println(albumNfcFile); #endif success = true; } else { #ifdef DEBUG Serial.print(F("" error writing ""));Serial.println(albumNfcFile); #endif digitalWrite(warnLedPin, HIGH); success = false; } #endif // SECOND write the TrackDb-File --> e.g. larsrent.txt memset(trackDbFile, 0, sizeof(trackDbFile)); // make sure var to hold path to track db file is empty strcat(trackDbFile, trackDbDir); // add the trackDb Directory to the strcat(trackDbFile, ""/""); // a / strcat(trackDbFile, plrCurrentFolder); // and the filename strcat(trackDbFile, "".txt""); // plus of course a txt extension SD.remove(trackDbFile); // we want the file to be empty prior writing directory and track to it, so we remove it // used in case the albumnfc.tdb file is written first - redeclare file var #ifdef ALBUMNFC file = SD.open(trackDbFile, FILE_WRITE); #endif // used in case we only write the TrackDB file - need to initially declare file var #ifndef ALBUMNFC File file = SD.open(trackDbFile, FILE_WRITE); #endif bytesWritten = file.write(trackDbEntry, sizeof(trackDbEntry)); file.close(); // now check if the write was successful - means we wrote the number of bytes of the trackDb entry to the file if (bytesWritten == sizeof(trackDbEntry)) { #ifdef DEBUG Serial.print(F("" ok. ""));Serial.print(bytesWritten);Serial.print(F("" byte(s) written to ""));Serial.println(trackDbFile); #endif success = true; } else { #ifdef DEBUG Serial.print(F("" error writing ""));Serial.println(trackDbFile); #endif digitalWrite(warnLedPin, HIGH); success = false; } // THIRD (if set) write the plrCurrentFolder (aka the album directory) to the file /trackdb0/LASTPLAY.TDB #ifdef RESUMELAST file = SD.open(resumeLastFile, FILE_WRITE); bytesWritten = file.write(plrCurrentFolder, sizeof(plrCurrentFolder)); file.close(); #endif return (success); } #endif // // NN NN FFFFFF CCCCC // NNN NN FF CC // NN NN NN FFFF CC // NN NNN FF CC // NN NN FF CCCCC // // check Tag presence is used in the loop() (to populate the char array with the uid of the tag) and in function playTrack() to see // if the tag is still on the reader - this can only be used with the Adafruit NFC library #ifdef NFCTRACKDB boolean checkTag() { boolean sameTagPresent = true; return(sameTagPresent); } #endif // // HH HH EEEEEE LL PPPPPP EEEEEE RRRRRR // HH HH EE LL PP PP EE RR RR // HHHHHHHH EEEE LL PPPPPPP EEEE RRRRR // HH HH EE LL PP EE RR RR // HH HH EEEEEE LLLLLL PP EEEEEE RR RR // // stores the file to play in the global var filename - it is created from the gloal vars plrCurrentFolder and current track static boolean setFileNameToPlay(byte trackNo) { // convert the trackNo to a char array - we need it next to create the filename of the track char curTrackCharNumber[4]; sprintf(curTrackCharNumber, ""%03d"", trackNo); // create the filename of the track to play, including path, so we can feed it to the music player strcpy(filename, """"); strcat(filename, ""/""); strcat(filename, plrCurrentFolder); strcat(filename, ""/""); strcat(filename, ""track""); strcat(filename, curTrackCharNumber); strcat(filename, "".mp3""); // return true or false for the filename created - this is checked return (SD.exists(filename)); } // store uid, plrCurrentFolder and firstTrackToPlay in the char array trackDbEntry[] // so we may write it to the track Db file #ifdef NFCTRACKDB static void setTrackDbEntry() { char tmpbuf[4]; // temp buffer for one number of the uid // create the entry for the ""Tag UID <-> directory + track number"" connection memset(trackDbEntry, 0, sizeof(trackDbEntry)); for (byte i = 0; i <= uidLength ; i++) { sprintf( tmpbuf, ""%d"", uid[i] ); // print one byte of the uid as decimal into tmpbuf, so strcat( charUid, tmpbuf ); // we can add it to the charUid } memcpy(trackDbEntry, charUid, sizeof(charUid)); // finally we add the charUid to the trackDbENtry strcat(trackDbEntry, "":""); // add a seperator : strcat(trackDbEntry, plrCurrentFolder); // the folder of the album this tag is connected with char cstr[4]; // a new char array that will hold firstTrackToPlay as a char array itoa(firstTrackToPlay, cstr, 10); // converting firstTrackToPlay to char and place it in cstr strcat(trackDbEntry, "":""); // and the number of the track strcat(trackDbEntry, cstr); // and the number of the track strcat(trackDbEntry, ""\\n""); // and a newline :-) } #endif #ifdef RAMCHECK // return the free RAM - called periodically during playTrack() int freeRam () { extern int __heap_start, *__brkval; int v; return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); } #endif // // FFFFFF II LL EEEEEE // FF II LL EE // FFFF II LL EEEE // FF II LL EE // FF II LLLLLL EEEEEE // // BELOW THIS LINE THE FILE HELPER FUNCTIONS CAN BE FOUND // // counts the number of files in directory static uint8_t countFiles(File dir) { uint8_t counter = 0; while (true) { File entry = dir.openNextFile(); // Skip directories and hidden files. //if (!entry.isSubDir() && !entry.isHidden()) { if (!entry) { // no more files break; } counter++; entry.close(); //} } dir.close(); return (counter); } // // WW WW AA RRRRRR NNNN NN // WW WW WW AAAA RR RR NN NN NN // WW WWWW WW AA AA RR RR NN NN NN // WWWW WWWW AAAAAAAA RRRRRRR NN NN NN // WW WW AA AA RR RR NN NNNN // static void issueWarning(const char msg[20], const char filename[23], boolean voiceOutput) { #ifdef DEBUG Serial.println(msg); #endif if (voiceOutput && SD.exists(filename)) { musicPlayer.playFullFile(filename); } /*else { musicPlayer.sineTest(0x30, 200); // Make a tone to indicate warning }*/ digitalWrite(warnLedPin, HIGH); } // // LL EEEEEE DDDDDD // LL EE DD DD // LL EEEE DD DD // LL EE DD DD // LLLLLL EEEEEE DDDDDD // // switches the value of lightOn between true and false - only needed in case there is a LED attached #ifdef OPRLIGHT static void switchLightState(void) { if (!lightOn) { #ifdef DEBUG Serial.println(F(""Switching light off -> ON"")); #endif lightOn = true; #ifdef OPRLIGHTTIME lightStartUpTime = millis(); // also sets the lightStartUpTime #endif } else { #ifdef DEBUG Serial.println(F(""Switching light on -> OFF"")); #endif lightOn = false; digitalWrite(infoLedPin, LOW); // also turns off the info led } } #endif ",16305,True,2792.336182696019,median "package starling.core { import starling.animation.Juggler; import starling.display.DisplayObject; import starling.display.Stage; import starling.events.EventDispatcher; import starling.events.ResizeEvent; import starling.events.TouchPhase; import starling.events.TouchProcessor; import starling.utils.HAlign; import starling.utils.SystemUtil; import starling.utils.VAlign; import starling.utils.execute; import com.assukar.airong.utils.Debug; import com.assukar.airong.utils.Utils; import com.assukar.engine.utils.UncaughtErrorHandler; import flash.display.InteractiveObject; import flash.display.Shape; import flash.display.Sprite; import flash.display.Stage3D; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.display3D.Context3D; import flash.display3D.Context3DCompareMode; import flash.display3D.Context3DRenderMode; import flash.display3D.Context3DTriangleFace; import flash.display3D.Program3D; import flash.errors.IllegalOperationError; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TouchEvent; import flash.geom.Rectangle; import flash.system.Capabilities; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.ui.Mouse; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.getTimer; import flash.utils.setTimeout; /** Dispatched when a new render context is created. The 'data' property references the context. */ [Event(name=""context3DCreate"", type=""starling.events.Event"")] /** Dispatched when the root class has been created. The 'data' property references that object. */ [Event(name=""rootCreated"", type=""starling.events.Event"")] /** Dispatched when a fatal error is encountered. The 'data' property contains an error string. */ [Event(name=""fatalError"", type=""starling.events.Event"")] /** Dispatched when the display list is about to be rendered. This event provides the last * opportunity to make changes before the display list is rendered. */ [Event(name=""render"", type=""starling.events.Event"")] /** The Starling class represents the core of the Starling framework. * *

The Starling framework makes it possible to create 2D applications and games that make * use of the Stage3D architecture introduced in Flash Player 11. It implements a display tree * system that is very similar to that of conventional Flash, while leveraging modern GPUs * to speed up rendering.

* *

The Starling class represents the link between the conventional Flash display tree and * the Starling display tree. To create a Starling-powered application, you have to create * an instance of the Starling class:

* *
var starling:Starling = new Starling(Game, stage);
* *

The first parameter has to be a Starling display object class, e.g. a subclass of * starling.display.Sprite. In the sample above, the class ""Game"" is the * application root. An instance of ""Game"" will be created as soon as Starling is initialized. * The second parameter is the conventional (Flash) stage object. Per default, Starling will * display its contents directly below the stage.

* *

It is recommended to store the Starling instance as a member variable, to make sure * that the Garbage Collector does not destroy it. After creating the Starling object, you * have to start it up like this:

* *
starling.start();
* *

It will now render the contents of the ""Game"" class in the frame rate that is set up for * the application (as defined in the Flash stage).

* * Context3D Profiles * *

Stage3D supports different rendering profiles, and Starling works with all of them. The * last parameter of the Starling constructor allows you to choose which profile you want. * The following profiles are available:

* *
    *
  • BASELINE_CONSTRAINED: provides the broadest hardware reach. If you develop for the * browser, this is the profile you should test with.
  • *
  • BASELINE: recommend for any mobile application, as it allows Starling to use a more * memory efficient texture type (RectangleTextures). It also supports more complex * AGAL code.
  • *
  • BASELINE_EXTENDED: adds support for textures up to 4096x4096 pixels. This is * especially useful on mobile devices with very high resolutions.
  • *
* *

The recommendation is to deploy your app with the profile ""auto"" (which makes Starling * pick the best available of those three), but test it in all available profiles.

* * Accessing the Starling object * *

From within your application, you can access the current Starling object anytime * through the static method Starling.current. It will return the active Starling * instance (most applications will only have one Starling object, anyway).

* * Viewport * *

The area the Starling content is rendered into is, per default, the complete size of the * stage. You can, however, use the ""viewPort"" property to change it. This can be useful * when you want to render only into a part of the screen, or if the player size changes. For * the latter, you can listen to the RESIZE-event dispatched by the Starling * stage.

* * Native overlay * *

Sometimes you will want to display native Flash content on top of Starling. That's what the * nativeOverlay property is for. It returns a Flash Sprite lying directly * on top of the Starling content. You can add conventional Flash objects to that overlay.

* *

Beware, though, that conventional Flash content on top of 3D content can lead to * performance penalties on some (mobile) platforms. For that reason, always remove all child * objects from the overlay when you don't need them any longer. Starling will remove the * overlay from the display list when it's empty.

* * Multitouch * *

Starling supports multitouch input on devices that provide it. During development, * where most of us are working with a conventional mouse and keyboard, Starling can simulate * multitouch events with the help of the ""Shift"" and ""Ctrl"" (Mac: ""Cmd"") keys. Activate * this feature by enabling the simulateMultitouch property.

* * Handling a lost render context * *

On some operating systems and under certain conditions (e.g. returning from system * sleep), Starling's stage3D render context may be lost. Starling can recover from a lost * context if the class property ""handleLostContext"" is set to ""true"". Keep in mind, however, * that this comes at the price of increased memory consumption; Starling will cache textures * in RAM to be able to restore them when the context is lost. (Except if you use the * 'AssetManager' for your textures. It is smart enough to recreate a texture directly * from its origin.)

* *

In case you want to react to a context loss, Starling dispatches an event with * the type ""Event.CONTEXT3D_CREATE"" when the context is restored. You can recreate any * invalid resources in a corresponding event listener.

* * Sharing a 3D Context * *

Per default, Starling handles the Stage3D context itself. If you want to combine * Starling with another Stage3D engine, however, this may not be what you want. In this case, * you can make use of the shareContext property:

* *
    *
  1. Manually create and configure a context3D object that both frameworks can work with * (through stage3D.requestContext3D and * context.configureBackBuffer).
  2. *
  3. Initialize Starling with the stage3D instance that contains that configured context. * This will automatically enable shareContext.
  4. *
  5. Call start() on your Starling instance (as usual). This will make * Starling queue input events (keyboard/mouse/touch).
  6. *
  7. Create a game loop (e.g. using the native ENTER_FRAME event) and let it * call Starling's nextFrame as well as the equivalent method of the other * Stage3D engine. Surround those calls with context.clear() and * context.present().
  8. *
* *

The Starling wiki contains a tutorial with more * information about this topic.

* */ public class Starling extends EventDispatcher { static private const LOG_SHARE_CONTEXT:Boolean = false; /** The version of the Starling framework. */ public static const VERSION:String = ""1.8""; /** The key for the shader programs stored in 'contextData' */ private static const PROGRAM_DATA_NAME:String = ""Starling.programs""; // members private var mStage3D:Stage3D; private var mStage:Stage; // starling.display.stage! private var mRootClass:Class; private var mRoot:DisplayObject; private var mJuggler:Juggler; private var mSupport:RenderSupport; private var mTouchProcessor:TouchProcessor; private var mAntiAliasing:int; private var mSimulateMultitouch:Boolean; // private var mEnableErrorChecking:Boolean; private var mLastFrameTimestamp:Number; private var mLeftMouseDown:Boolean; private var mStatsDisplay:StatsDisplay; private var mShareContext:Boolean; private var mProfile:String; private var mContext:Context3D; private var mStarted:Boolean; private var mRendering:Boolean; private var mSupportHighResolutions:Boolean; private var mBroadcastKeyboardEvents:Boolean; private var mViewPort:Rectangle; private var mPreviousViewPort:Rectangle; private var mClippedViewPort:Rectangle; private var mNativeStage:flash.display.Stage; private var mNativeOverlay:Sprite; private var mNativeStageContentScaleFactor:Number; private static var sCurrent:Starling; private static var sHandleLostContext:Boolean = true; private static var sContextData:Dictionary = new Dictionary(true); private static var sAll:Vector. = new []; // construction /** Creates a new Starling instance. * @param rootClass A subclass of 'starling.display.DisplayObject'. It will be created * as soon as initialization is finished and will become the first child * of the Starling stage. Pass null if you don't want to * create a root object right away. (You can use the * rootClass property later to make that happen.) * @param stage The Flash (2D) stage. * @param viewPort A rectangle describing the area into which the content will be * rendered. Default: stage size * @param stage3D The Stage3D object into which the content will be rendered. If it * already contains a context, sharedContext will be set * to true. Default: the first available Stage3D. * @param renderMode The Context3D render mode that should be requested. * Use this parameter if you want to force ""software"" rendering. * @param profile The Context3D profile that should be requested. * *
    *
  • If you pass a profile String, this profile is enforced.
  • *
  • Pass an Array of profiles to make Starling pick the first * one that works (starting with the first array element).
  • *
  • Pass the String ""auto"" to make Starling pick the best available * profile automatically.
  • *
*/ public function Starling( rootClass:Class, stage:flash.display.Stage, viewPort:Rectangle = null, stage3D:Stage3D = null, renderMode:String = ""auto"", profile:Object = ""baselineConstrained"" ) { if (stage == null) throw new ArgumentError(""Stage must not be null""); if (viewPort == null) viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); if (stage3D == null) stage3D = stage.stage3Ds[0]; SystemUtil.initialize(); sAll.push(this); makeCurrent(); mRootClass = rootClass; mViewPort = viewPort; mPreviousViewPort = new Rectangle(); mStage3D = stage3D; mStage = new Stage(viewPort.width, viewPort.height, stage.color); mNativeOverlay = new Sprite(); mNativeStage = stage; mNativeStage.addChild(mNativeOverlay); mNativeStageContentScaleFactor = 1.0; mTouchProcessor = new TouchProcessor(mStage); mJuggler = new Juggler(); mAntiAliasing = 0; mSimulateMultitouch = false; // mEnableErrorChecking = false; mSupportHighResolutions = false; mBroadcastKeyboardEvents = true; mLastFrameTimestamp = getTimer() / 1000.0; mSupport = new RenderSupport(); // for context data, we actually reference by stage3D, since it survives a context loss sContextData[stage3D] = new Dictionary(); sContextData[stage3D][PROGRAM_DATA_NAME] = new Dictionary(); // all other modes are problematic in Starling, so we force those here stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // register touch/mouse event handlers for each (var touchEventType:String in touchEventTypes) stage.addEventListener(touchEventType, onTouch, false, 0, true); // register other event handlers stage.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_UP, onKey, false, 0, true); stage.addEventListener(Event.RESIZE, onResize, false, 0, true); stage.addEventListener(Event.MOUSE_LEAVE, onMouseLeave, false, 0, true); mStage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false, 10, true); mStage3D.addEventListener(ErrorEvent.ERROR, onStage3DError, false, 10, true); if (mStage3D.context3D && mStage3D.context3D.driverInfo != ""Disposed"") { if (profile == ""auto"" || profile is Array) throw new ArgumentError(""When sharing the context3D, "" + ""the actual profile has to be supplied""); else mProfile = ""profile"" in mStage3D.context3D ? mStage3D.context3D[""profile""] : profile as String; mShareContext = true; setTimeout(initialize, 1); // we don't call it right away, because Starling should // behave the same way with or without a shared context if (LOG_SHARE_CONTEXT) Utils.log(""STARLING:SHARECONTEXT mShareContext="" + mShareContext + "" mProfile="" + mProfile); } else { if (!SystemUtil.supportsDepthAndStencil) Utils.log(""[Starling] Mask support requires 'depthAndStencil' to be enabled"" + "" in the application descriptor.""); mShareContext = false; requestContext3D(stage3D, renderMode, profile); if (LOG_SHARE_CONTEXT) Utils.log(""STARLING:SHARECONTEXT mShareContext="" + mShareContext); } } public function set nativeFocus( newFocus:InteractiveObject ):void { nativeStage.focus = newFocus; } /** Disposes all children of the stage and the render context; removes all registered * event listeners. */ public function dispose():void { stop(true); mNativeStage.removeEventListener(Event.ENTER_FRAME, onEnterFrame, false); mNativeStage.removeEventListener(KeyboardEvent.KEY_DOWN, onKey, false); mNativeStage.removeEventListener(KeyboardEvent.KEY_UP, onKey, false); mNativeStage.removeEventListener(Event.RESIZE, onResize, false); mNativeStage.removeEventListener(Event.MOUSE_LEAVE, onMouseLeave, false); mNativeStage.removeChild(mNativeOverlay); mStage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false); mStage3D.removeEventListener(ErrorEvent.ERROR, onStage3DError, false); for each (var touchEventType:String in touchEventTypes) mNativeStage.removeEventListener(touchEventType, onTouch, false); if (mStage) mStage.dispose(); if (mSupport) mSupport.dispose(); if (mTouchProcessor) mTouchProcessor.dispose(); if (sCurrent == this) sCurrent = null; if (LOG_SHARE_CONTEXT) Utils.log(""STARLING:SHARECONTEXT dispose mShareContext="" + mShareContext + "" mContext="" + mContext); if (mContext && !mShareContext) { // Per default, the context is recreated as long as there are listeners on it. // Beginning with AIR 3.6, we can avoid that with an additional parameter. execute(mContext.dispose, false); } var index:int = sAll.indexOf(this); if (index != -1) sAll.splice(index, 1); } // functions private function requestContext3D( stage3D:Stage3D, renderMode:String, profile:Object ):void { var profiles:Array; var currentProfile:String; if (profile == ""auto"") profiles = [""standardExtended"", ""standard"", ""standardConstrained"", ""baselineExtended"", ""baseline"", ""baselineConstrained""]; else if (profile is String) profiles = [profile as String]; else if (profile is Array) profiles = profile as Array; else throw new ArgumentError(""Profile must be of type 'String' or 'Array'""); mStage3D.addEventListener(Event.CONTEXT3D_CREATE, onCreated, false, 100); mStage3D.addEventListener(ErrorEvent.ERROR, onError, false, 100); requestNextProfile(); function requestNextProfile():void { currentProfile = profiles.shift(); try { execute(mStage3D.requestContext3D, renderMode, currentProfile); } catch (error:Error) { if (profiles.length != 0) setTimeout(requestNextProfile, 1); else throw error; } } function onCreated( event:Event ):void { var context:Context3D = stage3D.context3D; if (renderMode == Context3DRenderMode.AUTO && profiles.length != 0 && context.driverInfo.indexOf(""Software"") != -1) { onError(event); } else { mProfile = currentProfile; onFinished(); } } function onError( event:Event ):void { if (profiles.length != 0) { event.stopImmediatePropagation(); setTimeout(requestNextProfile, 1); } else onFinished(); } function onFinished():void { mStage3D.removeEventListener(Event.CONTEXT3D_CREATE, onCreated); mStage3D.removeEventListener(ErrorEvent.ERROR, onError); } } public var pendingInitialization:Boolean = true; public var initializations:int = 0; private function initialize():void { makeCurrent(); initializeGraphicsAPI(); initializeRoot(); mTouchProcessor.simulateMultitouch = mSimulateMultitouch; mLastFrameTimestamp = getTimer() / 1000.0; pendingInitialization = false; // Utils.printStackTrace(""pendingInitialization = false""); } private function initializeGraphicsAPI():void { mContext = mStage3D.context3D; mContext.enableErrorChecking = Debug.active; contextData[PROGRAM_DATA_NAME] = new Dictionary(); Utils.log(""Starling:: Initialization "" + mContext.driverInfo); updateViewPort(true); dispatchEventWith(Event.CONTEXT3D_CREATE, false, mContext); } private function initializeRoot():void { if (mRoot == null && mRootClass != null) { mRoot = new mRootClass() as DisplayObject; if (mRoot == null) throw new Error(""Invalid root class: "" + mRootClass); mStage.addChildAt(mRoot, 0); dispatchEventWith(starling.events.Event.ROOT_CREATED, false, mRoot); } } /** Calls advanceTime() (with the time that has passed since the last frame) * and render(). */ // private var passedTime:Number; public function get framePassedTime():Number { return (getTimer() / 1000.0) - mLastFrameTimestamp; } public function nextFrame():void { starlingScaleFactorr = 0.0; var now:Number = getTimer() / 1000.0; var passedTime:Number = now - mLastFrameTimestamp; mLastFrameTimestamp = now; // to avoid overloading time-based animations, the maximum delta is truncated. if (passedTime > 1.0) passedTime = 1.0; // after about 25 days, 'getTimer()' will roll over. A rare event, but still ... if (passedTime < 0.0) passedTime = 1.0 / mNativeStage.frameRate; advanceTime(passedTime); // added mRendering check as advanceTime might have stopped rendering if (mRendering) render(); } /** Dispatches ENTER_FRAME events on the display list, advances the Juggler * and processes touches. */ public function advanceTime( passedTime:Number ):void { if (!contextValid) return; makeCurrent(); mTouchProcessor.advanceTime(passedTime); mStage.advanceTime(passedTime); mJuggler.advanceTime(passedTime); } // obj-tion private var scaleX1:Number, scaleY1:Number; /** Renders the complete display list. Before rendering, the context is cleared; afterwards, * it is presented (to avoid this, enable shareContext). * *

This method also dispatches an Event.RENDER-event on the Starling * instance. That's the last opportunity to make changes before the display list is * rendered.

*/ public function render():void { if (!contextValid) return; makeCurrent(); updateViewPort(); dispatchEventWith(starling.events.Event.RENDER); scaleX1 = mViewPort.width / mStage.stageWidth; scaleY1 = mViewPort.height / mStage.stageHeight; mContext.setDepthTest(false, Context3DCompareMode.ALWAYS); mContext.setCulling(Context3DTriangleFace.NONE); mSupport.nextFrame(); mSupport.stencilReferenceValue = 0; mSupport.renderTarget = null; // back buffer mSupport.setProjectionMatrix(mViewPort.x < 0 ? -mViewPort.x / scaleX1 : 0.0, mViewPort.y < 0 ? -mViewPort.y / scaleY1 : 0.0, mClippedViewPort.width / scaleX1, mClippedViewPort.height / scaleY1, mStage.stageWidth, mStage.stageHeight, mStage.cameraPosition); if (!mShareContext) { RenderSupport.clear(mStage.color, 1.0); } mStage.render(mSupport, 1.0); mSupport.finishQuadBatch(); if (mStatsDisplay) mStatsDisplay.drawCount = mSupport.drawCount; if (!mShareContext) { //Utils.log(""PRESENT "" + mContext); mContext.present(); } } private function updateViewPort( forceUpdate:Boolean = false ):void { // the last set viewport is stored in a variable; that way, people can modify the // viewPort directly (without a copy) and we still know if it has changed. if (forceUpdate || mPreviousViewPort.width != mViewPort.width || mPreviousViewPort.height != mViewPort.height || mPreviousViewPort.x != mViewPort.x || mPreviousViewPort.y != mViewPort.y) { mPreviousViewPort.setTo(mViewPort.x, mViewPort.y, mViewPort.width, mViewPort.height); // Constrained mode requires that the viewport is within the native stage bounds; // thus, we use a clipped viewport when configuring the back buffer. (In baseline // mode, that's not necessary, but it does not hurt either.) mClippedViewPort = mViewPort.intersection(new Rectangle(0, 0, mNativeStage.stageWidth, mNativeStage.stageHeight)); if (LOG_SHARE_CONTEXT) Utils.log(""STARLING:SHARECONTEXT updateViewPort mShareContext="" + mShareContext + "" mProfile="" + mProfile); if (!mShareContext) { // setting x and y might move the context to invalid bounds (since changing // the size happens in a separate operation) -- so we have no choice but to // set the backbuffer to a very small size first, to be on the safe side. if (mProfile == ""baselineConstrained"") { configureBackBuffer(32, 32, mAntiAliasing, false); } mStage3D.x = mClippedViewPort.x; mStage3D.y = mClippedViewPort.y; configureBackBuffer(mClippedViewPort.width, mClippedViewPort.height, mAntiAliasing, // true, // mSupportHighResolutions); if (mSupportHighResolutions && ""contentsScaleFactor"" in mNativeStage) mNativeStageContentScaleFactor = mNativeStage[""contentsScaleFactor""]; else mNativeStageContentScaleFactor = 1.0; } } } /** Configures the back buffer while automatically keeping backwards compatibility with * AIR versions that do not support the ""wantsBestResolution"" argument. */ private function configureBackBuffer( width:int, height:int, antiAlias:int, enableDepthAndStencil:Boolean, wantsBestResolution:Boolean = false ):void { enableDepthAndStencil &&= SystemUtil.supportsDepthAndStencil; var configureBackBuffer:Function = mContext.configureBackBuffer; var methodArgs:Array = [width, height, antiAlias, enableDepthAndStencil]; if (configureBackBuffer.length > 4) methodArgs.push(wantsBestResolution); configureBackBuffer.apply(mContext, methodArgs); } private function updateNativeOverlay():void { mNativeOverlay.x = mViewPort.x; mNativeOverlay.y = mViewPort.y; mNativeOverlay.scaleX = mViewPort.width / mStage.stageWidth; mNativeOverlay.scaleY = mViewPort.height / mStage.stageHeight; } /** Stops Starling right away and displays an error message on the native overlay. * This method will also cause Starling to dispatch a FATAL_ERROR event. */ public function stopWithFatalError( message:String ):void { var background:Shape = new Shape(); background.graphics.beginFill(0x0, 0.8); background.graphics.drawRect(0, 0, mStage.stageWidth, mStage.stageHeight); background.graphics.endFill(); var textField:TextField = new TextField(); var textFormat:TextFormat = new TextFormat(""Verdana"", 14, 0xFFFFFF); textFormat.align = TextFormatAlign.CENTER; textField.defaultTextFormat = textFormat; textField.wordWrap = true; textField.width = mStage.stageWidth * 0.75; textField.autoSize = TextFieldAutoSize.CENTER; textField.text = message; textField.x = (mStage.stageWidth - textField.width) / 2; textField.y = (mStage.stageHeight - textField.height) / 2; textField.background = true; textField.backgroundColor = 0x550000; updateNativeOverlay(); nativeOverlay.addChild(background); nativeOverlay.addChild(textField); stop(true); Utils.log(""[Starling]"", message); dispatchEventWith(starling.events.Event.FATAL_ERROR, false, message); } /** Make this Starling instance the current one. */ public function makeCurrent():void { sCurrent = this; } /** As soon as Starling is started, it will queue input events (keyboard/mouse/touch); * furthermore, the method nextFrame will be called once per Flash Player * frame. (Except when shareContext is enabled: in that case, you have to * call that method manually.) */ public function start():void { mStarted = mRendering = true; mLastFrameTimestamp = getTimer() / 1000.0; } /** Stops all logic and input processing, effectively freezing the app in its current state. * Per default, rendering will continue: that's because the classic display list * is only updated when stage3D is. (If Starling stopped rendering, conventional Flash * contents would freeze, as well.) * *

However, if you don't need classic Flash contents, you can stop rendering, too. * On some mobile systems (e.g. iOS), you are even required to do so if you have * activated background code execution.

*/ public function stop( suspendRendering:Boolean = false ):void { mStarted = false; mRendering = !suspendRendering; } // event handlers private function onStage3DError( event:ErrorEvent ):void { if (event.errorID == 3702) { var mode:String = Capabilities.playerType == ""Desktop"" ? ""renderMode"" : ""wmode""; stopWithFatalError(""Context3D not available! Possible reasons: wrong "" + mode + "" or missing device support.""); } else stopWithFatalError(""Stage3D error: "" + event.text); } private function onContextCreated( event:Event ):void { initializations++; pendingInitialization = true; // Utils.printStackTrace(""pendingInitialization=true initializations="" + initializations); if (!Starling.handleLostContext && mContext) { event.stopImmediatePropagation(); stopWithFatalError(""The application lost the device context!""); Utils.log(""[Starling] Enable 'Starling.handleLostContext' to avoid this error.""); } else { initialize(); } } public var enterFrameDate:Date; public var frameLength:Number = 0; public var frameCount:uint = 0; //used to space out asset pushs between frames private var frameCallbacks:Vector.; public function pushFrameCallback( callback:Function ):void { if (!frameCallbacks) frameCallbacks = new []; frameCallbacks.push(callback); } public function renderFrame():void { enterFrameDate = new Date(); if (isStarted) { if (!UncaughtErrorHandler.ERROR) { nextFrame(); } else { UncaughtErrorHandler.ERROR = false; try { nextFrame(); } catch (err:Error) { stop(); juggler.purge(); Utils.logError(err, true); start(); } } } else render(); frameLength = new Date().getTime() - enterFrameDate.getTime(); } private function onEnterFrame( event:Event ):void { frameCount++; // On mobile, the native display list is only updated on stage3D draw calls. // Thus, we render even when Starling is paused. if (!mShareContext) { renderFrame(); } mNativeOverlay.x = mViewPort.x; mNativeOverlay.y = mViewPort.y; mNativeOverlay.scaleX = mViewPort.width / mStage.stageWidth; mNativeOverlay.scaleY = mViewPort.height / mStage.stageHeight; if (frameCallbacks) { for (var i:int = 0; i < 1 && frameCallbacks.length > 0; i++) { // Utils.log(""CALLING FRAMECALLBACK "" + i); var acallback:Function = frameCallbacks.shift() as Function; acallback(); } if (frameCallbacks.length == 0) frameCallbacks = null; } } private function onKey( event:KeyboardEvent ):void { if (!mStarted) return; var keyEvent:starling.events.KeyboardEvent = new starling.events.KeyboardEvent(event.type, event.charCode, event.keyCode, event.keyLocation, event.ctrlKey, event.altKey, event.shiftKey); makeCurrent(); //mStage.broadcastEvent(keyEvent); if (mBroadcastKeyboardEvents) mStage.broadcastEvent(keyEvent); else mStage.dispatchEvent(keyEvent); if (keyEvent.isDefaultPrevented()) event.preventDefault(); } private function onResize( event:Event ):void { var stageWidth:int = event.target.stageWidth; var stageHeight:int = event.target.stageHeight; if (contextValid) dispatchResizeEvent(); else addEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); function dispatchResizeEvent():void { // on Android, the context is not valid while we're resizing. To avoid problems // with user code, we delay the event dispatching until it becomes valid again. makeCurrent(); removeEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); mStage.dispatchEvent(new ResizeEvent(Event.RESIZE, stageWidth, stageHeight)); } } private function onMouseLeave( event:Event ):void { mTouchProcessor.enqueueMouseLeftStage(); } private function onTouch( event:Event ):void { if (!mStarted) return; var globalX:Number; var globalY:Number; var touchID:int; var phase:String; var pressure:Number = 1.0; var width:Number = 1.0; var height:Number = 1.0; // figure out general touch properties if (event is MouseEvent) { var mouseEvent:MouseEvent = event as MouseEvent; globalX = mouseEvent.stageX; globalY = mouseEvent.stageY; touchID = 0; // MouseEvent.buttonDown returns true for both left and right button (AIR supports // the right mouse button). We only want to react on the left button for now, // so we have to save the state for the left button manually. if (event.type == MouseEvent.MOUSE_DOWN) mLeftMouseDown = true; else if (event.type == MouseEvent.MOUSE_UP) mLeftMouseDown = false; } else { var touchEvent:TouchEvent = event as TouchEvent; // On a system that supports both mouse and touch input, the primary touch point // is dispatched as mouse event as well. Since we don't want to listen to that // event twice, we ignore the primary touch in that case. if (Mouse.supportsCursor && touchEvent.isPrimaryTouchPoint) return; else { globalX = touchEvent.stageX; globalY = touchEvent.stageY; touchID = touchEvent.touchPointID; pressure = touchEvent.pressure; width = touchEvent.sizeX; height = touchEvent.sizeY; } } // figure out touch phase switch (event.type) { case TouchEvent.TOUCH_BEGIN: phase = TouchPhase.BEGAN; break; case TouchEvent.TOUCH_MOVE: phase = TouchPhase.MOVED; break; case TouchEvent.TOUCH_END: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_DOWN: phase = TouchPhase.BEGAN; break; case MouseEvent.MOUSE_UP: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_MOVE: phase = (mLeftMouseDown ? TouchPhase.MOVED : TouchPhase.HOVER); break; } // move position into viewport bounds globalX = mStage.stageWidth * (globalX - mViewPort.x) / mViewPort.width; globalY = mStage.stageHeight * (globalY - mViewPort.y) / mViewPort.height; // enqueue touch in touch processor mTouchProcessor.enqueue(touchID, phase, globalX, globalY, pressure, width, height); // allow objects that depend on mouse-over state to be updated immediately if (event.type == MouseEvent.MOUSE_UP && Mouse.supportsCursor) mTouchProcessor.enqueue(touchID, TouchPhase.HOVER, globalX, globalY); } private function get touchEventTypes():Array { var types:Array = []; if (multitouchEnabled) types.push(TouchEvent.TOUCH_BEGIN, TouchEvent.TOUCH_MOVE, TouchEvent.TOUCH_END); if (!multitouchEnabled || Mouse.supportsCursor) types.push(MouseEvent.MOUSE_DOWN, MouseEvent.MOUSE_MOVE, MouseEvent.MOUSE_UP); return types; } // program management /** Registers a compiled shader-program under a certain name. * If the name was already used, the previous program is overwritten. */ public function registerProgram( name:String, vertexShader:ByteArray, fragmentShader:ByteArray ):Program3D { deleteProgram(name); var program:Program3D = mContext.createProgram(); program.upload(vertexShader, fragmentShader); programs[name] = program; return program; } /** Compiles a shader-program and registers it under a certain name. * If the name was already used, the previous program is overwritten. */ public function registerProgramFromSource( name:String, vertexShader:String, fragmentShader:String ):Program3D { deleteProgram(name); var program:Program3D = RenderSupport.assembleAgal(vertexShader, fragmentShader); programs[name] = program; return program; } /** Deletes the vertex- and fragment-programs of a certain name. */ public function deleteProgram( name:String ):void { var program:Program3D = getProgram(name); if (program) { program.dispose(); delete programs[name]; } } /** Returns the vertex- and fragment-programs registered under a certain name. */ public function getProgram( name:String ):Program3D { return programs[name] as Program3D; } /** Indicates if a set of vertex- and fragment-programs is registered under a certain name. */ public function hasProgram( name:String ):Boolean { return name in programs; } private function get programs():Dictionary { return contextData[PROGRAM_DATA_NAME]; } // properties /** Indicates if this Starling instance is started. */ public function get isStarted():Boolean { return mStarted; } /** The default juggler of this instance. Will be advanced once per frame. */ public function get juggler():Juggler { return mJuggler; } /** The render context of this instance. */ public function get context():Context3D { return mContext; } /** A dictionary that can be used to save custom data related to the current context. * If you need to share data that is bound to a specific stage3D instance * (e.g. textures), use this dictionary instead of creating a static class variable. * The Dictionary is actually bound to the stage3D instance, thus it survives a * context loss. */ public function get contextData():Dictionary { return sContextData[mStage3D] as Dictionary; } /** Returns the current width of the back buffer. In most cases, this value is in pixels; * however, if the app is running on an HiDPI display with an activated * 'supportHighResolutions' setting, you have to multiply with 'backBufferPixelsPerPoint' * for the actual pixel count. */ public function get backBufferWidth():int { return mClippedViewPort.width; } /** Returns the current height of the back buffer. In most cases, this value is in pixels; * however, if the app is running on an HiDPI display with an activated * 'supportHighResolutions' setting, you have to multiply with 'backBufferPixelsPerPoint' * for the actual pixel count. */ public function get backBufferHeight():int { return mClippedViewPort.height; } /** The number of pixel per point returned by the 'backBufferWidth/Height' properties. * Except for desktop HiDPI displays with an activated 'supportHighResolutions' setting, * this will always return '1'. */ public function get backBufferPixelsPerPoint():int { return mNativeStageContentScaleFactor; } /** Indicates if multitouch simulation with ""Shift"" and ""Ctrl""/""Cmd""-keys is enabled. * @default false */ public function get simulateMultitouch():Boolean { return mSimulateMultitouch; } public function set simulateMultitouch( value:Boolean ):void { mSimulateMultitouch = value; if (mContext) mTouchProcessor.simulateMultitouch = value; } /** Indicates if Stage3D render methods will report errors. Activate only when needed, * as this has a negative impact on performance. @default false */ // public function get enableErrorChecking():Boolean // { // return mEnableErrorChecking; // } // // public function set enableErrorChecking( value:Boolean ):void // { //// if (value) throw new AssukarError(""set \\""enableErrorChecking\\"" to false!""); // mEnableErrorChecking = value; // if (mContext) mContext.enableErrorChecking = value; // } /** The antialiasing level. 0 - no antialasing, 16 - maximum antialiasing. @default 0 */ public function get antiAliasing():int { return mAntiAliasing; } public function set antiAliasing( value:int ):void { if (mAntiAliasing != value) { mAntiAliasing = value; if (contextValid) updateViewPort(true); } } /** The viewport into which Starling contents will be rendered. */ public function get viewPort():Rectangle { return mViewPort; } public function set viewPort( value:Rectangle ):void { mViewPort = value.clone(); } /** The ratio between viewPort width and stage width. Useful for choosing a different * set of textures depending on the display resolution. */ public function get contentScaleFactor():Number { return (mViewPort.width * mNativeStageContentScaleFactor) / mStage.stageWidth; } /** A Flash Sprite placed directly on top of the Starling content. Use it to display native * Flash components. */ public function get nativeOverlay():Sprite { return mNativeOverlay; } /** Indicates if a small statistics box (with FPS, memory usage and draw count) is * displayed. * *

Beware that the memory usage should be taken with a grain of salt. The value is * determined via System.totalMemory and does not take texture memory * into account. It is recommended to use Adobe Scout for reliable and comprehensive * memory analysis.

*/ public function get showStats():Boolean { return mStatsDisplay && mStatsDisplay.parent; } public function set showStats( value:Boolean ):void { if (value == showStats) return; if (value) { if (mStatsDisplay) mStage.addChild(mStatsDisplay); else showStatsAt(); } else mStatsDisplay.removeFromParent(); } /** Displays the statistics box at a certain position. */ public function showStatsAt( hAlign:String = ""left"", vAlign:String = ""top"", scale:Number = 1 ):void { if (mContext == null) { // Starling is not yet ready - we postpone this until it's initialized. addEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } else { if (mStatsDisplay == null) { mStatsDisplay = new StatsDisplay(); mStatsDisplay.touchable = false; mStage.addChild(mStatsDisplay); } var stageWidth:int = mStage.stageWidth; var stageHeight:int = mStage.stageHeight; mStatsDisplay.scaleX = mStatsDisplay.scaleY = scale; if (hAlign == HAlign.LEFT) mStatsDisplay.x = 0; else if (hAlign == HAlign.RIGHT) mStatsDisplay.x = stageWidth - mStatsDisplay.width; else mStatsDisplay.x = int((stageWidth - mStatsDisplay.width) / 2); if (vAlign == VAlign.TOP) mStatsDisplay.y = 0; else if (vAlign == VAlign.BOTTOM) mStatsDisplay.y = stageHeight - mStatsDisplay.height; else mStatsDisplay.y = int((stageHeight - mStatsDisplay.height) / 2); } function onRootCreated():void { showStatsAt(hAlign, vAlign, scale); removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } } /** The Starling stage object, which is the root of the display tree that is rendered. */ public function get stage():Stage { return mStage; } /** The Flash Stage3D object Starling renders into. */ public function get stage3D():Stage3D { return mStage3D; } /** The Flash (2D) stage object Starling renders beneath. */ public function get nativeStage():flash.display.Stage { return mNativeStage; } /** The instance of the root class provided in the constructor. Available as soon as * the event 'ROOT_CREATED' has been dispatched. */ public function get root():DisplayObject { return mRoot; } /** The class that will be instantiated by Starling as the 'root' display object. * Must be a subclass of 'starling.display.DisplayObject'. * *

If you passed null as first parameter to the Starling constructor, * you can use this property to set the root class at a later time. As soon as the class * is instantiated, Starling will dispatch a ROOT_CREATED event.

* *

Beware: you cannot change the root class once the root object has been * instantiated.

*/ public function get rootClass():Class { return mRootClass; } public function set rootClass( value:Class ):void { if (mRootClass != null && mRoot != null) throw new Error(""Root class may not change after root has been instantiated""); else if (mRootClass == null) { mRootClass = value; if (mContext) initializeRoot(); } } /** Indicates if the Context3D render calls are managed externally to Starling, * to allow other frameworks to share the Stage3D instance. @default false */ // hidden to avoid behavior change dependent on share context // public function get shareContext():Boolean // { // return mShareContext; // } public function set shareContext( value:Boolean ):void { mShareContext = value; if (LOG_SHARE_CONTEXT) Utils.log(""STARLING:SHARECONTEXT shareContext="" + mShareContext); } /** The Context3D profile used for rendering. Beware that if you are using a shared * context in AIR 3.9 / Flash Player 11 or below, this is simply what you passed to * the Starling constructor. */ public function get profile():String { return mProfile; } /** Indicates that if the device supports HiDPI screens Starling will attempt to allocate * a larger back buffer than indicated via the viewPort size. Note that this is used * on Desktop only; mobile AIR apps still use the ""requestedDisplayResolution"" parameter * the application descriptor XML. @default false */ public function get supportHighResolutions():Boolean { return mSupportHighResolutions; } public function set supportHighResolutions( value:Boolean ):void { if (mSupportHighResolutions != value) { mSupportHighResolutions = value; if (contextValid) updateViewPort(true); } } /** Indicates if keyboard events are broadcast to all display objects, or dispatched * to the stage only. In some situations, it makes sense to deactivate this setting * for performance reasons. @default true */ public function get broadcastKeyboardEvents():Boolean { return mBroadcastKeyboardEvents; } public function set broadcastKeyboardEvents( value:Boolean ):void { mBroadcastKeyboardEvents = value; } /** The TouchProcessor is passed all mouse and touch input and is responsible for * dispatching TouchEvents to the Starling display tree. If you want to handle these * types of input manually, pass your own custom subclass to this property. */ public function get touchProcessor():TouchProcessor { return mTouchProcessor; } public function set touchProcessor( value:TouchProcessor ):void { if (value != mTouchProcessor) { mTouchProcessor.dispose(); mTouchProcessor = value; } } // obj-tion private var driverInfo1:String; /** Indicates if the Context3D object is currently valid (i.e. it hasn't been lost or * disposed). */ public function get contextValid():Boolean { if (mContext) { driverInfo1 = mContext.driverInfo; return driverInfo1 != null && driverInfo1 != """" && driverInfo1 != ""Disposed""; } else return false; } // static properties /** The currently active Starling instance. */ public static function get current():Starling { return sCurrent; } /** All Starling instances.

CAUTION: not a copy, but the actual object! Do not modify!

*/ public static function get all():Vector. { return sAll; } /** The render context of the currently active Starling instance. */ public static function get context():Context3D { return sCurrent ? sCurrent.context : null; } /** The default juggler of the currently active Starling instance. */ public static function get juggler():Juggler { return sCurrent ? sCurrent.juggler : null; } /** The contentScaleFactor of the currently active Starling instance. */ public static function get contentScaleFactor():Number { return sCurrent ? sCurrent.contentScaleFactor : 1.0; } static private var starlingScaleFactorr:Number = 0; public static function get starlingScaleFactor():Number { if (!starlingScaleFactorr) starlingScaleFactorr = Number(Starling.contentScaleFactor.toFixed(2)); return starlingScaleFactorr; } /** Indicates if multitouch input should be supported. */ public static function get multitouchEnabled():Boolean { return Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; } public static function set multitouchEnabled( value:Boolean ):void { if (sCurrent) throw new IllegalOperationError(""'multitouchEnabled' must be set before Starling instance is created""); else Multitouch.inputMode = value ? MultitouchInputMode.TOUCH_POINT : MultitouchInputMode.NONE; } /** Indicates if Starling should automatically recover from a lost device context. * On some systems, an upcoming screensaver or entering sleep mode may * invalidate the render context. This setting indicates if Starling should recover from * such incidents. * *

Beware: if used carelessly, this property may have a huge impact on memory * consumption. That's because, by default, it will make Starling keep a copy of each * texture in memory.

* *

However, this downside can be avoided by using the ""AssetManager"" to load textures. * The AssetManager is smart enough to restore them directly from their sources. You can * also do this by setting up ""root.onRestore"" on your manually loaded textures.

* *

A context loss can happen on almost every platform. It's very common on Windows * and Android, but rare on OS X and iOS (e.g. it may occur when opening up the camera * roll). It's recommended to always enable this property, while using the AssetManager * for texture loading.

* * @default false * @see starling.utils.AssetManager */ public static function get handleLostContext():Boolean { return sHandleLostContext; } public static function set handleLostContext( value:Boolean ):void { if (sCurrent) throw new IllegalOperationError(""'handleLostContext' must be set before Starling instance is created""); else sHandleLostContext = value; } } } ",12412,False,2323.0039709617263,median "class ZSAPLINK_VIEWS definition public inheriting from ZSAPLINK final create public . public section. methods CHECKEXISTS redefinition . methods CREATEIXMLDOCFROMOBJECT redefinition . methods CREATEOBJECTFROMIXMLDOC redefinition . protected section. methods DELETEOBJECT redefinition . methods GETOBJECTTYPE redefinition . private section. endclass. ""ZSAPLINK_VIEWS definition *----------------------------------------------------------------------* * class ZSAPLINK_VIEWS implementation. *----------------------------------------------------------------------* * *----------------------------------------------------------------------* class ZSAPLINK_VIEWS implementation. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ METHOD CHECKEXISTS. * Plugin created by: * Thomas Jung * thomas.jung1@gmail.com DATA: l_name TYPE ddobjname, dd25v_wa TYPE dd25v. l_name = objname. CALL FUNCTION 'DDIF_VIEW_GET' EXPORTING name = l_name IMPORTING dd25v_wa = dd25v_wa EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc = 0 AND dd25v_wa-viewname IS NOT INITIAL. exists = 'X'. ENDIF. ENDMETHOD. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ METHOD CREATEIXMLDOCFROMOBJECT. * Plugin created by: * Thomas Jung * thomas.jung1@gmail.com DATA: gotstate TYPE ddgotstate, dd25v_wa TYPE dd25v, dd09l_wa TYPE dd09v, dd26v_tab TYPE STANDARD TABLE OF dd26v, dd26v_wa LIKE LINE OF dd26v_tab, dd27p_tab TYPE STANDARD TABLE OF dd27p, dd27p_wa LIKE LINE OF dd27p_tab, dd28j_tab TYPE STANDARD TABLE OF dd28j, dd28j_wa LIKE LINE OF dd28j_tab, dd28v_tab TYPE STANDARD TABLE OF dd28v, dd28v_wa LIKE LINE OF dd28v_tab. *xml nodes DATA rootnode TYPE REF TO if_ixml_element. DATA dd09l_node TYPE REF TO if_ixml_element. DATA dd26v_node TYPE REF TO if_ixml_element. DATA dd27p_node TYPE REF TO if_ixml_element. DATA dd28j_node TYPE REF TO if_ixml_element. DATA dd28v_node TYPE REF TO if_ixml_element. DATA rc TYPE sysubrc. DATA _viewname TYPE ddobjname. _viewname = objname. CALL FUNCTION 'DDIF_VIEW_GET' EXPORTING name = _viewname langu = sy-langu IMPORTING gotstate = gotstate dd25v_wa = dd25v_wa dd09l_wa = dd09l_wa TABLES dd26v_tab = dd26v_tab dd27p_tab = dd27p_tab dd28j_tab = dd28j_tab dd28v_tab = dd28v_tab EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0 OR dd25v_wa-viewname IS INITIAL. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>not_found. ENDIF. * Create parent node DATA _objtype TYPE string. _objtype = getobjecttype( ). rootnode = xmldoc->create_element( _objtype ). setattributesfromstructure( node = rootnode structure = dd25v_wa ). dd09l_node = xmldoc->create_element( 'dd09l' ). setattributesfromstructure( node = dd09l_node structure = dd09l_wa ). rc = rootnode->append_child( dd09l_node ). LOOP AT dd26v_tab INTO dd26v_wa. dd26v_node = xmldoc->create_element( 'dd26v' ). setattributesfromstructure( node = dd26v_node structure = dd26v_wa ). rc = rootnode->append_child( dd26v_node ). ENDLOOP. LOOP AT dd27p_tab INTO dd27p_wa. dd27p_node = xmldoc->create_element( 'dd27p' ). setattributesfromstructure( node = dd27p_node structure = dd27p_wa ). rc = rootnode->append_child( dd27p_node ). ENDLOOP. LOOP AT dd28j_tab INTO dd28j_wa. dd28j_node = xmldoc->create_element( 'dd28j' ). setattributesfromstructure( node = dd28j_node structure = dd28j_wa ). rc = rootnode->append_child( dd28j_node ). ENDLOOP. LOOP AT dd28v_tab INTO dd28v_wa. dd28v_node = xmldoc->create_element( 'dd28v' ). setattributesfromstructure( node = dd28v_node structure = dd28v_wa ). rc = rootnode->append_child( dd28v_node ). ENDLOOP. *\\--------------------------------------------------------------------/ rc = xmldoc->append_child( rootnode ). ixmldocument = xmldoc. ENDMETHOD. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ METHOD CREATEOBJECTFROMIXMLDOC. * Plugin created by: * Thomas Jung * thomas.jung1@gmail.com DATA: gotstate TYPE ddgotstate, dd25v_wa type dd25v, dd09l_wa type dd09v, dd26v_tab type standard table of dd26v, dd26v_wa like line of dd26v_tab, dd27p_tab type standard table of dd27p, dd27p_wa like line of dd27p_tab, dd28j_tab type standard table of dd28j, dd28j_wa like line of dd28j_tab, dd28v_tab type standard table of dd28v, dd28v_wa like line of dd28v_tab. *xml nodes DATA rootnode TYPE REF TO if_ixml_element. data dd09l_node type ref to if_ixml_element. data dd26v_node type ref to if_ixml_element. data dd27p_node type ref to if_ixml_element. data dd28j_node type ref to if_ixml_element. data dd28v_node type ref to if_ixml_element. DATA node TYPE REF TO if_ixml_element. DATA filter TYPE REF TO if_ixml_node_filter. DATA iterator TYPE REF TO if_ixml_node_iterator. DATA rc TYPE sysubrc. DATA _tablname TYPE ddobjname. DATA _devclass TYPE devclass. DATA checkexists TYPE flag. DATA _objtype TYPE string. _devclass = devclass. _objtype = getobjecttype( ). xmldoc = ixmldocument. rootnode = xmldoc->find_from_name( _objtype ). CALL METHOD getstructurefromattributes EXPORTING node = rootnode CHANGING structure = dd25v_wa. objname = dd25v_wa-viewname. checkexists = checkexists( ). IF checkexists IS NOT INITIAL. IF overwrite IS INITIAL. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>existing. ELSE. * delete object for new install deleteobject( ). ENDIF. ENDIF. dd09l_node = xmldoc->find_from_name( 'dd09l' ). CALL METHOD getstructurefromattributes EXPORTING node = dd09l_node CHANGING structure = dd09l_wa. * retrieve Tabl details FREE: filter, iterator, node. filter = xmldoc->create_filter_name( 'dd26v' ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR dd26v_node. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = dd26v_wa. APPEND dd26v_wa TO dd26v_tab. node ?= iterator->get_next( ). ENDWHILE. FREE: filter, iterator, node. filter = xmldoc->create_filter_name( 'dd27p' ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR dd27p_node. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = dd27p_wa. APPEND dd27p_wa TO dd27p_tab. node ?= iterator->get_next( ). ENDWHILE. FREE: filter, iterator, node. filter = xmldoc->create_filter_name( 'dd28j' ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR dd28j_node. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = dd28j_wa. APPEND dd28j_wa TO dd28j_tab. node ?= iterator->get_next( ). ENDWHILE. FREE: filter, iterator, node. filter = xmldoc->create_filter_name( 'dd28v' ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR dd28v_node. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = dd28v_wa. APPEND dd28v_wa TO dd28v_tab. node ?= iterator->get_next( ). ENDWHILE. DATA : l_pgmid TYPE tadir-pgmid, l_object TYPE tadir-object, l_obj_name TYPE tadir-obj_name, l_dd_objname TYPE ddobjname, l_srcsystem TYPE tadir-srcsystem, l_author TYPE tadir-author, l_devclass TYPE tadir-devclass, l_masterlang TYPE tadir-masterlang. l_pgmid = 'R3TR'. l_object = _objtype. l_obj_name = objname. l_dd_objname = objname. l_srcsystem = sy-sysid. l_author = sy-uname. l_devclass = _devclass. l_masterlang = sy-langu. DATA: itadir TYPE tadir. itadir-pgmid = l_pgmid. itadir-object = l_object. itadir-obj_name = l_obj_name. itadir-srcsystem = l_srcsystem. itadir-author = l_author. itadir-devclass = l_devclass. itadir-masterlang = l_masterlang. MODIFY tadir FROM itadir. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_test_modus = ' ' wi_delete_tadir_entry = 'X' wi_tadir_pgmid = l_pgmid wi_tadir_object = l_object wi_tadir_obj_name = l_obj_name wi_tadir_srcsystem = l_srcsystem wi_tadir_author = l_author wi_tadir_devclass = l_devclass wi_tadir_masterlang = l_masterlang iv_set_edtflag = '' EXCEPTIONS tadir_entry_not_existing = 1 tadir_entry_ill_type = 2 no_systemname = 3 no_systemtype = 4 original_system_conflict = 5 object_reserved_for_devclass = 6 object_exists_global = 7 object_exists_local = 8 object_is_distributed = 9 obj_specification_not_unique = 10 no_authorization_to_delete = 11 devclass_not_existing = 12 simultanious_set_remove_repair = 13 order_missing = 14 no_modification_of_head_syst = 15 pgmid_object_not_allowed = 16 masterlanguage_not_specified = 17 devclass_not_specified = 18 specify_owner_unique = 19 loc_priv_objs_no_repair = 20 gtadir_not_reached = 21 object_locked_for_order = 22 change_of_class_not_allowed = 23 no_change_from_sap_to_tmp = 24 OTHERS = 25. IF sy-subrc NE 0. CASE sy-subrc. WHEN 1 OR 9 OR 7 OR 8. ""OK! - Doesn't exist yet WHEN 11 OR 23 OR 24. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>not_authorized. WHEN 22. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>locked. WHEN OTHERS. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>system_error. ENDCASE. ENDIF. CALL FUNCTION 'DDIF_VIEW_PUT' EXPORTING name = l_dd_objname dd25v_wa = dd25v_wa dd09l_wa = dd09l_wa TABLES dd26v_tab = dd26v_tab dd27p_tab = dd27p_tab dd28j_tab = dd28j_tab dd28v_tab = dd28v_tab EXCEPTIONS view_not_found = 1 name_inconsistent = 2 view_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>system_error. ENDIF. DATA: trobjtype TYPE trobjtype, trobj_name TYPE trobj_name. trobjtype = l_object. trobj_name = l_obj_name. CALL FUNCTION 'RS_INSERT_INTO_WORKING_AREA' EXPORTING object = trobjtype obj_name = trobj_name EXCEPTIONS wrong_object_name = 1. name = objName. ENDMETHOD. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ method DELETEOBJECT. * Plugin created by: * Thomas Jung * thomas.jung1@gmail.com endmethod. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| SAPlink is free software; you can redistribute it and/or modify | *| it under the terms of the GNU General Public License as published | *| by the Free Software Foundation; either version 2 of the License, | *| or (at your option) any later version. | *| | *| SAPlink is distributed in the hope that it will be useful, | *| but WITHOUT ANY WARRANTY; without even the implied warranty of | *| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | *| GNU General Public License for more details. | *| | *| You should have received a copy of the GNU General Public License | *| along with SAPlink; if not, write to the | *| Free Software Foundation, Inc., | *| 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *\\---------------------------------------------------------------------/ method GETOBJECTTYPE. * Plugin created by: * Thomas Jung * thomas.jung1@gmail.com objecttype = 'VIEW'. ""Views endmethod. endclass. ""ZSAPLINK_VIEWS implementation",4801,False,1172.4888365230008,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { COMPILE::JS public class XMLList { import org.apache.royale.debugging.throwError; import org.apache.royale.language.toAttributeName; /** * regex to match the xml declaration */ private static const xmlDecl:RegExp = /^\\s*<\\?xml[^?]*\\?>/im; /** * mimics the top-level XMLList function (supports 'this' correctly) * * @royalesuppressexport * @royaleignorecoercion XMLList */ public static function conversion(val:* = null):XMLList{ if (val && val.constructor == XMLList) return val as XMLList; else return new XMLList(val); } public function XMLList(expression:Object = null) { addIndex(0); if(expression != null) parseExpression(expression); } /** * @royaleignorecoercion String */ private function parseExpression(expression:Object):void { if(expression is XMLList) { targetObject = expression.targetObject; targetProperty = expression.targetProperty; var len:int = expression.length(); for(var i:int=0;i"") == 0 && expstr.indexOf("""") == expstr.length - 3) expression = expstr.substr(2, expstr.length - 5); } try { var item:XML = new XML(expression); if (item.nodeKind() == 'text' && item.getValue() == '') return; this[0] = item; } catch (e:Error) { if (typeof(expression) === ""string"") { var decl:String = xmlDecl.exec(expression); if (decl) expression = expression.replace(decl,''); // try adding a wrapping node and then grab the children expression = """" + expression + """"; try { var xml:XML = new XML(expression); var list:XMLList = xml.children(); var m:int = list.length(); for (var j:int = 0; j < m; j++) { this[j] = list[j]; } } catch (e2:Error) { throw e; // throw original error } } else throw e; } } } /** * [[ResolveValue]] from the e4x spec * @royaleignorecoercion QName * @royaleignorecoercion XMLList */ private function resolveValue():*{ if (_xmlArray.length > 0) return this; if ((_targetObject == null || _targetProperty == null) || (_targetProperty is QName && (QName(_targetProperty).isAttribute || QName(_targetProperty).localName == '*'))) return null; //2,a var base:* = (!_targetObject || _targetObject is XML) ? _targetObject : (_targetObject as XMLList).resolveValue(); if (base==null) return null; var target:XMLList = base.child(_targetProperty); if (target.length() == 0) { if (base is XMLList && (base.length() > 1)) return null; base.setChild(_targetProperty, ''); target = base.child(_targetProperty); } return target; } private var _xmlArray:Array = []; /* 9.2.1.2 [[Put]] (P, V) Overview The XMLList type overrides the internal [[Put]] method defined by the Object type. The XMLList [[Put]] method is used to modify or replace an XML object within the XMLList and the context of its parent. In addition, when the XMLList contains a single property with an XML object, the [[Put]] method is used to modify, replace, and insert properties or XML attributes of that value by name. The input argument P identifies which portion of the XMLList and associated XML objects will be affected and may be a numeric property name, an unqualified name for an XML attribute (distinguished from XML valued property names by a leading “@” symbol) or set of XML elements, a QName for a set of XML elements, an AttributeName for a set of XML attributes or the properties wildcard “*”. When the input argument P is an unqualified XML element name, it identifies XML elements in the default namespace. When the input argument P is an unqualified XML attribute name, it identifies XML attributes in no namespace. The input argument V may be a value of type XML, XMLList or any value that can be converted to a String with ToString(). NOTE Unlike the internal Object [[Put]] method, the internal XMLList [[Put]] method is never used for modifying the set of methods associated with XMLList objects. Semantics When the [[Put]] method of an XMLList object x is called with property name P and value V, the following steps are taken: 1. Let i = ToUint32(P) 2. If ToString(i) == P a. If x.[[TargetObject]] is not null i. Let r be the result of calling the [[ResolveValue]] method of x.[[TargetObject]] ii. If r == null, return b. Else let r = null c. If i is greater than or equal to x.[[Length]] i. If Type(r) is XMLList 1. If r.[[Length]] is not equal to 1, return 2. Else let r = r[0] ii. If r.[[Class]] is not equal to ""element"", return iii. Create a new XML object y with y.[[Parent]] = r, y.[[Name]] = x.[[TargetProperty]], y.[[Attributes]] = {}, y.[[Length]] = 0 iv. If Type(x.[[TargetProperty]]) is AttributeName 1. Let attributeExists be the result of calling the [[Get]] method of r with argument y.[[Name]] 2. If (attributeExists.[[Length]] > 0), return 3. Let y.[[Class]] = ""attribute"" v. Else if x.[[TargetProperty]] == null or x.[[TargetProperty]].localName == ""*"" 1. Let y.[[Name]] = null 2. Let y.[[Class]] = ""text"" vi. Else let y.[[Class]] = ""element"" vii. Let i = x.[[Length]] viii. If (y.[[Class]] is not equal to ""attribute"") 1. If r is not null a. If (i > 0) i. Let j = 0 ii. While (j < r.[[Length]]-1) and (r[j] is not the same object as x[i-1]) 1. Let j = j + 1 b. Else i. Let j = r.[[Length]]-1 c. Call the [[Insert]] method of r with arguments ToString(j+1) and y 2. If Type(V) is XML, let y.[[Name]] = V.[[Name]] 3. Else if Type(V) is XMLList, let y.[[Name]] = V.[[TargetProperty]] ix. Call the [[Append]] method of x with argument y d. If (Type(V) ∉ {XML, XMLList}) or (V.[[Class]] ∈ {""text"", ""attribute""}), let V = ToString(V) e. If x[i].[[Class]] == ""attribute"" i. Let z = ToAttributeName(x[i].[[Name]]) ii. Call the [[Put]] method of x[i].[[Parent]] with arguments z and V iii. Let attr be the result of calling [[Get]] on x[i].[[Parent]] with argument z iv. Let x[i] = attr[0] f. Else if Type(V) is XMLList i. Create a shallow copy c of V ii. Let parent = x[i].[[Parent]] iii. If parent is not null 1. Let q be the property of parent, such that parent[q] is the same object as x[i] 2. Call the [[Replace]] method of parent with arguments q and c 3. For j = 0 to c.[[Length]]-1 a. Let c[j] = parent[ToUint32(q)+j] iv. If c.[[Length]] == 0 1. For j = i + 1 to x.[[Length]] – 1, rename property j of x to ToString(j-1) v. Else 1. For j = x.[[Length]]-1 downto i + 1, rename property j of x to ToString(j + c.[[Length]] - 1) vi. For j = 0 to c.[[Length]]-1, let x[i + j] = c[j] vii. Let x.[[Length]] = x.[[Length]] + c.[[Length]] - 1 g. Else if (Type(V) is XML) or (x[i].[[Class]] ∈ {""text"", ""comment"", ""processing-instruction""}) i. Let parent = x[i].[[Parent]] ii. If parent is not null 1. Let q be the property of parent, such that parent[q] is the same object as x[i] 2. Call the [[Replace]] method of parent with arguments q and V 3. Let V = parent[q] iii. If Type(V) is String 1. Create a new XML object t with t.[[Class]] = ""text"", t.[[Parent]] = x and t.[[Value]] = V 2. Let x[i] = t iv. Else 1. Let x[i] = V h. Else i. Call the [[Put]] method of x[i] with arguments ""*"" and V 3. Else if x.[[Length]] is less than or equal to 1 a. If x.[[Length]] == 0 i. Let r be the result of calling the [[ResolveValue]] method of x ii. If (r == null) or (r.[[Length]] is not equal to 1), return iii. Call the [[Append]] method of x with argument r b. Call the [[Put]] method of x[0] with arguments P and V 4. Return */ private function addIndex(idx:int):void { var idxStr:String = """" + idx; Object.defineProperty(this,idxStr, { ""get"": function():* { return _xmlArray[idx]; }, ""set"": function(newValue:*):void { if(idx >= _xmlArray.length) append(newValue); else replaceChildAt(idx,newValue); }, enumerable: true, configurable: true } ); } /* [[Append]] from the e4x spec When the [[Append]] method of an XMLList object x is called with value V, the following steps are taken: 1. Let i = x.[[Length]] 2. Let n = 1 3. If Type(V) is XMLList, a. Let x.[[TargetObject]] = V.[[TargetObject]] b. Let x.[[TargetProperty]] = V.[[TargetProperty]] c. Let n = V.[[Length]] d. If n == 0, Return e. For j = 0 to V.[[Length]]-1, let x[i + j] = V[j] f. 4. Let x.[[Length]] = x.[[Length]] + n 5. Return */ /** * * @royaleignorecoercion XMLList * @royaleignorecoercion XML */ private function Append(content:Object):void{ var i:uint = _xmlArray.length; var n:uint = 1; if (content is XMLList) { var l:XMLList = content as XMLList; _targetObject = l._targetObject;//3.a _targetProperty = l._targetProperty;//3.b n = l.length();//3.c if (n == 0) return;//3.d for (var j:uint =0; j < n; j++){ //[[Put]] _xmlArray[i+j] = l._xmlArray[j]; //3.e addIndex(i+j); //setChild( i+j, l._xmlArray[j]); } } else { if (content is XML) { //[[Put]] //setChild( i, content as XML); //3.e _xmlArray[i] = content; //3.e addIndex(i); } } } public function append(child:XML):void { _xmlArray[_xmlArray.length] = child; addIndex(_xmlArray.length); do//while false { if(!_targetObject) break; if(!_targetProperty) { _targetObject.appendChild(child); break; } var objToAppend:XMLList = _targetObject.child(_targetProperty); if(!objToAppend.length()) { _targetObject.appendChild(child); break; } _targetObject.insertChildAfter(objToAppend[objToAppend.length()-1],child); }while(false); } public function appendChild(child:*):XML { if(isSingle()) return _xmlArray[0].appendChild(child); return null; } /** * Calls the attribute() method of each XML object and returns an XMLList object of the results. * * @param attributeName * @return * */ public function attribute(attributeName:*):XMLList { if(isSingle()) return _xmlArray[0].attribute(attributeName); var retVal:XMLList = new XMLList(); var len:int = _xmlArray.length; for (var i:int=0;i= 0 && propNum < _xmlArray.length) { retVal.append(_xmlArray[propNum]); retVal.targetObject = _xmlArray[propNum]; } return retVal; } if(isEmpty()) { retVal.targetObject = this; } if(isSingle()) return _xmlArray[0].child(propertyName); var len:int = _xmlArray.length; for (var i:int=0;i= 0; i--) { if(_xmlArray[i] == child) { _xmlArray.splice(i,1); if(child.hasAncestor(_targetObject)) child.parent().removeChild(child); } } } } public function removeChildAt(idx:int):void { if(idx >= 0 && idx < _xmlArray.length) { var child:XML = _xmlArray[idx]; _xmlArray.splice(idx,1); if(child.hasAncestor(_targetObject)) child.parent().removeChild(child); } } private function replaceChildAt(idx:int,child:*):void { var i:int; var childToReplace:XML = _xmlArray[idx]; if(childToReplace && _targetObject) { _targetObject.replaceChildAt(childToReplace.childIndex(),child); } if(child is XML) { _xmlArray[idx] = child; } else if(child is XMLList) { var len:int = child.length(); for(i=0;i""; } else { xmlStr += _targetProperty + ""/>""; } ret = new XML(xmlStr); } return ret; } public function setAttribute(attr:*,value:String):String { /*if(isEmpty() && targetObject)//walk up the tree and create nodes. _xmlArray[0] = targetObject.setChild(_targetProperty,xmlFromProperty(targetObject)); var len:int = _xmlArray.length; for (var i:int=0;i= _xmlArray.length) { //2.c var xmlR:XML = r as XML; if (!r && r is XMLList) { //2.c.i if (!(r as XMLList).isSingle()) return null; //2.c.i.1 xmlR = r[0]; //2.c.i.2 } if (xmlR && xmlR.nodeKind() != 'element') return null; //2.c.ii var y:XML = xmlFromProperty(xmlR); idx = _xmlArray.length; if (y.nodeKind() != 'attribute') {//2.c.vii if (xmlR) { //2.c.viii.1 if (idx > 0) { //2.c.viii.1.a var j:uint = 0; while (j < xmlR.getChildrenArray().length-1 && xmlR.getChildrenArray()[j] !== _xmlArray[idx-1]) { j++; } } else { j = xmlR.getChildrenArray().length -1; //2.c.viii.1.b } xmlR.insertChildAfter(xmlR.getChildrenArray()[j], y); //2.c.viii.1.c } if (elements is XML) y.setName((elements as XML).name());//2.c.viii.2 else if (elements is XMLList) y.setName(new QName((elements as XMLList)._targetProperty)); //2.c.viii.3 } //append(y); Append(y); } if ( !(elements is XML || elements is XMLList) || (elements is XML && ((elements as XML).nodeKind() == 'text' || (elements as XML).nodeKind() == 'attribute'))) { //2.d elements = elements + ''; } if ((_xmlArray[idx] as XML).nodeKind() == 'attribute') { var z:QName = (_xmlArray[idx] as XML).name(); (_xmlArray[idx] as XML).parent().setAttribute(z, elements); var attr:XMLList = (_xmlArray[idx] as XML).parent().attribute(z); _xmlArray[idx] = attr[0]; addIndex(idx); } else if (elements is XMLList) { var c:XMLList = new XMLList(elements); // 2.f.i (shallow copy) var parent:XML = (_xmlArray[idx] as XML).parent(); if (parent) { //1. Let q be the property of parent, such that parent[q] is the same object as x[i] @todo verify what this actually means var q:int = parent.getChildrenArray().indexOf(_xmlArray[idx]); //2. Call the [[Replace]] method of parent with arguments q and c parent.replaceChildAt(q, c); for (j =0; j idx; j--) { _xmlArray[j+cl] = _xmlArray[j]; addIndex(j+cl); } for (j = 0; j< cl; j++) { _xmlArray[idx+j] = c[j]; addIndex(idx+j); } } } else if (elements is XML || (_xmlArray[idx] as XML).nodeKind() == 'text' || (_xmlArray[idx] as XML).nodeKind() == 'comment' || (_xmlArray[idx] as XML).nodeKind() == 'processing-instruction') { parent = (_xmlArray[idx] as XML).parent(); if (parent) { //1. Let q be the property of parent, such that parent[q] is the same object as x[i] @todo verify what this actually means q = parent.getChildrenArray().indexOf(_xmlArray[idx]); //2. Call the [[Replace]] method of parent with arguments q and c parent.replaceChildAt(q, elements); elements = parent.getChildrenArray()[q]; } if (typeof elements == 'string') { var t:XML = new XML(); t.setParent(this as XML); //this is not XML... but we can cheat t.setValue(elements+''); _xmlArray[idx] = t; } else { _xmlArray[idx] = elements; } addIndex(idx); } else { (_xmlArray[idx] as XML).setChild('*', elements); } } else { //3 if (_xmlArray.length <= 1) { //3.a if (isEmpty()) { r = resolveValue(); if (r == null || r.length() != 1) return null; Append(r) } (_xmlArray[0] as XML).setChild(elementName, elements); } else { //match AVM, this is not covered in spec which says nothing, avm does this: throw new TypeError('Error #1089: Assignment to lists with more than one item is not supported.') } } return elements; } public function setParent(parent:XML):void { if(isSingle()) _xmlArray[0].setParent(parent); } public function setChildren(value:Object):XML { if(isSingle()) return _xmlArray[0].setChildren(value); return null; } public function setLocalName(name:String):void { if(isSingle()) _xmlArray[0].setLocalName(name); } public function setName(name:String):void { if(isSingle()) _xmlArray[0].setName(name); } public function setNamespace(ns:Namespace):void { if(isSingle()) _xmlArray[0].setNamespace(ns); } /** * Calls the text() method of each XML object and returns an XMLList object that contains the results. * * @return * */ public function text():XMLList { var retVal:XMLList = new XMLList(); var len:int = _xmlArray.length; for (var i:int=0;i