19
5/1/2016 1 Arduino Part Two Simple Digital Output digitalWrite(): Write a HIGH or a LOW value to a digital pin.

Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

1

Arduino

Part Two

Simple Digital Output• digitalWrite(): Write a HIGH or a LOW value to a digital pin.

Page 2: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

2

Simple Digital Outputvoid setup() {

// initialize digital pin 13 as an output.

pinMode(13, OUTPUT);

}

// the loop function runs over and over again forever

void loop() {

digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)

delay(1000); // wait for a second

digitalWrite(13, LOW); // turn the LED off by making the voltage LOW

delay(1000); // wait for a second

}

Simple Digital Input• digitalRead(): Reads the value from a specified digital pin, either

HIGH or LOW.

Page 3: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

3

Simple Digital Inputconst int buttonPin = 2; // the number of the pushbutton pin

const int ledPin = 13; // the number of the LED pin

// variables will change:

int buttonState = 0; // variable for reading the pushbutton status

void setup() {

// initialize the LED pin as an output:

pinMode(ledPin, OUTPUT);

// initialize the pushbutton pin as an input:

pinMode(buttonPin, INPUT);

}

Simple Digital Inputvoid loop() {

// read the state of the pushbutton value:

buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.

// if it is, the buttonState is HIGH:

if (buttonState == HIGH) {

// turn LED on:

digitalWrite(ledPin, HIGH);

} else {

// turn LED off:

digitalWrite(ledPin, LOW);

}

}

Page 4: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

4

Simple Analog Output• 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 on most pins is approximately

490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency

of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at

980 Hz.

• 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 - 13 and 44 - 46. Older Arduino boards with

an ATmega8 only support analogWrite() on pins 9, 10, and 11.

Simple Analog Output

Page 5: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

5

Simple Analog Output• analogWrite(): Write a HIGH or a LOW value to a digital pin.

Simple Analog Outputint ledPin = 9; // LED connected to digital pin 9

void setup() {

// nothing happens in setup

}

void loop() {

// fade in from min to max in increments of 5 points:

for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {

// sets the value (range from 0 to 255):

analogWrite(ledPin, fadeValue);

// wait for 30 milliseconds to see the dimming effect

delay(30);

}

Page 6: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

6

Simple Analog Output// fade out from max to min in increments of 5 points:

for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {

// sets the value (range from 0 to 255):

analogWrite(ledPin, fadeValue);

// wait for 30 milliseconds to see the dimming effect

delay(30);

}

}

Analog Input• 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 1023. 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 (0.0001 s) to read an analog input,

so the maximum reading rate is about 10,000 times a second.

Page 7: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

7

Analog Input

Analog Inputvoid setup() {

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

}

// the loop routine runs over and over again forever:

void loop() {

// read the input on analog pin 0:

int sensorValue = analogRead(A0);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):

float voltage = sensorValue * (5.0 / 1023.0);

// print out the value you read:

Serial.println(voltage);

}

Page 8: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

8

Serial Communication• The word serial means "one after the other.“ Information is passed

back & forth between the computer and Arduino by, essentially,

setting a pin high or low. Just like we used that technique to turn an

LED on and off, we can also send data. One side sets the pin and the

other reads it.

Serial Communication

Page 9: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

9

Serial Communication• The asynchronous serial protocol has a number of built-in rules -

mechanisms that help ensure robust and error-free data transfers.

These mechanisms, which we get for eschewing the external clock

signal, are:

• Data bits,

• Synchronization bits,

• Parity bits,

• and Baud rate.

• Through the variety of these signaling mechanisms, you’ll find that

there’s no one way to send data serially. The protocol is highly

configurable. The critical part is making sure that both devices on a

serial bus are configured to use the exact same protocols.

Serial Communication

Page 10: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

10

Serial CommunicationUsed for communication between the Arduino board and a computer or

other devices. All Arduino boards have at least one serial port (also

known as a UART or USART): Serial. It communicates on digital pins 0

(RX) and 1 (TX) as well as with the computer via USB. Thus, if you use

these functions, you cannot also use pins 0 and 1 for digital input or

output.

You can use the Arduino environment's built-in serial monitor to

