Solti Imre: Arduino eljárásgyűjtemény - PDF

Description
Solti Imre: Arduino eljárásgyűjtemény Ajánlás: Ez egy aurdino és egyéb szabadon másolható oldalakról összeollózott leírás Tudom, hogy semmi új nincs benne az aurdino.cc-hez képest, de egyrészt belevettem

Please download to get full document.

View again

of 197
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Information
Category:

Sales

Publish on:

Views: 14 | Pages: 197

Extension: PDF | Download: 0

Share
Transcript
Solti Imre: Arduino eljárásgyűjtemény Ajánlás: Ez egy aurdino és egyéb szabadon másolható oldalakról összeollózott leírás Tudom, hogy semmi új nincs benne az aurdino.cc-hez képest, de egyrészt belevettem pár library leírását, ami nem szerepelt az eredetiben, másrészt ez így egyben van, nem kell tokenenként átnyálazni...:-) Publikálásra került: november (TavIR-AVR; Arduino Language Reference Arduino programs can be divided in three main parts: structure, values (variables and constants), and functions. Structure setup() loop() Control Structures if if...else for switch case while do... while break continue return goto Further Syntax ; // /* */ #define #include (semicolon) (curly braces) (single line comment) (multi-line comment) Arithmetic Operators = + * / % (assignment operator) (addition) (subtraction) (multiplication) (division) (modulo) Comparison Operators ==!= = = (equal to) (not equal to) (less than) (greater than) (less than or equal to) (greaterthanor equal to) 1 Boolean Operators && (and) (or)! (not) Bitwise Operators & ^ ~ (bitwise and) (bitwise or) (bitwise xor) (bitwise not) (bitshift left) (bitshift right) Compound Operators ++ += -= *= /= &= = (increment) (decrement) (compound addition) (compound subtraction) (compound multiplication) (compound division) (compound bitwise and) (compound bitwise or) Variables Constants HIGH LOW INPUT OUTPUT INPUT_PULLUP true false integer constants floating point constants Data Types void boolean char unsigned char byte int unsigned int word long unsigned long float 2 double string - char array String - object array Conversion char() byte() int() word() long() float() Variable Scope & Qualifiers variable scope static volatile const Utilities sizeof() Functions Digital I/O pinmode() digitalwrite() digitalread() Analog I/O analogreference() analogread() analogwrite() - PWM Advanced I/O tone() notone() shiftout() shiftin() pulsein() Time millis() micros() 3 delay() delaymicroseconds() Math min() max() abs() constrain() map() pow() sqrt() Trigonometry sin() cos() tan() Random Numbers randomseed() random() Bits and Bytes lowbyte() highbyte() bitread() bitwrite() bitset() bitclear() bit() Interrupts attachinterrupt() detachinterrupt() interrupts() nointerrupts() Communication Serial Stream Leonardo Specific Keyboard Mouse 4 abs(x) Computes the absolute value of a number. Parameters: x: the number x: if x is greater than or equal to 0. -x: if x is less than 0. Warning Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results. abs(a++); a++; abs(a); // avoid this - yields incorrect results // use this instead // keep other math outside the function analogread() Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and This yields a resolution between readings of: 5 volts / 1024 units or,.0049 volts (4.9 mv) per unit. The input range and resolution can be changed using analogreference(). It takes about 100 microseconds ( s) to read an analog input, so the maximum reading rate is about 10,000 times a second. analogread(pin) Parameters: pin: the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega) int (0 to 1023) Note If the analog input pin is not connected to anything, the value returned by analogread() will fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your hand is to the board, etc.). int analogpin = 3; int val = 0; void setup() Serial.begin(9600); // potentiometer wiper (middle terminal) connected to analog pin 3 // outside leads to ground and +5V // variable to store the value read // setup serial 5 void loop() val = analogread(analogpin); Serial.println(val); // read the input pin // debug value analogreference(type) Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are: * DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards) * INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega) * INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only) * INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only) * EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference. Parameters type: which type of reference to use (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, or EXTERNAL). Returns None. Note After changing the analog reference, the first few readings from analogread() may not be accurate. Warning Don't use anything less than 0V or more than 5V for external reference voltage on the AREF pin! If you're using an external reference on the AREF pin, you must set the analog reference to EXTERNAL before calling analogread(). Otherwise, you will short together the active reference voltage (internally generated) and the AREF pin, possibly damaging the microcontroller on your Arduino board. Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you to switch between external and internal reference voltages. Note that the resistor will alter the voltage that gets used as the reference because there is an internal 32K resistor on the AREF pin. The two act as a voltage divider, so, for example, 2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin. analogwrite() Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogwrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogwrite() (or a call to digitalread() or digitalwrite() on the same pin). The frequency of the PWM signal is approximately 490 Hz. 6 On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 through 13. Older Arduino boards with an ATmega8 only support analogwrite() on pins 9, 10, and 11. You do not need to call pinmode() to set the pin as an output before calling analogwrite(). The analogwrite function has nothing whatsoever to do with the analog pins or the analogread function. analogwrite(pin, value) Parameters: pin: the pin to write to. value: the duty cycle: between 0 (always off) and 255 (always on). nothing Notes and Known Issues The PWM outputs generated on pins 5 and 6 will have higher-than-expected duty cycles. This is because of interactions with the millis() and delay() functions, which share the same internal timer used to generate those PWM outputs. This will be noticed mostly on low duty-cycle settings (e.g 0 10) and may result in a value of 0 not fully turning off the output on pins 5 and 6. Sets the output to the LED proportional to the value read from the potentiometer. int ledpin = 9; int analogpin = 3; int val = 0; // LED connected to digital pin 9 // potentiometer connected to analog pin 3 // variable to store the read value void setup() pinmode(ledpin, OUTPUT); // sets the pin as output void loop() val = analogread(analogpin); analogwrite(ledpin, val / 4); // read the input pin // analogread values go from 0 to 1023, analogwrite values from 0 to 255 Addition, Subtraction, Multiplication, & Division These operators return the sum, difference, product, or quotient (respectively) of the two operands. The operation is conducted using the data type of the operands, so, for example, 9 / 4 gives 2 since 9 and 4 are ints. This also means that the operation can overflow if the result is larger than that which can be stored in the data type (e.g. adding 1 to an int with the value 32,767 gives -32,768). If the operands are of different types, the larger type is used for the calculation. 7 If one of the numbers (operands) are of the type float or of type double, floating point math will be used for the calculation. s y = y + 3; x = x - 7; i = j * 6; r = r / 5; Syntax result = value1 + value2; result = value1 - value2; result = value1 * value2; result = value1 / value2; Parameters: value1: any variable or constant value2: any variable or constant Programming Tips: * Know that integer constants default to int, so some constant calculations may overflow (e.g. 60 * 1000 will yield a negative result). * Choose variable sizes that are large enough to hold the largest results from your calculations * Know at what point your variable will roll over and also what happens in the other direction e.g. (0-1) OR ( ) * For math that requires fractions, use float variables, but be aware of their drawbacks: large size, slow computation speeds * Use the cast operator e.g. (int)myfloat to convert one variable type to another on the fly. Arrays An array is a collection of variables that are accessed with an index number. Arrays in the C programming language, on which Arduino is based, can be complicated, but using simple arrays is relatively straightforward. Creating (Declaring) an Array All of the methods below are valid ways to create (declare) an array. int myints[6]; int mypins[] = 2, 4, 8, 3, 6; int mysensvals[6] = 2, 4, -8, 3, 2; char message[6] = hello ; You can declare an array without initializing it as in myints. In mypins we declare an array without explicitly choosing a size. The compiler counts the elements 8 and creates an array of the appropriate size. Finally you can both initialize and size your array, as in mysensvals. Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character. Accessing an Array Arrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence mysensvals[0] == 2, mysensvals[1] == 4, and so forth. It also means that in an array with ten elements, index nine is the last element. Hence: int myarray[10]=9,3,2,4,3,2,7,8,9,11; // myarray[9] contains 11 // myarray[10] is invalid and contains random information (other memory address) For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size - 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down. Unlike BASIC or JAVA, the C compiler does no checking to see if array access is within legal bounds of the array size that you have declared. To assign a value to an array: mysensvals[0] = 10; To retrieve a value from an array: x = mysensvals[4]; Arrays and FOR Loops Arrays are often manipulated inside for loops, where the loop counter is used as the index for each array element. For example, to print the elements of an array over the serial port, you could do something like this: int i; for (i = 0; i 5; i = i + 1) Serial.println(myPins[i]); = assignment operator (single equal sign) Stores the value to the right of the equal sign in the variable to the left of the equal sign. 9 The single equal sign in the C programming language is called the assignment operator. It has a different meaning than in algebra class where it indicated an equation or equality. The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign. int sensval; senval = analogread(0); // declare an integer variable named sensval // store the (digitized) input voltage at analog pin 0 in SensVal Programming Tips The variable on the left side of the assignment operator ( = sign ) needs to be able to hold the value stored in it. If it is not large enough to hold a value, the value stored in the variable will be incorrect. Don't confuse the assignment operator [ = ] (single equal sign) with the comparison operator [ == ] (double equal signs), which evaluates whether two expressions are equal. attachinterrupt() Specifies a function to call when an external interrupt occurs. Replaces any previous function that was attached to the interrupt. Most Arduino boards have two external interrupts: numbers 0 (on digital pin 2) and 1 (on digital pin 3). The Arduino Mega has an additional four: numbers 2 (pin 21), 3 (pin 20), 4 (pin 19), and 5 (pin 18). attachinterrupt(interrupt, function, mode) Parameters: interrupt: the number of the interrupt (int) function: the function to call when the interrupt occurs; this function must take no parameters and return nothing. This function is sometimes referred to as an interrupt service routine. mode defines when the interrupt should be triggered. Four contstants are predefined as valid values: * LOW to trigger the interrupt whenever the pin is low, * CHANGE to trigger the interrupt whenever the pin changes value * RISING to trigger when the pin goes from low to high, * FALLING for when the pin goes from high to low. none Note: Inside the attached function, delay() won't work and the value returned by millis() will not increment. Serial data received while in the function may be lost. You should declare as volatile any variables that you modify within the attached function. Interrupts using Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. A good task for using an interrupt might be reading a rotary encoder, monitoring user input. 10 If you wanted to insure that a program always caught the pulses from a rotary encoder, never missing a pulse, it would make it very tricky to write a program to do anything else, because the program would need to constantly poll the sensor lines for the encoder, in order to catch pulses when they occurred. Other sensors have a similar interface dynamic too, such as trying to read a sound sensor that is trying to catch a click, or an infrared slot sensor (photo-interrupter) trying to catch a coin drop. In all of these situations, using an interrupt can free the microcontroller to get some other work done while not missing the doorbell. int pin = 13; volatile int state = LOW; void setup() pinmode(pin, OUTPUT); attachinterrupt(0, blink, CHANGE); void loop() digitalwrite(pin, state); void blink() state =!state; begin() Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or You can, however, specify other rates - for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate. Serial.begin(speed) Arduino Mega only: Serial1.begin(speed) Serial2.begin(speed) Serial3.begin(speed) Parameters: speed: in bits per second (baud) long nothing void setup() Serial.begin(9600); // opens serial port, sets data rate to 9600 bps 11 void loop() Arduino Mega // Arduino Mega using all four of its Serial ports // (Serial, Serial1, Serial2, Serial3), // with different baud rates: void setup() Serial.begin(9600); Serial1.begin(38400); Serial2.begin(19200); Serial3.begin(4800); Serial.println( Hello Computer ); Serial1.println( Hello Serial 1 ); Serial2.println( Hello Serial 2 ); Serial3.println( Hello Serial 3 ); void loop() bitclear() Clears (writes a 0 to) a bit of a numeric variable. Parameters bitclear(x, n) x: the numeric variable whose bit to clear n: which bit to clear, starting at 0 for the least-significant (rightmost) bit none bit() Computes the value of the specified bit (bit 0 is 1, bit 1 is 2, bit 2 is 4, etc.). Parameters bit(n) n: the bit whose value to compute the value of the bit bitread() Description: Parameters: Reads a bit of a number. bitread(x, n) x: the number from which to read n: which bit to read, starting at 0 for the least-significant (rightmost) bit the value of the bit (0 or 1). 12 bitset() Sets (writes a 1 to) a bit of a numeric variable. Parameters: bitset(x, n) x: the numeric variable whose bit to set n: which bit to set, starting at 0 for the least-significant (rightmost) bit none bitshift left ( ), bitshift right ( ) From The Bitmath Tutorial in The Playground There are two bit shift operators in C++: the left shift operator and the right shift operator . These operators cause the bits in the left operand to be shifted left or right by the number of positions specified by the right operand. variable number_of_bits variable number_of_bits Parameters: variable - (byte, int, long) number_of_bits integer = 32 int a = 5; int b = a 3; int c = b 3; // binary: // binary: , or 40 in decimal // binary: , or back to 5 like we started with When you shift a value x by y bits (x y), the leftmost y bits in x are lost, literally shifted out of existence: int a = 5; int b = a 14; // binary: // binary: the first 1 in 101 was discarded If you are certain that none of the ones in a value are being shifted into oblivion, a simple way to think of the left-shift operator is that it multiplies the left operand by 2 raised to the right operand power. For example, to generate powers of 2, the following expressions can be employed: 1 0 == 1 1 1 == 2 1 2 == 4 1 3 == 8 == 9 == 10 == When you shift x right by y bits (x y), and the highest bit in x is a 1, the behavior depends on the 13 exact data type of x. If x is of type int, the highest bit is the sign bit, determining whether x is negative or not, as we have discussed above. In that case, the sign bit is copied into lower bits, for esoteric historical reasons: int x = -16; int y = x 3; // binary: // binary: This behavior, called sign extension, is often not the behavior you want. Instead, you may wish zeros to be shifted in from the left. It turns out that the right shift rules are different for unsigned int expressions, so you can use a typecast to suppress ones being copied from the left: int x = -16; int y = (unsigned int)x 3; // binary: // binary: If you are careful to avoid sign extension, you can use the right-shift operator as a way to divide by powers of 2. For int x = 1000; int y = x 3; // integer division of 1000 by 8, causing y = 125. Bitwise AND (&), Bitwise OR ( ), Bitwise XOR (^) The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming problems. Much of the material below is from an excellent tutorial on bitwise math wihch may be found here. Bitwise AND (&) The bitwise AND operator in C++ is a single ampersand, &, used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0. Another way of expressing this is: operand1 operand2 (operand1 & operand2) - returned result In Arduino, the type int is a 16-bit value, so using & between two int expressions causes 16 simultaneous AND operations to occur. In a code fragment like: int a = 92; // in binary: int b = 101; // in binary: int c = a & b; // result: , or 68 in decimal. Each of the 16 bits in a and b are processed by using the bitwise AND, and all 16 resulting bits are stored in c, resulting in the value in binary, which is 68 in decimal. One of the most common uses of bitwise AND is to select a particular bit (or bits) from an integer value, often called masking. See below for an example 14 Bitwise OR ( ) The bitwise OR operator
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks