+ All Categories
Home > Documents > Book Draft «Introduction to the programming language ... · The programming is done by plugging...

Book Draft «Introduction to the programming language ... · The programming is done by plugging...

Date post: 28-Jun-2020
Category:
Upload: others
View: 8 times
Download: 0 times
Share this document with a friend
62
© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright. 1 Book Draft «Introduction to the programming language Oxoscript»
Transcript
Page 1: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

1

Book Draft «Introduction to the programming language Oxoscript»

Page 2: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

2

First incomplete and uncorrected version. This document serves as a manual and introduction to programming with the new programming language Oxoscript based on the educational learning computer Oxocard. V 0.9_EN - 27.01.2020

OXON AG Waldeggstrasse 47 3097 Liebefeld Switzerland www.oxon.ch www.oxocard.ch

Page 3: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

3

Table of contents 1 Introduction ........................................................................................................................ 5

1.1 What is the Oxocard? ................................................................................................. 5 1.2 Programming with Blockly or Oxoscript? ................................................................. 7 1.3 Installing the Scripting Environment ......................................................................... 9

1.4 The Oxoscript development environment ................................................................ 10 1.5 Structure of a Script .................................................................................................. 12 1.6 Next Steps ................................................................................................................ 13

2 Reference: Language constructs ....................................................................................... 14 2.1 Program Sequence .................................................................................................... 14 2.2 Variable Declaration ................................................................................................ 14 2.3 Output of Data in the OUTPUT Window of the Browser ........................................ 19 2.4 Expressions and mathematical functions ................................................................. 20 2.5 Processing of lists ..................................................................................................... 21

2.6 Editing texts .............................................................................................................. 23 2.7 The For Loop ............................................................................................................ 25 2.8 The Repeat Loop ...................................................................................................... 27 2.9 Conditional Statements with if/then/else .................................................................. 28 2.10 The While Loop ....................................................................................................... 30 2.11 Bit Operations .......................................................................................................... 31 2.12 Break and Continue .................................................................................................. 33 2.13 Declaration of Functions .......................................................................................... 34 2.14 Sending data to the browser ..................................................................................... 37

3 Reference: Built-in functions of the Oxocard .................................................................. 39 3.1 Logic ......................................................................................................................... 39 3.2 Mathematical functions ............................................................................................ 39

3.3 Oxocard System Functions ....................................................................................... 39 3.4 Matrix Drawing Commands ..................................................................................... 41 3.5 Time Functions ......................................................................................................... 43 3.6 Accelerometer .......................................................................................................... 44 3.7 Sound Output ............................................................................................................ 45 3.8 Microphone .............................................................................................................. 47 3.9 Internet and Communication .................................................................................... 47 3.10 Permanent Memory .................................................................................................. 49 3.11 Hardware Communication ....................................................................................... 49

3.12 Console Output ......................................................................................................... 50

Page 4: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

4

4 Reference: Built-in Constants of the Oxocard ................................................................. 51

5 Reference: Colour systems ............................................................................................... 55 5.1 The RGB Color System ............................................................................................ 55 5.2 The Hue Colour System ........................................................................................... 56

6 Technical background information .................................................................................. 58 6.1 Distinction from Python ........................................................................................... 59 6.2 Purpose and area of application ............................................................................... 60

7 Change control ................................................................................................................. 62

Page 5: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

5

1 Introduction 1.1 What is the Oxocard? The Oxocard is a powerful educational learning computer with built-in sensors and WiFi communication. With the Oxocard, pupils, teenagers and of course interested adults can enter the fascinating world of programming and learn to grasp and understand today's common technology of the Internet and electronic world by means of exciting experiments. For this purpose, the Oxocard contains a finely tuned set of sensors and functionalities with which a large number of exciting aspects of computing can be illustrated. This learning computer is so simple in design that it can be used without any previous knowledge, but still powerful enough to cope with more demanding tasks. As a beginner programmer, you want to see quick results and of course you want to be surprised and inspired by all the fascinating things that are possible with a computer today. This is exactly what the Oxocard makes possible with the creative development environment Oxoscript.

LED40

LED48

LED1 LED2 LED3 LED4 LED5 LED6 LED7 LED8

LED9 LED10 LED11 LED12 LED13 LED14 LED15 LED16

LED17 LED18 LED19 LED20 LED21 LED22 LED23 LED24

LED25 LED26 LED27 LED28 LED29 LED30 LED31 LED32

LED33 LED34 LED35 LED36 LED37 LED38 LED39

LED41 LED42 LED43 LED44 LED45 LED46 LED47

LED49 LED50 LED51 LED52 LED53 LED54 LED55 LED56

LED57 LED58 LED59 LED60 LED61 LED62 LED63 LED64C6

OXOcardV23

Butt

on1

Butt

on2

Butt

on3

100

Power Supply

Reset

Butt

on6

Butt

on5

Butt

on4

VP

VN

GND

WS

SDATA

VDD

GND

SDA

VDD

VCC_LED

DO_LED

R21 R12

R11

R31

C23

R19

R13C5 C3R14

C10

R34 R33

C12

USB to VART

Q5 Q4

D10

D11

GND

UBUS

VDO CS

MISO SCK

MISO GND

R9R26VCC R5

C13C11

C16

R6 +-

R1

GND

Accelerometer

IC13

Micr

ocon

trol

ler

C78 C70 C62 C54 C46 C38 C30 C22

ACHTUNG, FERTIG, CODE!�� ��WAS MACHT DIE OXOCARD?

01 – MIKROFON

02 – AUDIO-AUSGANG

03 – CONTROLLER

04 – WIFI/BLUETOOTH

05 – BESCHLEUNIGUNGSSENSOR

06 – KNOPF/TASTE

07 – FARBIGE LED-LÄMPCHEN

08 – USB

Mit diesem elektronischen «Ohr» können akustische Signale verarbeitet werden.

�������������ϐ�Ú����������������������anschließen und so Töne und Geräusche erzeugen.

������������¡������ϐ���������������«Gehirn» der Oxocard. Zwei CPU-Kerne verarbeiten sämtliche Prozesse und steuern die Vorgänge.

Per WiFi kannst du Daten aus dem Internet holen und mit anderen Karten kommunizieren.

Per Bluetooth kannst du ebenfalls Daten an andere Geräte übermitteln, auch ohne externes Netz.

Bei Bewegung erfährt die Karte eine Beschleunigung, die mit diesem Sensor verarbeitet wird.

Mit den sechs Knöpfen kannst du deine Programme steuern und eine Aktion starten oder anhalten.

Mit den 64 LEDs kannst du farbige Bilder zeichnen, auch animierte.

Über die USB-Schnittstelle kannst du Daten austauschen und den Akku laden.

WAS KANN DIE OXOCARD?

07

08 02

05

03

04

01

06

������������������������ϐ����������������������Ǥ���������¡���������Ú�����������ǡ������������������������������ǡ�����������������������������ϐ�����Ǥ����������������ϐ���zeigt dir auf, was die Oxocard alles eingebaut hat und welche Zwecke die Teile erfüllen.

ELEKTRONIKMIKROFON

AUDIO - AUSGANG

CONTROLLER *

WIFI und BLE

BESCHLEUNIGUNGSSENSOR TEMPERATURSENSOR

TASTER

FARBIGE PIXEL

USB-BUCHSE

*DUAL-CORE TENSILICA-CHIP-DESIGN, 4 MB FLASH

Page 6: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