communicate with an Arduino board. Click the serial monitor button in

the toolbar and select the same baud rate used in the call to begin().

Serial Communication/* Simple Serial ECHO script, Use a variable called byteRead to

temporarily store the data coming from the computer */

byte byteRead;

void setup() {

Serial.begin(9600);

}

void loop() {

/* check if data has been sent from the computer: */

if (Serial.available()) {

/* read the most recent byte */

byteRead = Serial.read();

/*ECHO the value that was read, back to the serial port. */

Serial.write(byteRead);

}}

Page 11: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

11

Serial Communicationif (Serial) peek()

available() print(), println()

availableForWrite() read(), readBytes(),

readBytesUntil()

begin() readString(), readStringUntil()

end() setTimeout()

find(), findUntil() write()

flush() serialEvent()

parseFloat(), parseInt()

Serial Communication• if (Serial): Indicates if the specified Serial port is ready.

• void setup() {

//Initialize serial and wait for port to open:

Serial.begin(9600);

while (!Serial) {

; // wait for serial port to connect. Needed for native USB

}

}

void loop() {

//proceed normally

}

Page 12: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

12

Serial Communication• begin(): Sets the data rate in bits per second (baud) for serial data

transmission. For communicating with the computer, use one ofthese rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800,38400, 57600, or 115200. You can, however, specify other rates - forexample, to communicate over pins 0 and 1 with a component thatrequires a particular baud rate.

void setup(){

Serial.begin(9600);

Serial1.begin(38400);

Serial2.begin(19200);

Serial3.begin(4800);}

void loop() {

Serial.println("Hello Computer");

Serial1.println("Hello Serial 1");

Serial2.println("Hello Serial 2");

Serial3.println("Hello Serial 3");}

Serial Communication• end(): Disables serial communication, allowing the RX and TX pins to

be used for general input and output. To re-enable serial

communication, call Serial.begin().

• flush(): Waits for the transmission of outgoing serial data to

complete. (Prior to Arduino 1.0, this instead removed any buffered

incoming serial data.)

• available(): Get the number of bytes (characters) available for

reading from the serial port. This is data that's already arrived and

stored in the serial receive buffer (which holds 64 bytes).

Page 13: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

13

Serial Communication• int incomingByte = 0; // for incoming serial data

void setup() {

Serial.begin(9600); // opens serial port, sets data rate to 9600

bps

}

void loop() {

// send data only when you receive data:

if (Serial.available() > 0) {

// read the incoming byte:

incomingByte = Serial.read();

// say what you got:

Serial.print("I received: ");

Serial.println(incomingByte, DEC);

}

}

Serial Communication• read(): Reads incoming serial data.

int incomingByte = 0; // for incoming serial datavoid setup() {

Serial.begin(9600); // opens serial port, sets data rate to 9600 bps}void loop() {

// send data only when you receive data:if (Serial.available() > 0) {

// read the incoming byte:incomingByte = Serial.read();// say what you got:Serial.print("I received: ");Serial.println(incomingByte, DEC); } }

• peek(): Returns the next byte (character) of incoming serial datawithout removing it from the internal serial buffer. That is,successive calls to peek() will return the same character, as will thenext call to read().

Page 14: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

14

Serial Communication• print(): Prints data to the serial port as human-readable ASCII text.

This command can take many forms. Numbers are printed using an

ASCII character for each digit. Floats are similarly printed as ASCII

digits, defaulting to two decimal places. Bytes are sent as a single

character. Characters and strings are sent as is. For example:.

• println(): Prints data to the serial port as human-readable ASCII text

followed by a carriage return character (ASCII 13, or '\r') and a

newline character (ASCII 10, or '\n').

Serial Communication• int x = 10; // variable

void setup() {

Serial.begin(9600); // open the serial port at 9600 bps:

}

void loop() {

// print it out in many formats:

Serial.print(x); // print as an ASCII-encoded decimal - same as "DEC"

Serial.print("\t"); // prints a tab

Serial.print(x, DEC); // print as an ASCII-encoded decimal

Serial.print("\t"); // prints a tab

Serial.print(x, HEX); // print as an ASCII-encoded hexadecimal

Serial.print("\t"); // prints a tab

Serial.print(x, OCT); // print as an ASCII-encoded octal

Serial.print("\t"); // prints a tab

Serial.println(x, BIN); // print as an ASCII-encoded binary

}

