jueves, 21 de febrero de 2019
Azure notebooks - Tutorial: create and run a Jupyter notebook with Python
https://docs.microsoft.com/en-us/azure/notebooks/tutorial-create-run-jupyter-notebook
Azure notebooks
Tutorial: create and run a Jupyter notebook with Python
The completed notebook can be found on GitHub - Azure Notebooks Samples. This tutorial, however, begins with a new project and an empty notebook so you can experience creating it step by step.
Create the project
- Go to Azure Notebooks and sign in. (For details, see Quickstart - Sign in to Azure Notebooks).
- From your public profile page, select My Projects at the top of the page:
- On the My Projects page, select + New Project (keyboard shortcut: n); the button may appear only as + if the browser window is narrow:
- In the Create New Project popup that appears, enter or set the following details, then select Create:
- Project name: Linear Regression Example - Cricket Chirps
- Project ID: linear-regression-example
- Public project: (cleared)
- Create a README.md: (cleared)
- After a few moments, Azure Notebooks navigates you to the new project.
Create the data file
The linear regression model you create in the notebook draws data from a file in your project called cricket_chirps.csv. You can create this file either by copying it from GitHub - Azure Notebooks Samples, or by entering the data directly. The following sections describe both approaches.Upload the data file
- On your project dashboard in Azure Notebooks, select Upload > From URL
- In the popup, enter the following URL in File URL and cricket_chirps.csv in File Name, then select Done.
url
https://raw.githubusercontent.com/Microsoft/AzureNotebooks/master/Samples/Linear%20Regression%20-%20Cricket%20Chirps/cricket_chirps.csv
- The cricket_chirps.csv file should now appear in your project's file list:
Create a file from scratch
- On your project dashboard in Azure Notebooks, select + New > Blank File
- A field appears in the project's file list. Enter cricket_chirps.csv and press Enter.
- Right-click cricket_chirps.csv and select Edit File.
- In the editor that appears, enter the following data:
csv
Chirps/Minute,Temperature 20,88.6 16,71.6 19.8,93.3 18.4,84.3 17.1,80.6 15.5,75.2 14.7,69.7 17.1,82 15.4,69.4 16.2,83.3 15,79.6 17.2,82.6 16,80.6 17,83.5 14.4,76.3
- Select Save File to save the file and return to the project dashboard.
Install project level packages
Within a notebook, you can always use commands like!pip install
in a code cell to install required packages. However, such commands are
run every time you run the notebook's code cells, and can take
considerable time. For this reason, you can instead install packages at
the project level using a requirements.txt
file.- Use the process described in Create a file from scratch to create a file named
requirements.txt
with the following contents:
text
You can also upload amatplotlib==3.0.0 numpy==1.15.0 pandas==0.23.4 scikit-learn==0.20.0
requirements.txt
file from your local computer if you prefer, as described on Upload the data file.
- On the project dashboard, select Project Settings.
- In the popup that appears, select the Environment tab, then select +Add.
- In the first drop-down control (the operation) under Environment Setup Steps, choose Requirements.txt.
- In the second drop-down control (the file name), choose requirements.txt (the file you created).
- In the third drop-down control (the Python version), choose Python Version 3.6.
- Select Save.
With this setup step in place, any notebook you run in the project will run in an environment where those packages are installed.
Create and run a notebook
With the data file ready and the project environment set, you can now create and open the notebook.- On the project dashboard, select + New > Notebook.
- In the popup, enter Linear Regression Example - Cricket Chirps.ipynb for Item Name, choose Python 3.6 for the language, then select New.
- After the new notebook appears on the file list, select it to start the notebook. A new browser tab opens automatically.
- Because you have a requirements.txt file in the environment settings, you see the message, "Waiting for your container to finish being prepared." You can select OK to close the message and continue working in the notebook; you can't run code cells, however, until the environment is set up fully.
- The notebook opens in the Jupyter interface with a single empty code cell as the default.
Tour the notebook interface
With the notebook running, you can add code and Markdown cells, run those cells, and manage the operation of the notebook. First, however, it's worth taking a few minutes to familiarize yourself with the interface. For full documentation, select the Help > Notebook Help menu command.Along the top of the window you see the following items:
(A) The name of your notebook, which you can edit by clicking. (B) Buttons to navigate to the containing project and your projects dashboard, which open new tabs in your browser. (C) A menu with commands for working with the notebook. (D) a toolbar with shortcuts for common operations. (E) the editing canvas containing cells. (F) indicator of whether the notebook is trusted (default is Not Trusted). (G) the kernel used to run the notebook along with an activity indicator.
Jupyter provides a built-in tour of the primary UI elements. Start the tour by selecting the Help > User Interface Tour command and clicking through the popups.
The groups of menu commands are as follows:
Menu | Description |
---|---|
File | Commands to manage the notebook file, including commands to create and copy notebooks, show a print preview, and download the notebook in a variety of formats. |
Edit | Typical commands to cut, copy, and paste cells, find and replace values, manage cell attachments, and insert images. |
View | Commands to control visibility of different parts of the Jupyter UI. |
Insert | Commands to insert a new cell above or below the current cell. You use these commands frequently when creating a notebook. |
Cell | The various Run commands run one or more cells in different combinations. The Cell Type commands change the type of a cell between Code, Markdown, and Raw NBConvert (plain text). The Current Outputs and All Outputs commands control how output from run code is shown, and include a command to clear all output. |
Kernel | Commands to manage how code is being run in the kernel, along with Change kernel to change the language or Python version used to run the notebook. |
Data | Commands to upload and download files from the project or session. See Work with project data files |
Widgets | Commands to manage Jupyter Widgets, which provide additional capabilities for visualization, mapping, and plotting. |
Help | Commands that provide help and documentation for the Jupyter interface. |
You use a number of these commands as you populate the notebook in the sections that follow.
Create a Markdown cell
- Click into the first empty cell shown on the notebook canvas. By default, a cell is a Code
type, which means it's designed to contain runnable code for the
selected kernel (Python, R, or F#). The current type is shown in the
type drop-down on the toolbar:
- Change the cell type to Markdown using the toolbar drop-down; alternately, use the Cell > Cell Type > Markdown menu command:
- Click into the cell to start editing, then enter the following Markdown:
markdown
# Example Linear Regression
This notebook contains a walkthrough of a simple linear regression. The data, obtained from [college.cengage.com](http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/slr/frames/frame.html), relates the rate of cricket chirps to temperature from *The Song of Insects*, by Dr. G. W. Pierce, Harvard College Press.
In this example we're using the count of chirps per minute as the independent varible to then predict the dependent variable, temperature. In short, we're using a little data science to make ourselves a cricket thermometer. (You could also reverse the data and use temperature to predict the number of chirps, but it's more fun to use crickets as the thermometer itself!)
The methods shown in this example follow what's presented in the Udemy course, [Machine Learning A to Z](https://www.udemy.com/machinelearning/learn/v4/).
A lovely aspect of Notebooks is that you can use Markdown cells to explain what the code is doing rather than code comments. There are several benefits to doing so:
- Markdown allows for richer text formatting, like *italics*, **bold**, `inline code`, hyperlinks, and headers.
- Markdown cells automatically word wrap whereas code cells do not. Code comments typically use explicit line breaks for formatting, but that's not necessary in Markdown.
- Using Markdown cells makes it easier to run the Notebook as a slide show.
- Markdown cells help you remove lengthy comments from the code, making the code easier to scan.
When you run a code cell, Jupyter executes the code; when you run a Markdown cell, Jupyter renders all the formatting into text that's suitable for presentation.
markdown
## Install packages using pip or conda Because the code in your notebook likely uses some Python packages, you need to make sure the Notebook environment contains those packages. You can do this directly within the notebook in a code block that contains the appropriate pip or conda commands prefixed by `!`: \``` !pip install <pkg name> !conda install <pkg name> -y \```
- To edit the Markdown again, double-click in the rendered cell. To render HTML again after making changes, run the cell.
Create a code cell with commands
As the previous Markdown cell explained, you can include commands directly in the notebook. You can use commands to install packages, run curl or wget to retrieve data, or anything else. Jupyter notebooks effectively run within a Linux virtual machine, so you have the full Linux command set to work with.- Enter the commands below in the code cell that appeared after you used Run on the previous Markdown cell. If you don't see a new cell, create one with Insert > Insert Cell Below or use the + button on the toolbar.
bash
!pip install numpy
!pip install matplotlib
!pip install pandas
!pip install sklearn
markdown
Note that when you run a code block that contains install commands, and also those with `import` statements, it make take the notebooks a little time to complete the task. To the left of the code block you see `In [*]` to indicate that execution is happening. The Notebook's kernel on the upper right also shows a filled-in circle to indicate "busy."
pip install
commands to run, and because you already installed these packages in
the project environment (and because they're also included in Azure
Notebooks by default), you see many messages that read, "Requirement
already satisfied." All of that output can be visually distracting, so
select that sell (using a single click), then use the Cell > Cell Outputs > Toggle to hide the output. You can also use the Clear command on that same submenu to remove the output entirely.The Toggle command hides only the most recent output from the cell; if you run the cell again, the output reappears.
! pip install
commands using #
;
this way they can remain in the notebook as instructional material but
won't take any time to run and won't produce unnecessary output. In this
case, keeping the commented commands in the notebook also indicates the
notebook's dependencies.
bash
# !pip install numpy # !pip install matplotlib # !pip install pandas # !pip install sklearn
Create the remaining cells
To populate the rest of the notebook, you next create a series of Markdown and code cells. For each cell listed below, first create the new cell, then set the type, then paste in the content.Although you can wait to run the notebook after you've created each cell, it's interesting to run each cell as you create it. Not all cells show output; if you don't see any errors, assume the cell ran normally.
Each code cell depends on the code that's been run in previous cells, and if you neglect to run one of the cells, later cells may produce errors. If you find that you've forgotten to run a cell, try using the Cell > Run All Above before running the current cell.
If you see unexpected results (which you probably will!), check that each cell is set to "Code" or "Markdown" as necessary. For example, an "Invalid syntax" error typically occurs when you've entered Markdown into Code cell.
- Markdown cell:
markdown
## Import packages and prepare the dataset
In this example we're using numpy, pandas, and matplotlib. Data is in the file cricket_chirps.csv. Because this file is in the same project as this present Notebook, we can just load it using a relative pathname.
print
statement.
Python
import numpy as np
import pandas as pd
dataset = pd.read_csv('cricket_chirps.csv')
print(dataset)
X = dataset.iloc[:, :-1].values # Matrix of independent variables -- remove the last column in this data set
y = dataset.iloc[:, 1].values # Matrix of dependent variables -- just the last column (1 == 2nd column)
Note
You may see warnings from this code about "numpy.dtype size changed"; the warnings can be safely ignored.
markdown
Next, split the dataset into a Training set (2/3rds) and Test set (1/3rd). We don't need to do any feature scaling because there is only one column of independent variables, and packages typically do scaling for you.
Python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
markdown
## Fit the data to the training set
"Fitting" the data to a training set means making the line that describes the relationship between the independent and the dependent variables. With a simple data set like we're using here, you can visualize the line on a simple x-y plot: the x-axis is the independent variable (chirp count in this example), and the y-axis is the independent variable (temperature). Fitting the data means plotting all the points in the training set, then drawing the best-fit line through that data.
With two independent variables you can imagine a three-dimensional plot with a line fitted to the data. At three or more independent variables, however, it's no longer easy to visualize the fit, but you get the idea. In the end, it's all just mathematics, which a computer can handle easily without having to form a mental picture!
The regressor's `fit` method here creates the line, which algebraically is of the form `y = x*b1 + b0`, where b1 is the coefficient or slope of the line (which you can get to through `regressor.coef_`), and b0 is the intercept of the line at x=0 (which you can get to through `regressor.intercept`).
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None,normalize=False)
.
Python
from sklearn.linear_model import LinearRegression
regressor = LinearRegression() # This object is the regressor, that does the regression
regressor.fit(X_train, y_train) # Provide training data so the machine can learn to predict using a learned model.
markdown
## Predict the results
With the regressor in hand, we can predict the test set results using its `predict` method. That method takes a vector of independent variables for which you want predictions.
Because the regressor is fit to the data by virtue of `coef_` and `intercept_` and `coef_`, a prediction is the result of `coef_ * x + intercept_`. (Indeed, `predict(0)` returns `intercept_` and `predict(1)` returns `intercept_ + coef_`.)
In the code, the `y_test` matrix (from when we split the set) contains the real observations. `y_pred` assigned here contains the predictions for the same `X_test` inputs. It's not expected that the test or training points exactly fit the regression; the regression is trying to find the model that we can use to make predictions with new observations of the independent variables.
[79.49588055 75.98873911 77.87719989 80.03544077 75.17939878]
.
Python
y_pred = regressor.predict(X_test)
print(y_pred)
markdown
It's interesting to think that all the "predictions" we use in daily life, like weather forecasts, are just regression models of some sort working with various data sets. Those models are much more complicated than what's shown here, but the idea is the same.
Knowing how predictions work help us understand that the actual observations we would collect in the moment will always be somewhat off from the predictions: the predictions fit exactly to the model, whereas the observations typically won't.
Of course, such systems feed new observations back into the dataset to continually improve the model, meaning that predictions should get more accurate over time.
The challenge is determining what data to actually use. For example, with weather, how far back in time do you go? How have weather patterns been changing decade by decade? In any case, something like weather predictions will be doing things hour by hour, day by day, for things like temperature, precipitation, winds, cloud cover, etc. Radar and other observations are of course fed into the model and the predictions are reduced to mathematics.
markdown
## Visualize the results
The following code generates a plot: green dots are training data, red dots are test data, blue dots are predictions. Gray line is the regression itself. You see that all the blue dots are exactly on the line, as they should be, because the predictions exactly fit the model (the line).
Python
import matplotlib.pyplot as plt
plt.scatter(X_train, y_train, color = 'green')
plt.scatter(X_test, y_test, color = 'red')
plt.scatter(X_test, y_pred, color = 'blue') # The predicted temperatures of the same X_test input.
plt.plot(X_train, regressor.predict(X_train), color = 'gray')
plt.title('Temperature based on chirp count')
plt.xlabel('Chirps/minute')
plt.ylabel('Temperature')
plt.show()
markdown
## Closing comments At the end of the day, when you create a model, you use training data. Then you start feeding test data (real observations) to see how well the model actually works. You may find that the model is a little inaccurate over time, in which case you retrain the model with some new data. Retraining the model means you're creating a new fit line that's used for predictions. This regression can be used to examine the variability of the relationship between temperature and chirp count. Of course, if the model proves too inaccurate (that is, the predictions aren't very good), then it suggests that we might need to introduce more independent variables like humidity, time of year, latitude, amount of moonlight, and so on. If you have such data, you can do separate lines regressions for each independent variable, and then do multiple regressions with combinations of independent variables. Again, once you are working with more than one or two independent variables, it's much easier to use machine learning to crunch the numbers than to try to visualize it graphically.
Clear outputs and rerun all cells
After following the steps in the previous section to populate the entire notebook, you've created both a piece of running code in the context of a full tutorial on linear regression. This direct combination of code and text is one of the great advantages of notebooks!Try rerunning the whole notebook now:
- Clear all the kernel's session data and all cell output by selecting Kernel > Restart & Clear Output.
This command is always a good one to run when you've completed a
notebook, just to make sure that you haven't created any strange
dependencies between code cells.
- Rerun the notebook using Cell > Run All. Notice the kernel indicator is filled in while code is running.
If you have any code that runs for too long or otherwise gets stuck, you can stop the kernel by using the Kernel > Interrupt command.
- Scroll through the notebook to examine the results. (If again the plot doesn't appear, rerun that cell.)
Save, halt, and close the notebook
During the time you're editing a notebook, you can save its current state with the File > Save and Checkpoint command or the save button on the toolbar. A "checkpoint" creates a snapshot that you can revert to at any time during the session. Checkpoints allow you to make a series of experimental changes, and if those changes don't work, you can just revert to a checkpoint using the File > Revert to Checkpoint command. An alternate approach is to create extra cells and comment out any code that you don't want to run; either way works.You can also use the File > Make a Copy command at any time to make a copy of the current state of the notebook into a new file in your project. That copy opens in a new browser tab automatically.
When you're done with a notebook, use the File > Close and halt command, which closes the notebook and shuts down the kernel that's been running it. Azure Notebooks then closes the browser tab automatically.
Debug notebooks using Visual Studio Code
If the code cells in your notebook don't behave in the way you expect, you may have code bugs or other defects. However, other than usingprint
statements to show the value of variables, a typical Jupyter environment doesn't offer any debugging facilities.Fortunately, you can download the notebook's .ipynb file, then open it in Visual Studio Code using the Python extension. The extension directly imports a notebook as a single code file, preserving your Markdown cells in comments. Once you've imported the notebook, you can use the Visual Studio Code debugger to step through your code, set breakpoints, examine state, and so forth. After making corrections to your code, you then export the .ipynb file from Visual Studio Code and upload it back into Azure Notebooks.
For more information, see Debug a Jupyter notebook in the Visual Studio Code documentation.
Also see Visual Studio Code - Jupyter support for additional features of Visual Studio Code for Jupyter notebooks.
lunes, 18 de febrero de 2019
Métodos clásicos de ajuste de controladores PID Ziegler and Nichols - Классические методы настройки ПИД-регулятора Циглера и Николса
Métodos clásicos de ajuste de controladores PID Ziegler and Nichols
Классические методы настройки ПИД-регулятора Циглера и Николса
http://www.eng.newcastle.edu.au/~jhb519/teaching/caut1/Apuntes/PID.pdf
Классические методы настройки ПИД-регулятора Циглера и Николса
http://www.eng.newcastle.edu.au/~jhb519/teaching/caut1/Apuntes/PID.pdf
TensorFlow and deep learning, without a PhD - TensorFlow и глубокое обучение, без докторской степени
TensorFlow and deep learning, without a PhD
TensorFlow и глубокое обучение, без докторской степени
https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/#0
sábado, 9 de febrero de 2019
C Crash course
https://home.roboticlab.eu/en/programming/c/crashcourse
C Crash course
Program structure
As a principle, program written in C-language can be in any form, even
in one line, because the compiler assumes only the following of syntax
rules. However, it is advisable to take care of program coding style for
clearness and simplicity. Typical structure of a C-language program:
/* Include header files */ #include <avr/io.h> #include <stdio.h> /* Makro declarations */ #define PI 3.141 /* Data type definitions */ typedef struct { int a, b; } element; /* Global variables */ element e; /* Functions */ int main(void) { // Local variables int x; // Program code printf("Tere maailm!\n"); }
Comments
Programmer can write random text into program code for notes and
explanations that is no compiled. Comments can also be used for
temporally excluding some parts of code from compiling. Examples of two
commenting methods:
// Line comment is on one line. // Text after two slash signs is considered as comment. /* Block comment can be used to include more than one line. The beginning and the end of a comment is assigned with slash and asterisk signs. */
Data
Data types
C-language basic data types:
The word “signed” in brackets is not necessary to use because data types are bipolar by default.
AVR microcontroller has int = short
PC has int = long
There is no special string data type in C-language. Instead char type arrays (will be covered later) and ASCII alphabet is used where every char has its own queue number.
Type | Minimum | Maximum | Bits | Bytes |
---|---|---|---|---|
(signed) char | -128 | 127 | 8 | 1 |
unsigned char | 0 | 255 | 8 | 1 |
(signed) short | -32768 | 32767 | 16 | 2 |
unsigned short | 0 | 65535 | 16 | 2 |
(signed) long | -2147483648 | 2147483647 | 32 | 4 |
unsigned long | 0 | 4294967295 | 32 | 4 |
float | -3.438 | 3.438 | 32 | 4 |
double | -1.7308 | 1.7308 | 64 | 8 |
AVR microcontroller has int = short
PC has int = long
There is no special string data type in C-language. Instead char type arrays (will be covered later) and ASCII alphabet is used where every char has its own queue number.
Variables
Program can use defined type of memory slots - variables. Variable names
can include latin aplhabet characters, numbers and underdashes.
Beginning with a number is not allowed. When declarations to variables
are being made, data type is written in front of it. Value is given to
variable by using equal sign (=). Example about using variables:
// char type variable c declaration char c; // Value is given to variable c. c = 65; c = 'A'; // A has in ASCII character map also value 65 // int type variable i20 declaration and initialization int i20 = 55; // Declaration of several unsigned short type variables unsigned short x, y, test_variable;
Constants
Constants are declarated in the same way as variables, exept const keyword is added in front of data type. Constants are not changeable during program work. Example about using them:
// int type constant declaration const int x_factor = 100;
Structures
Basic data types can be arranged into structures by using struct keyword. Structure is a combined data type. Type is declarated with typedef keyword. Example about structures by creating and using data type:
// Declaration of a new data type "point" typedef struct { // x and y coordinates and color code int x, y; char color; } point; // declaration of a variable as data type of point point p; // Assigning values for point variable p.x = 3; p.y = 14;
Arrays
Data types can be arranged into arrays. Array can have more than one
dimensions (table, cube etc). Example about using one- and
two-dimensional arrays:
// Declaration of one- and two-dimensional arrays char text[3]; int table[10][10]; // Creating a string from char array text[0] = 'H'; // Char text[1] = 'i'; // Char text[2] = 0; // Text terminator (0 B) // Assigning new value for one element. table[4][3] = 1;
Operations
Variables, constants and value returning functions can be used for
composing operations. The result of and operation can be assigned to a
variable, it can be used as a function parameter and in different
control structures.
Arithmetic operators
C-language supported artithmetic operations are addition (+),
subtraction (-), multiplication (*), division (/) and modulo (%). Some
examples about using operators:
int x, y; // Modulo, multiplication and assigning value // x gets value of 9 x = (13 % 5) * 3; // Adding-assigning operator // x gets value of 14 x += 5; // Quick style method for subtracting 1 // x gets value of 13 x--;
Logical operators
Logical operators are negation NOT (!), logic multiplication AND
(&&) and logic addition OR (||). Example about using them:
bool a, b, c; // Initialization a = true; b = false; // Negation // c will get a value of false because a is true c = !a; // Logic multiplication // c will get a value of false because one of the operators is false c = a && b; // Logic addition // c will get a value of true because one of the operators is true c = a || b;NB! bool data type in C-language is actually missing and instead integers are used where 0 marks false and every other value marks true. For example, in HomeLab library bool is defined as unsigned char. Constant true marks a value of 1 and false a value of 0.
Relational and equality operators
Logical values are a result of comparison of variable values. Equality
operators are equal to (==), not equal to (!=), greater than (>),
greater than or equal to (>=), less than (<) and less than or
equal to (⇐). Exaple about using them:
int x = 10, y = 1; // greater than operation which is true // brackets around the operation are only for clarity bool b = (5 > 4); // Not equal to operation // The result is false b = (4 != 4); // Arithmetic, equality and logic operations alltogether // b is false because the first operator of logic multiplication is false b = (x + 4 > 15) && (y < 4);
Bit operations
Bit operations are for data manipulation in binary numeral system. These
can be applied only to integer type data. Bit operations are quite
similar to logic operations but differ from them because operation is
carried out with every single bit not the whole number. Bit operations
in C-language are inversion (~), conjunction (&), disjunction (|),
antivalency (^), left shift («) and right shift (»).
// Declaration of unsigned 8 bit char type variable // Variable value is 5 in decimal system, 101 in binary system unsigned char c = 5; // Disjunction of c with a digit 2 (010 in binary) // c value will become 7 (111 in binary) c = c | 2; // Bit left shift by 2 // c value will become 28 (11100 in binary) c = c << 2;Bit operations are essential when using the registers of microcontroller. These are described in AVR register chapter.
Functions
Functions are part of a program that can be called by its name. Function
can include parameters as input and can return one output. If the
function is not returning a parameter, it has type void. If the function has no parameters as its input, in older C-language compilers void must also be written besides parameter declaration. Example about addition function and a function without return:
// Declaration of 2 int type parameter function // The function returns int type value int sum(int a, int b) { // Addition of 2 variables and returning of their sum return a + b; } // Function without parameters and no return output void power_off(void) { }To use a function, it must be called. It is required that a function is declared before call. Example about calling addition function:
int x; int y = 3; // Calling an addition function // Parameetriteks on muutuja ja konstandi väärtus // The parameters are variable and constant x = sum(y, 5); // The call of a power off function // No parameters power_off();The execution of a C-language program is started from main function which makes it compulsory function.
Statements
If/Else statement
Conditional statements enable to execute or skip program code based on
based on logic and relational operations. Conditional statement uses a
keyword if. Example about using it:
// Statement is true and operation x = 5 will be executed // because 2 + 1 is higher than 2 if ((2 + 1) > 2) x = 5; // If x equals 5 and y equals 3 then the following code will be executed if ((x == 5) && (y == 3)) { // Random action y = 4; my_function(); }If statement can be longer and include code which will be executed in case the statement is false. For this, after if statement, else statement can be used. Example:
// Is x equal with 5 ? if (x == 5) { // Random action z = 3; } // If this is false then x might be equal with 6 else if (x == 6) { // Random action q = 3; } // If x was not 5 nor 6 ... else { // Random action y = 0; }
Switch statement
When required to compare operations and variables with many different values, it is reasonable to use comparison statement with switch keyword. Example about using this:
int y; // Switch statement for comparing y switch (y) { // is y equal to 1 ? case 1: // Random action function1(); break; // is y equal to 2 ? case 2: // Random action function2(); break; // All other cases default: // Random action functionX(); // break operation not needed, // because the comparison ends anyway }
Loops
Loops can be used for executing code several times.
while loop
Code marked with while keyword is executed until condition in brackets is true. Example:
int x = 0; // Loop will execute until x is smaller than 5 while (x < 5) { // x incrementation x++; }
for loop
for keyword loop is similar to while loop exept there
are described operation executed before the loop and operation executed
in the end of every loop cycle. Example:
int i, x = 0; // i is equal to 1 at the beginning of the loop. // Loop will be executed until i is smaller than 5. // i will be incremented in the end of every loop cycle. for (i = 0; i < 5; i++) { // x addition by 2 x += 2; } // here x value is 10
Halting loops
As and exception exit from while and for loops can be made with keyword break. To start the next loop cycle without executing the remaining code in loop, continue keyword can be used. For example:
int x = 0, y = 0; // Infinite loop because 1 is logic true while (1) { // Exit the the loop cycle if x becomes 100 if (x >= 100) break; // x incrementation to end loop at some time x++; // If x is 10 or less then the next cycle is started if (x <= 10) continue; // y incrementation y++; } // Here y value is 90
Text operations
Text operations are needed for microcontrollers foremost for displaying characters and text on LCD.
sprintf
sprintf function is similar to ordinary printf
function commonly used in C-language. The difference is that the result
of this function is loaded into variable not standard output.
return = sprintf(variable, parameter_text, parameters);
Example:
Example:
return = sprintf(variable, parameter_text, parameters);
Example:
int r = sprintf(buffer, "%d pluss %d on %d", a, b, a+b);It will load formated text into variable which is given from the function second to n parameter. sprintf will simplify composing more sophisticated statements. Easier is to use variables in text that will be replaced by values. Function returns the length of text loaded into variable. In case of error occurrence, negative value is returned.
Example:
sprintf(x, "%d. is first", 1); // the same result can be achieved also: x = "1. is first"; sprintf(x, "%s is %d years old", "Juku", 10); // the same result can be achieved also: x = "Juku is 10 years old";%s and %d are in this case parameters that will be repalaced accordingly by variable values which are the last parameters to function. The number of parameters must be the same as variables. In the first example, the parameter was %d which was replaced by variable value 1. In the second example parameters were %s and %d which were replaced by variable values “Juku” and 10. It was strictly in this order because %s was waiting value in form of a text and %d value of a number. There are special variable descriptions for different data types:
Parameter | Description | Example |
---|---|---|
%c | Char | a |
%i or %d | Integer | 123 |
%f | Real number | 3,14 |
%s | Text | example |
%X | Hexadecimal number | 3F |
#include <stdio.h> int main () { char buffer [50]; int n, a=5, b=3; n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("\"%s\" is %d digits long\n",buffer,n); return 0; }
General utilities
Standard functions library (stdlib.h) includes functions to simplify different common operations and conversions.
Random function
Generating a random number is not so simple for AVR microcontroller.
At first the random number generator must be inputed with a number to be the basis of random number array generation. The array based on one number is always the same. To make the result more random, the function can be inputed with a values taken from free floating ADC.
Example:
http://www.cplusplus.com/reference/clibrary/
At first the random number generator must be inputed with a number to be the basis of random number array generation. The array based on one number is always the same. To make the result more random, the function can be inputed with a values taken from free floating ADC.
Example:
srand(100); rand();Example about generating a random number in range of 16:
#include <stdlib.h> int x; x=rand() % 16;The more in-depth english description about C-language functions is in:
http://www.cplusplus.com/reference/clibrary/
Online Logo is an educational programming language - Logo - образовательный язык программирования
Logo is an educational programming language - Logo - образовательный язык программирования
Logo is an educational programming language, designed in 1967 by Wally Feurzeig, Seymour Papert, and Cynthia Solomon. Logo is not an acronym: the name was coined by Feurzeig while he was at Bolt, Beranek and Newman, and derives from the Greek logos, meaning word or thought.
A general-purpose language, Logo is widely known for its use of turtle graphics.
https://www.calormen.com/jslogo/#
https://www.transum.org/software/Logo/
https://turtleacademy.com/
La nueva versión de LibreOffice.org incluye un interprete del lenguaje de programación educativo Logo.
http://librelogo.org/en/
Logo is an educational programming language, designed in 1967 by Wally Feurzeig, Seymour Papert, and Cynthia Solomon. Logo is not an acronym: the name was coined by Feurzeig while he was at Bolt, Beranek and Newman, and derives from the Greek logos, meaning word or thought.
A general-purpose language, Logo is widely known for its use of turtle graphics.
https://www.calormen.com/jslogo/#
https://www.transum.org/software/Logo/
https://turtleacademy.com/
La nueva versión de LibreOffice.org incluye un interprete del lenguaje de programación educativo Logo.
http://librelogo.org/en/
lunes, 4 de febrero de 2019
Compartiendo codigo Hola Mundo con codiva.io
Compartiendo codigo Hola Mundo con codiva.io
https://www.codiva.io/p/03754588-e187-4159-836c-0c0201ee91a9
Web Platforms To compile and run programming Languages Online - Compilers online - Compilers over Web - Веб-платформы Для компиляции и запуска языков программирования онлайн - Компиляторы онлайн - Компиляторы через Интернет
To compile and run programming Languages Online - Compilers online - Compilers over Web
Веб-платформы Для компиляции и запуска языков программирования онлайн - Компиляторы онлайн - Компиляторы через Интернет
Веб-платформы Для компиляции и запуска языков программирования онлайн - Компиляторы онлайн - Компиляторы через Интернет
https://codepad.co/compiler
https://ideone.com/
http://www.compileonline.com
http://www.compileonline.com/index.htm
https://www.jdoodle.com/c-online-compiler
https://tio.run
https://repl.it
https://www.learn-c.org/
https://www.codiva.io
Suscribirse a:
Entradas (Atom)