6

The Oxocard is based on a powerful MCU (Microcontroller Unit) from Espressif. On this ESP32 runs the programs developed by users. The chip also has two radio modules for WiFi and Bluetooth communication. It is not only the maker and education scene that has discovered this chip for itself. Many commercial products now also rely on it, for example consumer electronics devices (WiFi speakers, Internet radios), communication (WiFi router) or in the field of building or home automation (light and blind control, etc.). The Oxocard additionally has the following hardware elements: 64 LED Pixel Matrix This can be used to output graphics, animations and texts in

multiple colours. The LEDs are very bright and can also perform signalling, alarming or lighting tasks. Each of the 64 pixels can be controlled individually with the command setPixel(..). The color space comprises 255 red, green and blue shades each. This results in a variety of 16 million colours!

6 Buttons The buttons arranged below serve as input medium for controlling and regulating various tasks. You can use them to control games, set values or change modes. Of course you can also switch the Oxocard on and off with the buttons.

Accelerometer The so-called accelerometer measures the acceleration in three axes (horizontal: x, y and vertical: z). This allows movements to be detected, but also gravity. In this way it is possible to find out how the Oxocard is currently aligned. With a little mathematics, it is then also possible to make angle measurements or move a pixel back and forth on a matrix display by tilting the Oxocard.

Temperature sensor The accelerometer has an integrated temperature sensor. This is not very precise, and it is not calibrated. But you can determine the temperature with an accuracy of about 2 degrees, which is sufficient for most tasks.

Audio output On the MCU there is an 8bit digital-to-analog converter with which you can generate audio signals, among other things. The output signal can be analog via 3.5 mm jack plugs over conventional headphones or external speaker boxes. We have provided a first small software library with which you can generate different noises and sounds with different timbres.

Microphone input The Oxocard has a microphone. At the latest since speech recognition has been built into almost every smartphone, it has become clear that a microphone can be used not only to record sounds or noises, but also to analyze these data. With the built-in functions, the noise level as well as the dominant frequency can be determined and used in own projects.

Battery The built-in lithium-polymer battery allows wireless operation of the Oxocard.

USB The built-in battery can be charged via USB. It is also possible to read different values around the battery and USB and to integrate them into programs. So you can determine if the Oxocard is connected to a USB device and what the

Page 7: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

7

battery charge state is. Via USB it is also possible to program the Oxocard with Arduino, Espressif IDF or with Tigerjython.

Expansion ports With a little bit of skill you can build an adapter that adds further sensors to the Oxocard. The kit is available in the shop on oxocard.ch

The Oxocard is a device of the "Internet of Things" (IoT): this refers to the network of the next computer generation. These computers are no longer immediately recognizable as such, as they have no display and no keyboard. They are built into household appliances, vehicles or machines. IoT devices automatically network with other devices and the Internet and exchange information and commands. The Oxocard gives you an impression of how simple and powerful such network computers are and how they work. Some things can already be understood with the built-in sensors and you can also program applications yourself. For example, it is possible to use a microphone to perceive sounds or the accelerometer to detect vibrations, which either cause the device to perform a visual action or to make a discreet note somewhere in a database. This opens up exciting possibilities in the field of so-called "data mining", i.e. data collection and "machine learning", in which large data sets use algorithms from the field of artificial intelligence to examine data according to patterns and independently develop algorithms. 1.2 Programming with Blockly or Oxoscript? The Oxocard can be programmed in different ways: by block programming (blockly.oxocard.ch), Python, C++ and now also with scripting. This book concentrates on scripting and explains the programming language "Oxoscript" with many examples.

Page 8: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

8

Blockly, a visual programming language based on the Lego principle, is pre-installed on the brand-new Oxocard. The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used for demanding projects, but then the programs become confusing relatively quickly, because the blocks need a lot of space and the language is designed for simple tasks.

The new scripting language Oxoscript now offers an alternative. With this language we write "code", i.e. we write a kind of text which is translated into machine language by the Oxoscript translator and then transferred to the Oxocard.

This example program always draws an apple when the user presses the "L1" key. The two examples are identical in content.

ist gekippt nach links

nach links

nach rechts

nach vorne

nach hinten

L1

L2 L3

R1

R2R3

Ist Knopf gedrückt? L1

Alle Pixel löschen

Alle Pixel löschen

Warte Millisekunden3000

Einfarbiges Bild

X 0 Y 0

ist Knopf gedrückt? L1wenn…

dann

ACHTUNG, FERTIG, CODE!52 BEDINGTE ANWEISUNGEN 53

Mit dem Beschleunigungsensor spart ein Handy Strom.

���������������������������������������¡�������ϐ�����������ǡ������������������������haushälterisch mit der Energiemenge um, die ihm zur Verfügung steht. So stellt dein Handy viele Funktionen ab, wenn es auf dem Tisch liegt. Diesen Zustand nimmt es über den Beschleunigungssensor war.

Um solche Abläufe zu programmieren, brauchen wir den Wenn-Dann-Block und einen Ereignisblock.

Der Wenn-Dann-Block hat im Titel das Ereignis. In unserem Beispiel wird überprüft, ob ein Knopf gedrückt wurde. Wenn das der Fall ist, wird alles hin-ter «dann» ausgeführt. Hier zeichnen wir einen Apfel und warten 3 Sekunden. Es gibt viele Ereignisse, auf die die Oxocard reagieren kann. Wir stellen hier zwei vor:

WENN/DANN-BEDINGUNGEN EREIGNIS

ANWEISUNG

Page 9: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

9

1.3 Installing the Scripting Environment To work with scripting, the firmware must be changed. This is the operating system of the Oxocard. Currently there are three different firmwares: Blockly, Oxoscript and Tigerjython. How to install the Oxoscript firmware is described in a separate document. This can be found on the website https://editor.oxocard.ch under "Read now". After the installation is complete, we have an Oxocard that - is connected to the Internet (WiFi configuration) - has installed the new Oxoscript firmware, and - is linked to the browser on editor.oxocard.ch ("pairing") If the same computer is always used on the same network, this setup is a one-time thing. If the network is changed, such as when you bring the Oxocard home from school, you need to adjust the WiFi settings in the Hotspot menu. It's also possible to have two or more hotspots if you change locations frequently. If the computer in use changes, the pairing must be performed again. Pairing connects the Oxocard to a specific computer. Important: the pairing is also browser specific. For example, if the same computer is used once in the Safari browser and then in the Chrome browser, the pairing must be renewed each time. With the Oxoscript firmware installed, you can only program with the editor, no longer with Blockly. If you want to use Blockly again, the firmware must be reset according to the online instructions. The instructions for all these configurations can be found either in the package or online in the Blockly and Oxoscript editors (blockly.oxocard.ch or editor.oxocard.ch).

Page 10: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

10

1.4 The Oxoscript development environment Before we start with programming, here is a short overview of the environment. The Oxoscript environment can be found under the link: https://editor.oxocard.ch.

The Oxoscript editor is dominated by a code editor (A). Here the scripts are written, which are then translated and transferred to the Oxocard. The editor masters today's common programming editor functions such as auto-completion, colored instructions, help and positioning lines. By using the right mouse click, additional functions are also available. As soon as something in the code is changed, the program is automatically checked for errors in the background. You can see this by the info line F turning orange. If an error is detected, the corresponding line is marked red and the appropriate error message is displayed. Whenever the status line (F) is green, the program can be downloaded to the connected Oxocard (see "Download" key combination according to the instructions). If a program produces output to the browser, this is output in the OUTPUT window (B). We will see later that the Oxocard can also send data in other ways, which can be found in the sidebar (C) under "Data".