Page 15: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

15

Serial Communication• write(): Writes binary data to the serial port. This data is sent as a

byte or series of bytes; to send the characters representing the digits

of a number use the print() function instead.

void setup(){

Serial.begin(9600);

}

void loop(){

Serial.write(45); // send a byte with the value 45

int bytesSent = Serial.write(“hello”); //send the string “hello” and

return the length of the string.

}

Serial Communication• parseInt(): Looks for the next valid integer in the incoming serial

stream.

• parseFloat() Serial.parseFloat() returns the first valid floating point

number from the Serial buffer. Characters that are not digits (or the

minus sign) are skipped. parseFloat() is terminated by the first

character that is not a floating point number.

• Serial.readBytesUntil() returns the number of characters read into

the buffer. A 0 means no valid data was found.

• readString(): Serial.readString() reads characters from the serial

buffer into a string. The function terminates if it times out.

• readStringUntil(): readStringUntil() reads characters from the serial

buffer into a string. The function terminates if the terminator

character is detected or it times out

Page 16: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

16

Serial Communication• Serial.readBytes(): Serial.readBytes() reads characters from the

serial port into a buffer. The function terminates if the determined

length has been read, or it times out.

• Serial.readBytesUntil() reads characters from the serial buffer into

an array. The function terminates if the terminator character is

detected, the determined length has been read, or it times out.

• Serial.readBytesUntil() returns the number of characters read into

the buffer. A 0 means no valid data was found.

• readString(): Serial.readString() reads characters from the serial

buffer into a string. The function terminates if it times out.

• readStringUntil(): readStringUntil() reads characters from the serial

buffer into a string. The function terminates if the terminator

character is detected or it times out

Voltage Measurement• The Arduino analog input is limited to a 5 VDC input. If you wish to

measure higher voltages, you will need to resort to another

means. One way is to use a voltage divider.

• It is fundamentally a 5:1 voltage divider using a 30K and a 7.5K Ohm

resistor.

• Keep in mind, you are restricted to voltages that are less than 25

volts. More than that and you will exceed the voltage limit of your

Arduino input.

Page 17: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

17

Voltage Measurement

Voltage Measurementint analogInput = A1; // I used A1

float vout = 0.0;

float vin = 0.0;

float R1 = 30000.0; //30k

float R2 = 7500.0; //7500 ohm resistor, I tweaked this

int value = 0;

void setup()

{ pinMode(analogInput, INPUT);

Serial.begin(9600);

Serial.println("BASIC DC VOLTMETER");}

void loop()

{ // read the value at analog input

value = analogRead(analogInput);

vout = (value * 5.0) / 1024.0;

vin = vout / (R2/(R1+R2));

Serial.print("Voltage = ");

Serial.println(vin,2);

delay(500);}

Page 18: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

18

Current Measurement

Voltage Measurementconst int analogIn = A0;

int mVperAmp = 185; // use 100 for 20A Module and 66 for 30A

Module

int RawValue= 0;

int ACSoffset = 2500;

double Voltage = 0;

double Amps = 0;

void setup(){

Serial.begin(9600);

}

Page 19: Part Two - جامعة نزوى...Arduino2 Author Munaf Subject Arduino2 Keywords Arduino2 Created Date 5/1/2016 9:24:53 PM

5/1/2016

19

Voltage Measurementvoid loop(){

RawValue = analogRead(analogIn);

Voltage = (RawValue / 1024.0) * 5000; // Gets you mV

Amps = ((Voltage - ACSoffset) / mVperAmp);

Serial.print("Raw Value = " ); // shows pre-scaled value

Serial.print(RawValue);

Serial.print("\t mV = "); // shows the voltage measured

Serial.print(Voltage,3); // the '3' after voltage allows you to display 3

digits after decimal point

Serial.print("\t Amps = "); // shows the voltage measured

Serial.println(Amps,3); // the '3' after voltage allows you to display 3

digits after decimal point

delay(2500);

}