E D

C

F

A

B

Page 11: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

11

The sidebar (C) contains various categories, which we would like to briefly introduce here: Read now Here is this manual. My Oxocard The current Oxocard link can be checked here, or

released again. Documentation This is the online documentation of all functions that are

available in Oxoscript. Examples Here you will find various examples that can serve as a

basis for your own experiments. Worksheets The worksheets can be found in this section. Data If you use pushValues in scripting to send data to the

browser, it will appear here and can be edited. Settings Here you can change the language and change

individual editor settings. Feedback At this point you can find an e-mail address for beta

feedback. Later we will add a form here.

Page 12: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

12

1.5 Structure of a Script In Oxoscript every program has the same basic structure and starts with a main function: def main(): connect(WIFI) print "Hello from the Oxocard!"

"main" is the function that is always executed when the Oxocard is started. It is defined with the following signature: def main():

So the Oxocard checks if there is a main function and executes the indented commands sequentially. In this simple example, the Oxocard connects to the Internet via "connect(WIFI)" and then sends a text to the OUTPUT window of the browser: connect(WIFI) print "Hello from the Oxocard!"

Page 13: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

13

1.6 Next Steps There are several ways to teach yourself how to program. Depending on your previous knowledge and also personal preference, you can first use the language reference described in this document to get an overview and independently carry out your own small tasks. A normally rather unconventional method, but widely used in the programming world, is learning by means of ready-made examples. No matter if you are a beginner and have never programmed anything before, or if you already have experience: studying ready-made, functional examples has the advantage that you can draw conclusions about the program based on a result and thus understand it better. Even an experienced developer can gain valuable information about how to use the language. The examples can be easily executed by opening them via menu and transferring them to the Oxocard. Many examples have a small comment in the first lines of code, most of them are self-explanatory. The code is in English or trivialized English. It is worth trying to find out here line by line what the program does exactly. If a term appears which is not clear, you can take a short look at the chapter in question in this language reference. The next step is to make small changes. Programs usually consist of program logic, which is a bit difficult to understand at the beginning, and numbers and texts that we can read. A simple exercise now is to change these numbers or texts and then check what happens. Let us look at the example "Hello World": def main(): setColor(0, 150, 40) drawText("Hello World", false) delay(2000)

When we start the example, Hello World is displayed as a ticker in a certain color and after 2 seconds the Oxocard switches off again. If you search for "setColor" / "drawText" or "delay" in this reference you will find a description of these commands. For example, you can see that setColor is used to set the color with RGB color values. After reading only a few lines you are able to set any color. In a short time, you will understand how this program works and you will have learned three exciting commands that you will already know in more complex programs. The experiments available free of charge on the online platform are also based on this method.

Page 14: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

14

2 Reference: Language constructs 2.1 Program Sequence A program always starts with «def main():». The following statements must be indented, as is common in Python: def main(): instructions instructions

2.2 Variable Declaration The following data types are currently available in Oxoscript: Data type Size Examples Integer 2 Bytes

(-32768 bis 32767) 1 -3 15 -12342 +9932 0b00000000 0xff 'c'

String (text) Any length, currently without special characters (only ASCII character set)

"Oxocard" "Hello World" " The result is 10"

Lists (numbers) Range of values of a number: (-32768 bis 32767)

[1,3,-4, 0]

Variables can be declared globally and functionally locally. Important: there are no block variables. These are always visible at least function wide. Wherever possible, local variables should be preferred to global ones, since global variables require memory during the entire program flow, whereas with local variables the memory is released again when the functions are terminated. Local variables One speaks of local variables when they are declared within a function, e.g. indented within "def main ():". Here is an example:

Page 15: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

15

def main(): connect(WIFI) a=10 print a b="Hello World!" print b c=[1,2,3] print "size :" print size(c) disconnect()

Output: 10 Hello World! 3

Here we define three different types of variables and then output the value of each. This first statement defines an integer variable by assigning a value: a=10

Integer variables are generally only assigned to numbers, although a single character can also be used as a special case. In this case, the character must be placed in a single quotation mark: a='c'

It is also possible to enter a binary value (preceded by "0b") and a hexadecimal value (preceded by "0x"). The number systems are very common in computer science. They are a bit unfamiliar when you see them for the first time, so we will introduce them here briefly. We usually calculate in the decimal system, using the digits 0 to 9. With one digit we can represent 0-9, i.e. 10 different values. If we can have two digits, we represent 100 (102) etc. In the binary system there are only 0 and 1, so if we have one digit, we can represent two values. If we have two places, we can represent four values, namely: 00, 01,10 and 11, i.e. 22. In the hexadecimal system we have 16 values per place. Since we only know the numbers 0-9, we use the letters a-f in the hexadecimal system, i.e. one place can take the values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and a, b, c, d, e, f, therefore there are 16 states. With two places we have 162, 256 possible values that we can represent.

Page 16: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

16

As mentioned before, these number systems are important in computer science, since the smallest storable unit is always a so-called bit. This can be compared to an on/off switch and this can only represent two states. So, if we want to store large numbers in the computer, we have to consider how many bits we need for the number we have in mind. With 8 bits you can store 255 values for example (28). When programming we will rarely need the hexadecimal numbers, but the binary numbers have a practical use. The following program draws a smiley on the Oxocard screen.

(You draw pictures with the bits. In this case we need 8 lines of 8 bits each to draw a smiley).

image1 = [] image1 += 0b00000000 image1 += 0b00100100 image1 += 0b00100100 image1 += 0b00000000 image1 += 0b00011000 image1 += 0b01000010 image1 += 0b00111100 image1 += 0b00000000

Page 17: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

17

Variables can be increased or decreased by one with the ++ or -- statements: def main(): connect(WIFI) a=0 print a a++ print a a++ print a a-- print a a-- print a disconnect()

0 1 2 1 0

A text is assigned to the variable b, which we then print with "print ... " afterwards: b="Hello World!" print b

Number series are declared with square brackets. The following example creates a list with the numbers 1, 2 and 3. With the function "size(..)" the size of the list can be read. c=[1,2,3]

l = size(c) print "size:", l

It is important to know that the above-mentioned variables keep their type. After assigning the value 10 to a, Oxoscript has reserved a space in memory for the variable for a number. It is then no longer possible to assign a text to the variable a, for example. This is partly possible in other programming languages but should be avoided from the point of view of code readability. A list variable can also be initialized "empty" if the values are to be inserted later. The following statement reserves a variable c, in which a list is to be inserted later: c=[]

Global variables

Page 18: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

18

The previous statements provided the variable with an appropriate space when it was first assigned, in that Oxoscript automatically determined the type. If you want to define a variable "globally", you must specify the type for text and list variables, as explained in the following example: a=0 b=[] def main(): connect(WIFI) a=4711 b="This is a global variable " print a print b disconnect()

Output: 4711 This is a global variable

The variables a and b are globally visible. This means that they are visible within main, but also in all other functions (see Functions). The integer variable is simply defined by listing the variables on the same column as "def" and assigning the value 0: a=0

List and text variables are declared with an empty square bracket: b=[]

Page 19: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

19

2.3 Output of Data in the OUTPUT Window of the Browser An instruction is available for the output of data Instruction Declaration print ... Outputs any expression in the output window in the browser.

Important: an Internet connection is required for print to work. This is always initiated with the command connect(WIFI).

Examples: def main(): connect(WIFI) s = "Hello" print s x = [1,2,3] print x print 12+15 a = 47-(12+18) print "Result: " print a print " All in all:", s,x,a disconnect()

Hello 1, 2, 3 27 Result: 17 All in all: Hello 1, 2, 3 26

Depending on the type of variable, print applies a different formatting. print "Result: " + a

Alternatively, the values can be packed into a statement separated by commas, which leads to the same result: print "Result:", a

Page 20: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

20

2.4 Expressions and mathematical functions Integer variables can be calculated in many ways. The following operators are available: Operators Example + - / * Addition: 1+2

Multiplication: 4*5 Integer division: 10/2 Subtraction: 8-4

% provides the rest of a division ("Modulo"): 10 % 3 = 1 (10/3) = 3 (Integer value)

( ) 10-(3+4) Currently we only have a small set of mathematical functions, but this will be expanded in the near future. Function Example sinf(grad, faktor) Returns the sine value of the value specified in degrees

and multiplies the result by "factor": a = sinf(30,100) The sine of 30 degrees is 0.5235..., multiplied by 100 and without decimals this gives the value 52. Degrees: Value range between 1 and 360.

cosf(grad, factor) Returns the cosine value of the specified angle in degrees, multiplied by the factor.

random(start, end) returns a random number in the value range of start and end. r = random(1,10) returns any number between 1 and 10.

def main(): connect(WIFI) a=10 b=30 c=3*a+b d=a*(b%9) print a,b,c,d disconnect()

10 30 60 3

Page 21: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

21

2.5 Processing of lists There are various options for editing lists, which are summarized in the following table. Command Function Example variable* Defines an empty list or

text variable in the parameter block of a def function

def sum(list*) def split(splittedlist*, origlist*,from, to)

variable = [] Empty list (local) a = [] b = [] hallo = []

variable = [value1, value2 ..]

Assignment of a list of numerical values

oneToTen = [1,2,3,4,5,6,7,8,8,10] primeNumbers = [2,3,5,7,11]

variable+= value adds a value to the list a = [1,2,3] a += 4

variable = list1 + value you can also assign a single value to a list

a = [1,2,3] + 4

variable = list1+ list2 lists can also be combined a = [1,2,3] + [4,5,6] variable[index] reads a value of a variable

at a specific location Note: the first digit has the index 0

a = [1,2,3] print a[0] + a[1] + a[2]

size(variable) reads the size of the list A = [1,1,1,1,1,1,1,1] print size(a)

min(list) returns the smallest value of a list

a = min([1,2,3]) a ist 1

max(list) returns the largest value in a list

a = max([1,2,3]) a ist 3

avg(list) provides the average

a = avg([1,2,3]) a ist 2

Page 22: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

22

def main(): connect(WIFI) list1 = [] list1 += 1 list1 += 2 list1 += 3 print list1 list2 = [1,2,3,4,5,6,7,8,9,10] print list2 list3 += list1 list3 += list2 print list3 print "Sum of the list1: " print list1[0] + list1[1] + list1[2] print "Number of elements in list3: " print size(list3) disconnect()

Output: 1, 2, 3 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Sum of the list1: 6 Number of elements in list3: 13

You can also use lists in other statements, for example, you can output a list directly using print: print [1,2,3]

1, 2, 3

You can also calculate values in lists: a = [2*2,4*4,8*8] print a

4, 16, 64

Calculated values can also be added:

Page 23: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

23

a = [1,2,3] + (3*4-2) print a

1, 2, 3, 10

2.6 Editing texts The editing of texts works in principle in the same way as for lists. The same functions are also available. Command for texts Function Example variable = "" Defines an empty text

variable a="" name=""

variable ="text" Assignment of a text name="Thomas" Ort="Liebefeld"

variable+="test" Adding to a text ort = "3097 " ort += "Liebefeld

variable = "text" + number It is also possible to include numbers in texts.

print " Temperature: " + getTemperature() returns: Temperature: 24

def main(): connect(WIFI) a = "My name is" a+= " Thomas" print a disconnect()

Output: My name is Thomas

Texts and numbers can be mixed arbitrarily, whereby numbers are currently always output in decimal notation: def main(): connect(WIFI) print "The temperature is " + getTemperature() + " degree Celsius." disconnect()

Page 24: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

24

Output: Temperatur 24 Grad Celsius

Important notice: Texts are nothing more than lists. You can therefore link lists and texts with "+", where the left element determines the type of expression. Here is an example: def main(): connect(WIFI) a = "Test" b = [] print a + b print b + a

Output: Test 84, 101, 115, 116

With the first "print" the left character is a string, therefore "Test" is correctly output. With the second "print" we have a list of numbers on the left (here an empty list), to which we attach a text. Oxoscript interprets the result as a list. The values displayed here correspond to the numerical representations of the letters ("T" = 84, "e" = 101, etc.). Sometimes you have to consciously force the formatting. For example, if you want to format a list as a string, you can do this with the following statement: def main(): connect(WIFI) alphabet = [] for i in 26: alphabet+=(97+i) print "" + alphabet

Output: abcdefghijklmnopqrstuvwxyz

Page 25: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

25

2.7 The For Loop With the for loop you can step through a list of elements. The structure is as follows: for variable in expression: instructions

"expression" can be a number, a list or a variable. In the following example we create a list "a" with numbers and calculate the sum: def main(): connect(WIFI) a = [1,2,3,4,5,6,7,8,9,10] s=0 for i in a: s=s+i print i print "Sum: " print s disconnect()

Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Sum: 55

Man kann die Schleife auch mit einer Integer-Variable oder eine Zahl initialisieren, wie folgendes Beispiel zeigt: def main(): for i in 10: print i x = 10 for i in x: print i

0 1 2

Page 26: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

26

3 4 5 6 7 8 9 0 1 2 3 4

The loop always starts at 0 and increases by one each time, i.e. if the number 5 is specified, the loop passes through the values from 0 to 4. It is also possible to specify a list directly: def main(): for i in [0,1,2,3,4,5,6,7]: print i

0 1 2 3 4 5 6 7

Page 27: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

27

2.8 The Repeat Loop The repeat instruction repeats a block a specified number of times and is defined as follows: repeat number: instructions....

Example: def main() : connect(WIFI) s = 10 repeat s: stars ="" repeat s: stars+="*" print stars disconnect()

The example consists of two nested repeat instructions. The inner loop prints the columns, the outer loop prints the rows: ********** ********** ********** ********** ********** ********** ********** ********** ********** **********

Page 28: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

28

2.9 Conditional Statements with if/then/else Conditional statements are formulated with the if statement. The structure is as follows: if Here's a condition: Here are instructions that are executed when the condition is met. elif Here is another condition If the second condition is met, this block is executed. else: Here are the instructions that are executed alternatively.

The elif/else statements are optional and can also be omitted. In addition, the "elif" block can be specified several times, whereby the "else" block must always be at the end (or omitted). Example: def main() : connect(WIFI) for x in [1,2,3]: if x == 1: print "one" elif x == 2: print "two" elif x == 3: print "three"

Output: one two three

The following comparison operators can be used: Comparison Operators Example == is equal* != is not equal* > greater than >= greater than or equal to < less than <= less than or equal to && or "and" and || or "or" or not not

* these two comparison operators can also be applied to lists and strings.

Page 29: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

29

Results of comparison operators can also be assigned to variables. Numerically, "false" corresponds to the value 0 and "true" to the value 1. We will see the comparison operations in the while block as well. The operator "not" can be prefixed to a variable, as demonstrated in the following example: def main(): connect(WIFI) a=false b=not a if not a: print "a is true" if c: print "c is not true" disconnect()

Output: a is true c is not true

Lists and strings can also be compared, as the following example shows: def main(): connect(WIFI) list1=[] list1+=1 list1+=2 list1+=3 if list1 == [1,2,3]: print "The list has the elements 1,2 and 3!"

Output: The list has the elements 1,2 and 3

Page 30: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

30

2.10 The While Loop The while loop is executed as long as the condition is true. In the following example, we have a sequence number i that is incremented by one for each pass. The loop is now executed as long as i is smaller than the length of the list "l". def main() : connect(WIFI) l=[] x=0 repeat 10: x++ l+=x i = 0 while i<size(l): print l[i] i++ disconnect()

Output: 1 2 3 4 5 6 7 8 9 10

When programming it is sometimes useful to use an endless loop. This is often also implemented with while. In this case you simply use a condition that is always valid. In the simplest case this is "true": def main(): connect(WIFI) while true: print " I will never stop"

I will never stop I will never stop I will never stop I will never stop ....

Page 31: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

31

2.11 Bit Operations Oxoscript supports the following bitwise operations: Operation Function Example a << b Move bitwise to the right 0b00000001 << 1

= 0b00000010 shifts the bit pattern one position to the left.

a >> b Move bitwise to the right 0b10000000 >> 1 = 0b01000000 shifts the bit pattern one place to the right.

a & b Bitwise "and" Every digit that occurs both in a and b is taken

0b11110000 & 0b10100000 = 0b10100000

a | b Bitwise "or" Every digit that occurs in either a or b is taken over

0b11110000 | 0b10100011 = 0b11110011

a ^ b "xor" / either or Only the positions that are set at either a or b are taken over.

0b10010001 ^ 0b11110000 = 0b01100001

For the output of binary formatted numbers the function "bin(number)" is available. The following example shifts a bit pattern one digit to the left and then outputs the result first in decimal and then in binary representation: def main(): connect(WIFI) a = 0b00000001 repeat 8: print a print bin(a) a = a << 1

Output: 1 00000001 2 00000010 4 00000100

Page 32: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

32

8 00001000 16 00010000 32 00100000 64 01000000 128 10000000

The bit operations are very rarely used in web/apps or database solutions. However, they are still very up-to-date for programming close to the hardware, since sensor chips are often configured via bit patterns.

Page 33: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

33

2.12 Break and Continue The loops "for", "repeat" and "while" each have two additional commands with which the loop pass can be changed. break Terminates the loop prematurely and

continues the program where the loop ends. continue Cancels the current loop and starts over

again. Example: def main(): connect(WIFI) for i in 10: if i ==5: continue elif i>=8: break print i

Output: 0 1 2 3 4 6 7

If i=5, the program jumps to the start of the loop and 5 is not output. If i >=8, we abort the loop prematurely, so 9 is not output.

Page 34: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

34

2.13 Declaration of Functions A function structures the code into logical units. In Oxoscript, functions are kept very simple and somewhat more limited than in other languages. Nevertheless, impressive programs can be implemented, even recursive calls, as we will see in the following. A function is declared as follows: def functionName (parameter,...): instructions

Some explanations: The function name can be freely defined. However, the function must be defined BEFORE the first use, otherwise it is not visible and an error is output. def helloWorld(): instructions

def something(): instructions

The parameters are optional. You can specify integer and list types. Integer variables are simply named, list variables must also be marked with an *: def addition(x,y): return x+y

def subtraction(x,y): return x-y

def sum(list*): r = 0 for x in list: r=r+x return x

Important: the list variables are always passed by reference. This means that the passed variable is changed by the function call. Return can currently only return integer values, not lists. Some examples: # function without parameter def helloWorld(): print "Hello World!" # function with int parameters def printStars(number_of_stars):

Page 35: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

35

stars="" repeat number_of_stars: stars+="*" print stars # function with integers and list parameters def fillArray(ch,count,array*): repeat count: array+=ch def main(): connect(WIFI) helloWorld() printStars(10) list = "" fillArray('x',10,list) print list disconnect()

Output: Hello World! ********** xxxxxxxxxx

The following example draws a pyramid using a recursive algorithm: def pyramid(elements, height): spaces = "" repeat height - elements: spaces +=" " stars = "" repeat elements: stars +="**" print spaces + stars if elements < height: pyramid(elements+1, height) def main(): connect(WIFI) pyramid(1,20) disconnect()

Output: ** **** ****** ******** **********

Page 36: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

36

************ ************** **************** ****************** ******************** ********************** ************************ ************************** **************************** ****************************** ******************************** ********************************** ************************************ ************************************** ****************************************

Page 37: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

37

2.14 Sending data to the browser With the Oxocard various data can be collected, e.g. temperature, noise, frequencies, but also vibrations or other values that can be calculated by the accelerometer. There is now a very elegant way to forward this data to the browser and via browser e.g. to Excel for other programs. With the functions "pushValue/pushValues/clearValue" data can be stored on the server. Here is an example: def main(): connect(WIFI) while true: a = getAngle() pushValue("angle", a) delay(2000)

This program reads the tilt of the card and sends a value to the "angle" list every 2 seconds. This list can be found under "Data":

Page 38: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

38

The values can also be displayed graphically with the diagram symbol at the top right:

The data can also be "actively" tracked by incorporating the "public link" link into other programs. The link provides current data in the well-known JSON format:

Page 39: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

39

3 Reference: Built-in functions of the Oxocard 3.1 Logic isButtonPressed()

Returns true if the corresponding button is pressed. int waitForButtonPressed(int button)

Wait until the corresponding button is pressed. 3.2 Mathematical functions int random(int from, int to)

Returns a random value between 'from' and 'to'. int sinf(int degree, int factor)

Returns the sine value of the angle specified in degrees and multiplies it by the factor. int cosf(int degree, int factor)

Returns the cosine value of the angle specified in degrees and multiplies it by the factor. int pow(int base, int exponent)

Calculates base to the power of exponent. int map(int value, int a1, int a2, int b1, int b2)

Converts the value "value" from the value range a1-a2 to the value range b1-b2. int abs(int value)

Returns the absolute value of the number. 3.3 Oxocard System Functions

reboot()

Restart the Oxocard. turnOffWakeUpButton(int l1, int l2, int l3, int r1, int r2, int r3)

Page 40: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

40

Switches the Oxocard off and determines with which of the given buttons the card can be switched on again afterwards. configureAutoTurnOff(int seconds)

Sets the time after which the Oxocard is automatically switched off. enableAutoTurnOff()

Activates the automatic switch-off (normal: 120s). disableAutoTurnOff()

Disables the automatic switch-off. int getBatteryVoltage()

Delivers the battery voltage in millivolts. int isFullyCharged()

Returns true when the battery is fully charged. int isUsbPluggedIn()

Returns true when the USB plug is plugged in. int getTemperature()

Returns the temperature in degrees Celsius.

sleep(seconds)

Switches the Oxocard off for the number of seconds. See also getWakeupCause()

int getWakeupCause()

With the function getWakeupCause() you can find out by which event the card was started. The following events are possible: • RESET • TIMER (see sleep()) • BTN_L1 • BTN_L2 • BTN_L3 • BTN_R1

Page 41: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

41

• BTN_R2 • BTN_R3 3.4 Matrix Drawing Commands setHueColor(int hue)

Sets a color in the color wheel. hue must be between 1 and 360 (degrees). enableAutoUpdate()

Activates the automatic updating of the display. Drawing commands are displayed automatically. disableAutoUpdate()

Disables the automatic refresh of the display. To display the drawing commands, update() must be called. int isAutoUpdate()

Returns true if automatic updating of the display is enabled. update()

Updates the display. See also disableAutoUpdate(). fillScreen()

Fills the entire display with the currently set color. clearScreen()

Deactivates/deletes all pixels. drawPixel(int x, int y)

Draws a pixel with the currently set color at the specified position. clearPixel(int x, int y)

Deletes the pixel at the specified position.

Page 42: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

42

readPixel(color, int x, int y)

Reads the color of the pixel at the specified position. color: • RED • GREEN • BLUE int isPixelSet(int x, int y)

Returns true if the pixel at the specified position is not empty (red=0, blue=0, green=0) but set.

fill()

Fills all subsequent geometric shapes (circle, rectangle, triangle) noFill()

The following geometric shapes are not filled in. See also "fill()". drawLine(int x1, int y1, int x2, int y2)

Draws a line from `x1`:`y1` to `x2`:`y2`.

drawRectangle(int x, int y, int w, int h)

Draws a square with upper left corner in position `x`:`y` and width and height of `w` and `h`. drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3)

Draws a triangle with the points `x1`:`y1`, `x2`:`y2` and `x3`:`y3`. drawCircle(int x, int y, int r)

Draws a circle with center `x`:`y` and a radius of `r`. drawNumber(int num)

Draws a number on the display. drawText(int[] text, int isBigFont)

Draws text on the display.

Page 43: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

43

setActiveFrameBuffer(int num)

Sets the active frame buffer (1, 2 or 3). copyFrameBufferContent(int fromBuffer, int toBuffer)

Copies the contents of one frame buffer to another. 3.5 Time Functions delay(int ms)

Wait for the specified time in milliseconds. int msSinceStart()

Returns the elapsed time in milliseconds since start-up. usetimeZone(int id)

Sets the time zone according to the following table: id Zone 1 Pacific/Samoa - Pago Pagp 2 Pacific/Honolulu - Honolulu, Papeete 3 Pacific/Auckland - Anchorage 4 America/Los Angeles - Los Angeles, Vancouver 5 America/Phoenix - Calgary, Phoenix 6 America/Chicago - Chicago, Mexico City 7 America/New York - New York, Toronto 8 America/Santiago - Santiago, Halifax 9 America/Sao_Paulo- Buenos Aires, São Paulo 10 Atlantic/Cape_Verde, Praia 11 Europe/London, Lisbon, London 12 Europe/Zurich, Zürich, Warsaw 13 Europe/Athens, Athens, Helsinki 14 Europe/Moscow, Moscow, Baghdad 15 Asia/Baku, Baku, Dubai 16 Asia/Karachi, Karachi, Yekaterinburg 17 Asia/Dhaka, Dhaka, Omsk 18 Asia/Jakarta, Jakarta, Bangkok 19 Asia/Kuala_Lumpur, Beijing, Kuala Lumpur 20 Asia/Tokyo, Tokyo, Yakutsk 21 Australia/Brisbane, Port Moresby, Brisbane 22 Australia/Sydney, Sydney, Nouméa 23 Pacific/Auckland, Auckland, Suva

Page 44: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

44

setTime(int h, int m, int s)

Sets the time manually. int getTime(int unit)

Get a time unit. unit: • SECONDS • MINUTES • HOURS int get_date(unit)

Get a date unit. unit: • DAY • MONTH • YEAR set_date(int d, int m, int y)

Sets the date (day, month, year) manually. 3.6 Accelerometer int getAcceleration(int axis)

Gets the acceleration value of the specified axis. axis: • AXIS_X • AXIS_Y • AXIS_Z int getNormalizedValue()

Get the normalized acceleration vector. setAccelerometerCursor(int x, int y)

Function to set the cursor. getAccelerometerCursor(axis)

Page 45: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

45

Function to read the cursor position. axis: • AXIS_X • AXIS_Y

configureAccelerometer(dataRate, range)

Configures the sensitivity of the accelerometer. The "dataRate" determines the scanning speed. The higher the rate, the more accurate the results. "range" determines the sensitivity. Constants exist for both parameters (see list of constants). int getOrientation()

Gets the current orientation of the Oxocard. Return value: • ORIENTATION_UNKNOWN • ORIENTATION_FLAT • ORIENTATION_FLAT_FLIPPED • ORIENTATION_UP • ORIENTATION_HALF_UP • ORIENTATION_DOWN • ORIENTATION_HALF_DOWN • ORIENTATION_LEFT • ORIENTATION_HALF_LEFT • ORIENTATION_RIGHT • ORIENTATION_HALF_RIGHT int isOrientation(int direction)

Returns true if the Oxocard is in the specified orientation. direction: see return value for getOrientation()

setReferenceVector()

Sets the reference vector to the current position on the Oxocard. This allows to initialize the vector before calling getAngle(). int getAngle()

Gets the current angle to the reference vector. If not specified, the vector is set when the card is flat on the table. 3.7 Sound Output playTone(int hz)

Page 46: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

46

Plays a sound at the specified frequency. playToneFor(int hz, int ms)

Plays a sound with the specified frequency for the set time. int noteToMs(int noteDuration)

Converts a note length in milliseconds. playNote(int note)

Plays a note. playNoteFor(int note, int ms)

Plays a note for the set time. noTone()

Stops playing sounds. setWaveForm(int waveForm)

Sets the waveform of the audio signal.

setOctave(int octave)

Sets the octave of the notes. setBPM(int bpm)

Sets the BPM (beats per minute) value. setToneBlocking(int isBlocking)

Wait after the tones. setVolume(int volume)

Sets the volume of the audio signal. int getVolume()

Returns the current volume value.

Page 47: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

47

volumeUp()

Increases the volume.

volumeDown()

Decreases the volume. 3.8 Microphone record(int ms)

Record audio for the specified time.

playRecorded(int repeat)

Plays the recording. waitForLoudNoise()

Waits for a loud noise and interrupts the program sequence accordingly. First the microphone must be started; see startMicrophone(). startMicrophone()

Activates the microphone. int readDecibel()

Returns the current noise level of the microphone in decibels. First the microphone must be started; see startMicrophone().

int readFrequency()

Returns the frequency with the currently highest amplitude. First the microphone must be started; see startMicrophone(). int stopMicrophone()

Disables the microphone. 3.9 Internet and Communication connect(int interface)

Page 48: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

48

Connects the Oxocard to the specified interface (currently only WIFI). disconnect()

Terminates the connection. startAccessPointMode()

Sets the Oxocard in the access point mode. startPairingMode()

Starts the connection process. bool hasNewScript()

Checks if a new script is available on the server. downloadScript()

Download the latest script, if available. pushValue(name, value)

Sends a value under the specified name to the browser. Important: requires a connect(WIFI) call first. pushValues(name, list)

Sends an entire list under the specified name to the browser. Important: requires a connect(WIFI) call first. getValues(name, buffer)

Gets a list of values under the name from the server and stores them in the buffer list. Important: requires a connect(WIFI) call first. clearValues (name)

If there is a list with the name on the server, this call will delete the list. Important: requires a connect(WIFI) call first.

Page 49: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

49

removeValues(name)

Deletes the list completely (including headers). 3.10 Permanent Memory The following commands can be used to save data permanently (persistently). This means that the values are also retained when the card is switched off and on again. Attention: this memory is only suitable for small amounts of data. bool hasPersistentVariable(key*)

Checks whether a variable has been saved under the name "key. savePersistentVariable(key*, value)

Stores the numeric "value" under the specified name. int loadPersistentVariable(key*)

Loads the variable and returns it as return value. deletePersistentVariable(key*)

Deletes the permanent variable. 3.11 Hardware Communication setPinMode(int pin, int mode)

Sets the mode of a pin. setPin(int pin, int state)

Sets the state of the specified pin. readPin(int pin)

Returns the state of the specified pin

Page 50: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

50

int i2cWrite(slaveAdr, dataAdr, data*)

Writes to the I2C data bus int i2cRead(slaveAdr, dataAdr, data*, dataLength)

Reads from the I2c data bus and writes the result to data.

3.12 Console Output

print ..., ..., ...

Function to send text, numbers or lists to the output window of the connected browser. hex()

Converts a number into a hexadecimal representation. bin()

Converts a number into a binary representation.

Page 51: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

51

4 Reference: Built-in Constants of the Oxocard Logical Values: true= 1 false= 0 True= 1 False= 0 TRUE= 1 FALSE= 0 Buttons: BTN_L1= 0 BTN_L2= 1 BTN_L3= 2 BTN_R1= 3 BTN_R2= 4 BTN_R3= 5 BTN_ANY= 6

Music and Sounds: NOTE_REST= 0 NOTE_C= 1 NOTE_CS= 2 NOTE_D= 3 NOTE_DS= 4 NOTE_E= 5 NOTE_F= 6 NOTE_FS= 7 NOTE_G= 8 NOTE_GS= 9 NOTE_A= 10 NOTE_AS= 11 NOTE_B= 12 Note Lengths: NOTE_DUR_WHOLE= 32 NOTE_DUR_HALF= 16 NOTE_DUR_QUARTER= 8 NOTE_DUR_EIGHTH= 4 NOTE_DUR_SIXTEENTH= 2 NOTE_DUR_THIRTY_SECOND= 1 Octaves:

Page 52: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

52

OCTAVE_C3= 0 OCTAVE_C4= 1 OCTAVE_C5= 2 OCTAVE_C6= 3 OCTAVE_C7= 4 OCTAVE_C8= 5 Tone Colors (waveforms): WAVEFORM_SINE= 0 WAVEFORM_SQUARE= 1 WAVEFORM_SAWTOOTH= 2 WAVEFORM_TRIANGLE= 3 Connections: WIFI= 0 Orientations: ORIENTATION_UNKNOWN= 0 ORIENTATION_FLAT= 1 ORIENTATION_FLAT_FLIPPED= 2 ORIENTATION_UP= 3 ORIENTATION_HALF_UP= 4 ORIENTATION_DOWN= 5 ORIENTATION_HALF_DOWN= 6 ORIENTATION_LEFT= 7 ORIENTATION_HALF_LEFT= 8 ORIENTATION_RIGHT= 9 ORIENTATION_HALF_RIGHT= 10 Axes: AXIS_X= 0 AXIS_Y= 1 AXIS_Z= 2 Wake Up Reasons (wakeupCause) RESET= 7 TIMER= 8 Time and Date Constants: SECONDS= 0 MINUTES= 1 HOURS= 2 WEEKDAY= 3 DAY= 4 MONTH= 5 YEAR= 6 Pins: IO5= 5 IO16= 16 IO17= 17

Page 53: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

53

IO18= 18 IO19= 19 IO23= 23 Pin Modes: INPUT= 1 INPUT_PULLUP= 2 INPUT_PULLDOWN= 5 OUTPUT= 9 Hardware Connections: HIGH= 1 LOW= 0 IO5 = 5 IO16 = 16 IO17 = 17 IO18 = 18 IO19 = 19 IO23 = 23 INPUT = 1 INPUT_PULLUP = 2 INPUT_PULLDOWN = 5 OUTPUT = 9 Weather constants: TEMPERATURE= 0 DEW_POINT= 1 HUMIDITY= 2 WIND= 3 PRECIPITATION= 4 Color selection for getPixel(color, x,y) RED= 0 GREEN= 1 BLUE= 2 Accelerometer: Datarate: POWER_DOWN = 0 NORMAL_1_Hz = 1 NORMAL_10_Hz = 2 NORMAL_25_Hz = 3 NORMAL_50_Hz = 4 NORMAL_100_Hz = 5 NORMAL_200_Hz = 6 NORMAL_400_Hz = 7 NORMAL_1344_Hz = 9 Range:

Page 54: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

54

MAX_2G = 0 MAX_4G = 1 MAX_8G = 2 MAX_16G = 3

Page 55: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

55

5 Reference: Colour systems Colors can be categorized in different ways. For the Oxocard we use two colour systems, the RGB system and the Hue colour circle. Both are briefly introduced here. 5.1 The RGB Color System In the RGB color system the colors are composed of the primary colors red, green and blue. The individual values are specified as numerical values between 0 and 255, whereby 0 represents no color and 255 is the maximum value that can be specified. By combining these three colors, you can now combine 255x255x255, i.e. theoretically over 16 million different colors.

The color can be specified with the function setColor(r,g,b), whereby all three color components must always be specified. Here are two examples: red: setColor(255,0,0)

green: setColor(0,255,0)

Important note: The Oxocard uses very strong LEDs. Since for each of the basic colors a separate LED is necessary, we need 8x8x3 LEDs for our 8x8 pixel display. Unfortunately, not all of them are allowed to shine at maximum at the same time, because too high currents

Page 56: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

56

would flow. Therefore the colors are dimmed the more and the brighter the LEDs have to shine. 5.2 The Hue Colour System With the Hue color system, the colors are displayed on a color circle. Thus, 360 different colour values can be entered.

In Oxoscript the command is called setHueColor(c), which you can use for this: Examples: red: setHueColor(0)

Page 57: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

57

blue: setHueColor(240)

The color wheel is often used in combination with brightness or saturation. By combining it with the color value, millions of color combinations can be achieved again afterwards. With the Oxocard we use a simplified model without brightness/saturation.

Page 58: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

58

6 Technical background information Oxoscript is a fast single-pass compiler that generates a compact bytecode. This bytecode is then executed with an interpreter on the target system. The compiler can be run on the target device, e.g. on the Oxocard - or you can also use the compiler on a PC/Mac/Browser, and have only the bytecode interpreter run on the target system. Depending on the performance of the hardware, Oxoscript can thus be run on different - even the smallest - embedded controllers, since the resource requirements of the interpreter remain very low. Oxoscript is a strictly typed language, but its syntax was strongly inspired by Python. Compared to Python, however, Oxoscript has only a very simple garbage collector and the memory allocation is determined at compile time - with the exception of dynamic lists - which makes the interpreter much easier and faster. Oxoscript has integrated the common language constructs if/then - while - for, but also new concepts like "repeat". The internal data type is integer (2 bytes). This data type is used to store numbers and characters. In addition, there are dynamic lists with which number series and character strings can be stored. It was deliberately limited to a very simple type system to keep the space consumption and the complexity of the interpreter as low as possible. With the 2 bytes, integers in the value range of -32768, +32767 can be mapped. Floating point numbers were deliberately avoided in the first version. Despite strict typing, the operation is very easy and is very close to the simpler dynamic languages. This has been achieved by incorporating various syntactic optimizations («syntactic sugar»). To structure code, you can use the «def» statement to create procedures, as they are common in Python. Further structures, which serve for modularization or encapsulation, have been omitted, since Oxoscript is primarily intended for short programs. It is neither the goal nor the intention to use Oxoscript for the development of frameworks, low-level drivers or complex algorithms based on higher mathematics. Rather, Oxoscript is intended to use such libraries and make them available to script programmers via an easy-to-use interface. Depending on the target system, we offer a collection of built-in functions that allow procedural access to the system's functions as an abstraction layer. Due to the architecture special functions of the used controllers, but also powerful libraries written in C++ can be embedded in Oxoscript in a very simple way. In the case of the Oxocard, the palette is so powerful that even Internet communication solutions can be programmed with it, as the following simple program will show as an example: # Print a message in the web browser def main(): connect(WIFI) repeat 3: print ("Hello World") disconnect()

The resulting compilation is only 88 bytes in size: 11 00 41 02 00 00 10 00 0B 01 02 00 03 03 00 00 | ..A............. 04 00 00 02 00 00 25 0D 00 3A 2F 03 00 01 04 00 | ......%..:/..... 01 02 00 00 2D 04 00 01 10 00 05 10 00 0A 01 01 | ....-........... 04 00 00 35 03 00 00 0F 00 10 10 00 0C 01 2E 3C | ...5...........<

Page 59: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

59

3C 00 02 00 04 00 40 00 0C 00 03 01 0B 48 65 6C | <[email protected] 6C 6F 20 57 6F 72 6C 64 | lo World

The program first opens a connection to the Internet with «connect(WIFI)». In the block «repeat» the indented instruction is executed three times. «print» prints the output in the console window of the linked browser. «disconnect()» then disconnects the Internet connection again to save power on the device. Hello World Hello World Hello World

6.1 Distinction from Python Python, the programming language widely used at high schools, universities and in research, is today often used as an entry-level programming language, because the language is particularly easy to learn, but is nevertheless very powerful. With these advantages, however, it is not particularly efficient. This is not a significant limitation on fast PC's/Macs or in server environments with almost unlimited computer capacity. However, if you work with computers that only have little memory capacity and, in favor of energy efficiency, also have little computing power, Python unfortunately very quickly reaches its limits. Therefore, IoT devices are usually programmed with the machine-oriented programming languages C and C++. Today, more than 90% of these are also used for operating systems or time-critical applications. These statically typed languages produce very compact machine code, but programming is cumbersome and error-prone, as the programmer has to take care of much more technical details. For example, Python elegantly solves the very big problem of memory management by "building and consuming" data structures as desired, and then managing, cleaning up and reusing the memory required for this purpose for other purposes. This process is called garbage collector. There are currently various Python implementations available, including those specifically for embedded controllers with low performance. However, detailed analysis and many experiments have shown that none of the sources we tested can handle normal Python efficiently enough. In some cases, operation was not possible at all. With the most powerful ones, essential hardware parts were not supported, and only very small Python programs could be developed because the memory was not accessible. Furthermore, according to current knowledge, it is not possible to update the Python environment via WiFi. This means that updates would have had to be done manually using a PC or Mac and additionally installed software. All this led to the realization, after long attempts, that a different path had to be taken. During the research we spoke with various teachers and also analyzed existing beginners' teaching materials. Interestingly enough, it turned out that only a very small part of the Python language is used at all. So, the full Python language scope is rarely necessary. The balancing act between simple beginner language and efficient execution is great, so the result can only be a well-defined compromise. Our goal was to find the optimum of these diverging aspects. Oxoscript is typed statically, making the language feel as if it were dynamic. We use tricks from compiler technology ("syntactic sugar") for this. Oxoscript massively restricts the data types, so that only a very simple garbage collector is necessary, the memory consumption remains low and a high execution speed can be achieved. With slightly larger chips, the entire Oxoscript compiler including interpreter can run on the target system. If performance is low, the Oxoscript

Page 60: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

60

compiler can be started in the browser window on the PC/Mac. The resulting very compact, architecture-independent machine code can then be transferred to the target system and executed. The interpreter required for this is so small that it also runs on very compact MCU's. It is important to recognize what Oxoscript solves for a problem: It is not intended to provide all facets of modern programming languages, but primarily to offer an easy start. If we make the environment simple enough, yet powerful enough, we can awaken the students' enthusiasm for this fascinating world. Oxoscript is to be understood in this context as an educational programming language and as such can be used. However, due to the close proximity to Python, a change to the complete Python vocabulary is only a small step and quickly accomplished. 6.2 Purpose and area of application Oxoscript serves primarily as a configuration and learning language and is neither a full-fledged replacement for C++, nor can it compete with high-level languages such as Python, Ruby or Javascript. Oxoscript has a lot to offer: - The scripting language is ideal for occasional users and beginners as the syntax of the

language is based on Python and has a low frustration potential. - Programming is done in the browser window. No software has to be installed on the

PC/Mac, because the scripting compiler runs directly in the browser. - The code editor has automatic error detection during programming. In addition to

automatic completion during writing, the editor offers a full-text based language reference, extensive examples and this documentation.

- Programs written with Oxoscript are very fast in execution, because the environment does not have to consider many aspects of complicated systems, including dynamic typing, but also more complex language constructs like classes and inheritance, which have been omitted.

- The compiles, i.e. the executable programs, are very small, which means that they have very low requirements both in terms of communication and memory requirements on the target device. The Oxocard scripts are usually one hundred to one thousand times smaller than comparable conventionally programmed firmware based on C++. This is due to the fact that a kind of operating system with built-in interpreter is persistent on the target system. This means that the entire system does not have to be replaced with each update, but only the script code or the compilation.

- Oxoscript can be adapted very quickly and easily to specific hardware, since a simple C++ binding exists with which the range of functions can be adapted to the system environment. With the Oxocard, for example, this means that we have complete access to the sensors and actuators via the scripting environment, including I2C and I2S. With the latter, there is even an FFT implementation available for analyzing the audio frequency.

Oxoscript can be used as a configuration and learning language: Oxoscript is used as configuration language for example for the Oxobuttons in order to adapt the functionality of the button to your own needs, to draw pictures on the screen or even to create small applications.

Page 61: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

61

Oxoscript is primarily used as a learning language to familiarize students with simple programming algorithms on the Oxocard learning computer. With Oxoscript, we add a more powerful access to block programming, which allows much more sophisticated algorithmic experiments in the fields of art, gaming, communication, physics and mathematics.

Page 62: Book Draft «Introduction to the programming language ... · The programming is done by plugging blocks together. Blockly is particularly suitable as an introduction. It can be used

© 2020 by OXON AG, Liebefeld, Switzerland. This material is protected by copyright.

62

7 Change control 24.11.2019 First publication 03.12.2019 Constants added Various additions to the reference:

hasNewScript() removeValues(key) int i2cWrite(slaveAdr, dataAdr, data*) int i2cRead(slaveAdr, dataAdr, data*, dataLength) mathematical functions Function for persistent storage of values

if / elif added With print the bracket was removed everywhere, because it is no

longer necessary. break and continue added


Recommended