Arduino aref пин: измеряем точное напряжение

Digital Pins

The pins on the Arduino can be configured as either inputs or outputs. This document explains the functioning of the pins in those modes. While the title of this document refers to digital pins, it is important to note that vast majority of Arduino (Atmega) analog pins, may be configured, and used, in exactly the same manner as digital pins.

Properties of Pins Configured as INPUT

This also means however, that pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires connected to them that are not connected to other circuits, will report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin.

Pullup Resistors with pins configured as INPUT

Often it is useful to steer an input pin to a known state if no input is present. This can be done by adding a pullup resistor (to +5V), or a pulldown resistor (resistor to ground) on the input. A 10K resistor is a good value for a pullup or pulldown resistor.

Properties of Pins Configured as INPUT_PULLUP

There are 20K pullup resistors built into the Atmega chip that can be accessed from software. These built-in pullup resistors are accessed by setting the pinMode() as INPUT_PULLUP. This effectively inverts the behavior of the INPUT mode, where HIGH means the sensor is off, and LOW means the sensor is on.

The value of this pullup depends on the microcontroller used. On most AVR-based boards, the value is guaranteed to be between 20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For the exact value, consult the datasheet of the microcontroller on your board.

When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be connected to ground. In the case of a simple switch, this causes the pin to read HIGH when the switch is open, and LOW when the switch is pressed.

The pullup resistors provide enough current to dimly light an LED connected to a pin that has been configured as an input. If LEDs in a project seem to be working, but very dimly, this is likely what is going on.

The pullup resistors are controlled by the same registers (internal chip memory locations) that control whether a pin is HIGH or LOW. Consequently, a pin that is configured to have pullup resistors turned on when the pin is an INPUT, will have the pin configured as HIGH if the pin is then switched to an OUTPUT with pinMode(). This works in the other direction as well, and an output pin that is left in a HIGH state will have the pullup resistors set if switched to an input with pinMode().

Prior to Arduino 1.0.1, it was possible to configure the internal pull-ups in the following manner:

pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

NOTE: Digital pin 13 is harder to use as a digital input than the other digital pins because it has an LED and resistor attached to it that’s soldered to the board on most boards. If you enable its internal 20k pull-up resistor, it will hang at around 1.7V instead of the expected 5V because the onboard LED and series resistor pull the voltage level down, meaning it always returns LOW. If you must use pin 13 as a digital input, set its pinMode() to INPUT and use an external pull down resistor.

Properties of Pins Configured as OUTPUT

Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. Atmega pins can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits. This is enough current to brightly light up an LED (don’t forget the series resistor), or run many sensors, for example, but not enough current to run most relays, solenoids, or motors.

Short circuits on Arduino pins, or attempting to run high current devices from them, can damage or destroy the output transistors in the pin, or damage the entire Atmega chip. Often this will result in a «dead» pin in the microcontroller but the remaining chip will still function adequately. For this reason it is a good idea to connect OUTPUT pins to other devices with 470Ω or 1k resistors, unless maximum current draw from the pins is required for a particular application.

Step 3: Switch and LED and Using Pin Bank D.

Bank D controls pins 0 — 7, but pins 0 and 1 are used for serial communication. Most Arduino enthusiasts do not try to use these pins for anything else. Things can get weird if you mess with these pins. So for safety it is best to preserve the values of bits 0 and 1 in the DDRD and PORTD registers. This requires the use of logical AND and OR commands.

Each register is 8 bits numbered 0 to 7 from right to left. Bit 0 is 2^0, bit 1 is 2^1, etc.

A logical OR compares two bytes bit for bit and the result is 1 if either or the bytes is 1, if not the result is 0.

The vertical line (|) is the symbol for a logical OR.

Here is a truth table for a logical OR:

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
So if we OR        11001100
Against            00111100
The result will be 11111100

A logical AND compares two bytes bit for bit and the result is 1 only if both bits are 1.The ampersand (&) is the symbol for a logical AND.

Here is a truth table for a logical AND:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
So if we AND       11001100
Against            00111100 
The result will be 00001100

In order to preserve a bit you can OR it against 0 or AND it against 1.

Follow along with the documentation in the program to see how this works.

Build the circuit shown in the diagram, you will need:

  • Arduino
  • Breadboard
  • LED
  • Resistor, 330-560 Ohm
  • Jumper wires

Copy this program into the Arduino IDE and upload it to your Arduino:

/*********************************************************
 * Demonstration using bank D pins 0 - 7 and preserving the 
 * values of pins 0 and 1 in the DDRD and PORTD registers.
 *
 * The anode of an LED is connected to pin 7 with 
 * a resistor in series connected to ground. 
 *
 * A pushbutton switch is connected to pin 2 and ground
 * and uses the internal pull-up resistor.
 *
 * The LED lights when the button is pressed.
 *
 *********************************************************/

/**********************************************
 * setup() function
 **********************************************/
void setup()
{
  // Set pin 2 to input and pin 7 to output
  // while maintaining the state of pins 0 and 1.
  // We don't care what happens to 3 - 6.

  DDRD = DDRD | B10000000;

  // The "|" means a logical OR.
  // We now know that bit 7 is high.
  // And we know bits 0 and 1 are preserved.
  // But we still are not sure of bit two. 

  DDRD = DDRD & B10000011;

  // We do a logical AND, now we know the status of all the bits.

  // A logical OR against zero or a logical AND against one
  // will not change the status of a bit.

  // This preserved the status of bits 7, 1, and 0.
  // Since bit 2 was ANDed against 0 we know that it is now clear.
  // The DDRD register is now where we want it.
 
  // Now we need to get the PORTD register set the way we want it.

  PORTD = PORTD & B00000011;

  // Bits 0 and 1 are preserved, all others are off.

  PORTD = PORTD | B00000100;

  // Bits 7 is off, the initial state of the LED.
  // Bit 2 is on, because pin 2 is an input turning it's bit
  // on in PORTD turns on the internal pull-up resistor.
}

/**********************************************
 * loop() function
 **********************************************/
void loop()
{
  // Read the PIND register.

  int button = PIND;

  // you now have the values of all eight pins in the PIND register
  // contained in a variable. The only pin we care about is pin 2.
  // So we do a logical AND on the button variable to isolate the
  // bit we want.
       
  button = button & B00000100;

  // Because of the internal pull-up resistor the pin will be high
  // if the button is not pressed, and low if it is.
  // So button will return either 2^2 (4) or zero if it is pressed.

  PORTD = PORTD & B00000111;

  // Turn LED off, and preserve bits 0 - 2.
 
  if(button == 0) 
  {
    PORTD = PORTD | B10000000;
  // turn LED on, and preserve bits 0 - 2.
  }
}

The digitalWrite() command will slow a program down a lot in a loop, but the pinMode() command is normally used only in the setup() function and run once. the program above will run just as well if you use a more standard setup() function, like this:

setup()
{
  pinMode(7, OUTPUT);
  pinMode(2, INPUT_PULLUP;
}

While using the DDRD register is not necessary it is nice to understand how it and the logical operations work.

Analog Read Serial

This example shows you how to read analog input from the physical world using a potentiometer. A potentiometer is a simple mechanical device that provides a varying amount of resistance when its shaft is turned. By passing voltage through a potentiometer and into an analog input on your board, it is possible to measure the amount of resistance produced by a potentiometer (or pot for short) as an analog value. In this example you will monitor the state of your potentiometer after establishing serial communication between your Arduino or Genuino and your computer running the Arduino Software (IDE).

Circuit

Connect the three wires from the potentiometer to your board. The first goes from one of the outer pins of the potentiometerto ground . The second goes from the other outer pin of the potentiometer to 5 volts. The third goes from the middle pin of the potentiometer to the analog pin A0.

By turning the shaft of the potentiometer, you change the amount of resistance on either side of the wiper, which is connected to the center pin of the potentiometer. This changes the voltage at the center pin. When the resistance between the center and the side connected to 5 volts is close to zero (and the resistance on the other side is close to 10k ohm), the voltage at the center pin nears 5 volts. When the resistances are reversed, the voltage at the center pin nears 0 volts, or ground. This voltage is the analog voltage that you’re reading as an input.

The Arduino and Genuino boards have a circuit inside called an analog-to-digital converter or ADC that reads this changing voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in one direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned all the way in the opposite direction, there are 5 volts going to the pin and the input value is 1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin.

Code

In the sketch below, the only thing that you do in the setup function is to begin serial communications, at 9600 bits of data per second, between your board and your computer with the command:

Next, in the main loop of your code, you need to establish a variable to store the resistance value (which will be between 0 and 1023, perfect for an datatype) coming in from your potentiometer:

Finally, you need to print this information to your serial monitor window. You can do this with the command Serial.println() in your last line of code:

Now, when you open your Serial Monitor in the Arduino Software (IDE) (by clicking the icon that looks like a lens, on the right, in the green top bar or using the keyboard shortcut Ctrl+Shift+M), you should see a steady stream of numbers ranging from 0-1023, correlating to the position of the pot. As you turn your potentiometer, these numbers will respond almost instantly.

See Also:

  • setup()
  • loop()
  • analogRead()
  • int
  • serial

  • BareMinimum — The bare minimum of code needed to start an Arduino sketch.
  • Blink — Turn an LED on and off.
  • DigitalReadSerial — Read a switch, print the state out to the Arduino Serial Monitor.
  • Fade — Demonstrates the use of analog output to fade an LED.

Last revision 2015/07/28 by SM

Digital Read Serial

This example shows you how to monitor the state of a switch by establishing serial communication between your Arduino or Genuino and your computer over USB.

Circuit

Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10k ohm) to ground. The other leg of the button connects to the 5 volt supply.

Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and reads as LOW, or 0. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that the pin reads as HIGH, or 1.

If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the input is «floating» — that is, it doesn’t have a solid connection to voltage or ground, and it will randomly return either HIGH or LOW. That’s why you need a pull-down resistor in the circuit.

Code

In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your board and your computer with the line:

Next, initialize digital pin 2, the pin that will read the output from your button, as an input:

Now that your setup has been completed, move into the main loop of your code. When your button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the input pin will be connected to ground through the 10k ohm resistor. This is a digital input, meaning that the switch can only be in either an on state (seen by your Arduino as a «1», or HIGH) or an off state (seen by your Arduino as a «0», or LOW), with nothing in between.

The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch. Since the information coming in from the switch will be either a «1» or a «0», you can use an datatype. Call this variable , and set it to equal whatever is being read on digital pin 2. You can accomplish all this with just one line of code:

Once the board has read the input, make it print this information back to the computer as a decimal value. You can do this with the command Serial.println() in our last line of code:

Now, when you open your Serial Monitor in the Arduino Software (IDE), you will see a stream of «0»s if your switch is open, or «1»s if your switch is closed.

See Also:

  • setup()
  • loop()
  • pinMode()
  • digitalRead()
  • delay()
  • int
  • serial
  • DigitalPins

  • AnalogReadSerial — Read a potentiometer, print its state out to the Arduino Serial Monitor.
  • BareMinimum — The bare minimum of code needed to start an Arduino sketch.
  • Blink — Turn an LED on and off.
  • Fade — Demonstrates the use of analog output to fade an LED.
  • ReadAnalogVoltage — Reads an analog input and prints the voltage to the serial monitor.

Last revision 2015/07/29 by SM

Bit-banging Pulse Width Modulation

You can «manually» implement PWM on any pin by repeatedly turning the pin on and off for the desired times. e.g.

void setup(){
  pinMode(13, OUTPUT);}void loop(){
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 — 100);}

This technique has the advantage that it can use any digital output pin. In addition, you have full control the duty cycle and frequency. One major disadvantage is that any interrupts will affect the timing, which can cause considerable jitter unless you disable interrupts. A second disadvantage is you can’t leave the output running while the processor does something else. Finally, it’s difficult to determine the appropriate constants for a particular duty cycle and frequency unless you either carefully count cycles, or tweak the values while watching an oscilloscope.

Устройство и принцип работы потенциометра

Переменный резистор (потенциометр) поворотом ручки изменяет сопротивление в электрической цепи от нуля до номинального сопротивления в 10 кОм. Потенциометр сделан состоит из токопроводящей поверхности — плоского постоянного резистора с двумя контактами и скользящего по поверхности токосъемника. Потенциометр предназначен для точной регулировки напряжения в электрической цепи.


Со средней ножки потенциометра снимают значение напряжения

Переменный резистор имеет прочную токопроводящую поверхность, поскольку положение настройки потенциометра изменяется постоянно. Переменный резистор служит для регулярного применения, например, для изменения уровня громкости. Часто применяется в различных проектах Ардуино для начинающих.

Подстроечный резистор служит для точной настройки работы электронных устройств. Положение настройки, как правило, в течении всего срока эксплуатации устройства не изменяется. Поэтому, перемещение скользящего контакта производится с помощью отвертки, а прочность проводящего слоя не имеет большого значения.

Analog Write with 12 LEDs on an Arduino Mega

This example fades 12 LEDs up and the down, one by one, on an Arduino or Genuino Mega board, taking advantage of the increased number of PWM enabled digital pins of this board.

Circuit

Connect the longer, positive legs (anodes) of 12 LEDs to digital pins 2-13 through 220 ohm current limiting resistors. Connect the shorter, negative legs (cathodes) to ground.

Code

In the function of the code below, a loop is used to assign digital pins 2-13 of the Mega as outputs.

Next, in the function of the program below, a trio of nested loops are used.

The first of these loops,

moves through each of the LEDS one by one, from the lowest pin to the highest. Before this loop is allowed to move from one pin to the next, two things must be accomplished. First, you brighten the individual LED through these lines of code:

With each pass through the loop above, the variable brightness increases by one point, and that value is written to the pin currently selected to the main loop. One that pin reaches the maximum PWM value (255), the following loop kicks in:

This loop subtracts a point from the brightness variable, dimming the LED back down to 0. Once zero is reached, the main loop kicks in, and the program moves on to the next LED pin, repeating all the steps mentioned above.

/*
  Mega analogWrite() test
  This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
  This sketch was written for the Arduino Mega, and will not work on other boards.
  The circuit:
  — LEDs attached from pins 2 through 13 to ground.
  created 8 Feb 2009
  by Tom Igoe
  This example code is in the public domain.
  http://www.arduino.cc/en/Tutorial/AnalogWriteMega
*/// These constants won’t change. They’re used to give names to the pins used:
const int lowestPin = 2;
const int highestPin = 13;void setup() {
  // set pins 2 through 13 as outputs:
  for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }}void loop() {
  // iterate over the pins:
  for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
    // fade the LED on thisPin from off to brightest:
    for (int brightness = ; brightness < 255; brightness++) {
      analogWrite(thisPin, brightness);
      delay(2);
    }
    // fade the LED on thisPin from brightest to off:
    for (int brightness = 255; brightness >= ; brightness—) {
      analogWrite(thisPin, brightness);
      delay(2);
    }
    // pause between LEDs:
    delay(100);
  }}

See Also:

  • for()
  • analogWrite()
  • delay()

  • AnalogInOutSerial — Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
  • AnalogInput — Use a potentiometer to control the blinking of an LED.
  • Calibration — Define a maximum and minimum for expected analog sensor values.
  • Fading — Use an analog output (PWM pin) to fade an LED.
  • Smoothing — Smooth multiple readings of an analog input.

Last revision 2015/07/28 by SM

Чем отличается аналоговый сигнал от цифрового

Аналоговый сигнал непрерывно изменяется во времени. Вся информация в природе аналоговая — волны на воде, колебание струны и т.д. Изначально человек записывал информацию (звуки, изображения, видео) с помощью аналоговых устройств. Но аналоговые сигналы чувствительны к воздействию шумов и помех.

Цифровой сигнал передается в виде единиц и нулей, для компьютеров и цифровой техники это проще реализовать (есть сигнал или нет сигнала). Для оперативной памяти в компьютерах используют конденсаторы, один заряженный конденсатор — 1 бит. На флеш-памяти используют транзисторы с плавающим затвором.

С появлением компьютеров аналоговые сигналы стали переводить в цифру, поскольку аналоговый сигнал подвержен искажениям и затуханию при передаче или записи. Наглядно продемонстрировать разницу между аналоговым и цифровым сигналом поможет картинка, где изображен процесс квантования — разбиение непрерывной величины на конечное число интервалов (перевод аналогового сигнала в цифру).


Квантование — разбиение непрерывной величины на интервалы

Аналоговые и цифровые выходы на Ардуино

Если вы хотите регулировать выходное напряжение, то следует использовать пины, помеченные символом «~». Для Arduino Uno — это 3, 5, 6, 9, 10, 11. С помощью аналоговых портов можно выдавать любое напряжение 0 до 5 Вольт, а цифровые выходы можно только включать и выключать. Аналоговые порты используют ШИМ (широтно-импульсную модуляцию), по английски PWM (pulse-width modulation), с помощью которой имитируется аналоговый сигнал.


Аналоговые выходы на плате Ардуино имеют, отметку тильда «~»

Чтобы понять разницу между цифровым и аналоговым сигналом, соберите на макетной плате схему из светодиода и резистора, как на первом занятии — Подключение светодиода. Но в этот раз подключите светодиод к аналоговому выходу ~9. Откройте скетч для мигания светодиодом из первого занятия и измените в нем порт выхода с Pin13 на Pin9. Загрузите скетч в плату Arduino NANO или UNO.


На Arduino аналоговый выход будет работать, как цифровой

9 порт может работать, как цифровой выход. Но если функцию digitalWrite изменить на analogWrite, то вместо значения HIGH (1) и LOW (0) можно поставить любое значение от 0 до 255. Именно в этом интервале можно менять напряжение на аналоговых выходах. Загрузите программу для плавного включения и затухания светодиода. Подробное описание работы данной программы даны ниже в пояснении к коду.

Скетч. Аналоговый сигнал Ардуино и светодиод

int svet = 0; // начальная яркость свечения светодиода
int fade = 5; // шаг изменения яркости свечения светодиода

void setup() {
  pinMode(9, OUTPUT); // используем Pin9 для операции вывода
}

void loop() {
 // устанавливаем яркость светодиода на Pin9
  analogWrite(9, svet);

// изменяем яркость, прибавляя заданную величину fade в каждом цикле
  svet = svet + fade;

// меняем порядок затухания при минимальной и максимальной яркости
  if (svet == 0 || svet == 255) {
    fade = -fade;
  }

  delay(20); // устанавливаем паузу для эффекта
}

How to use digitalRead in Arduino ?

  • So, you can see in the above figure that we have RXD at 0 which is sued for Serial receiving and then we have TXD at 1 used for Serial writing.
  • So, these pins from 0 to 13 are all digital and after these digital Pins we have GND.
  • Now I hope you have got the idea of digital Pins.
  • Next thing is How to use these digital Pins, normally we connect different digital sensors with these digital Pins.
  • For example, I have a digital Sensor named as Vibration Sensor. This sensor gives HIGH when it feels vibrations and gives LOW in normal condition.
  • So, I am gonna connect the Signal Pin of this Sensor with any digital Pin of Arduino.
  • Now, coming towards digitalRead command, this digitalRead command is used in Arduino for reading the status of digital Pins on Arduino.
  • So, when we want to read whether the digital Pin of Arduino is HIGH or LOW, we use this digitalRead command.
  • The syntax of digitalRead is as follows:

int Reading = digitalRead (int PinNumber);

  • digitalRead command takes one input which is the value of the Pin, like if you wanna read the digital status of Pin # 8 then you have to enter 8 in the small brackets of digitalRead.
  • digital Read returns Boolean data which is either HIGH or LOW and it is saved in the integer variable which I have named Reading in the above syntax. We have discussed it in Arduino Datatypes.
  • So, let’s have a look at the example of digitalRead:

Reading = digitalRead (8);

  • In the above example, I am reading the status of digital Pin # 8 of Arduino and saving it value in the Reading variable.
  • So, I hope now you have understood completely How to use the digital Read in Arduino.

Note:

  • One important thing to note here is that because we are reading the data from digital Pin so that digital Pin must have to be an input.
  • So, you need to declare that Pin as an input.
  • So, let’s have a look at a small code in which we will read the status of pin # 8 of Arduino and then display its status on Serial Monitor.
  • I hope you have already read How to write Arduino Code and knows its basics.
int Pin = 8; // Initializing Arduino Pin
int Reading;

void setup() {
  pinMode(Pin, INPUT); // Declaring Arduino Pin as an Input
}

void loop() {
  Reading = digitalRead(Pin); // Reading status of Arduino digital Pin
  
  if(Reading == HIGH)
  {
    Serial.println("HIGH");
  }

  if(Reading == LOW)
  {
    Serial.println("LOW");
  }
 
}

Summary

Definition:

  • digitalRead is used to read the status of any digital Pin in Arduino.
  • We have to give the digital Pin number in the small brackets.

Syntax:

Syntax of digital Read is:

int Reading = digitalRead (int PinNumber);

Return:

digitalRead returns HIGH or LOW depending on the status of corresponding digital Pin.

Example:

Reading = digitalRead (8);

Restriction:

Before reading status of any digital Pin, we have to first declare that Pin as an input.:

pinMode(8,INPUT);

How to use DigitalWrite Arduino Command

JLCPCB – Prototype 10 PCBs for $2 (For Any Color)China’s Largest PCB Prototype Enterprise, 600,000+ Customers & 10,000+ Online Orders DailyHow to Get PCB Cash Coupon from JLCPCB: https://bit.ly/2GMCH9w

Объяснение работы программы

Для того, чтобы полноценно использовать АЦП в Arduino Uno, необходимо сделать следующие вещи:

Прежде всего необходимо отметить что каналы АЦП Arduino Uno имеют по умолчанию опорное значение 5 В (опорное напряжение). Это означает, что максимальное входное значение напряжения для каждого канала АЦП Arduino составляет 5 В. Но некоторые датчики имеют выходное напряжение в диапазоне 0-2,5 В, поэтому если мы будем использовать опорное напряжение по умолчанию (5 В), то мы потеряем в точности измерений. В связи с этим полезно иметь возможность изменения значения опорного напряжения, для Arduino Uno это делается с помощью команды “analogReference();”.

По умолчанию мы имеем разрешающую способность АЦП, равную 10 бит, разрешение АЦП мы также можем изменить используя команду “analogReadResolution(bits);”. Это может быть полезно в ряде случаев.

Теперь, если все установки параметров работы АЦП нами сделаны, мы можем считать значение АЦП с канала ‘0’ просто используя инструкцию “analogRead(pin);”, где “pin” означает контакт (вывод), на который мы подаем аналоговый сигнал, в нашем случае это будет контакт “A0”. Значение с выхода АЦП может быть преобразовано в число типа integer, например, с помощью инструкции “int ADCVALUE = analogRead(A0);”, в результате выполнения этой инструкции значение с используемого канала АЦП после проведения преобразования (то есть АЦП) сохраняется в переменной целого типа (integer) под названием “ADCVALUE”.

Теперь несколько слов о работе с ЖК дисплеем 16×2. Сначала мы должны подключить необходимый заголовочный файл с помощью команды ‘#include <LiquidCrystal.h>’, этот заголовочный файл содержит все необходимые функции для работы с ЖК дисплеем. По умолчанию функционал этого файла настроен для работы с ЖК дисплеем в 4-битном режиме. С помощью этого заголовочного файла нам не нужно будет заботиться о том, чтобы передавать данные в ЖК дисплей бит за битом и писать какие либо собственные функции для работы с ЖК дисплеем.

Далее мы должны указать какой именно тип ЖК дисплея мы будем использовать. Существуют различные типы ЖК дисплеев, например, 20×4, 16×2, 16×1 и т.д. Мы в нашем проекте будем использовать ЖК дисплей 16×2, поэтому мы должны будем записать команду ‘lcd.begin(16, 2);’. А если бы у нас был дисплей 16×1, то нам бы пришлось использовать команду ‘lcd.begin(16, 1);’.

Далее мы Arduino Uno должны указать, к каким ее контактам мы подключили ЖК дисплей. В нашем случае мы к Arduino Uno подключили следующие выводы ЖК дисплея: “RS, En, D4, D5, D6, D7”. Мы подключили их к контактам 0, 1, 8, 9, 10, 11 Arduino Uno, поэтому в нашем случае соответствующая команда будет иметь следующий вид: “LiquidCrystal lcd(0, 1, 8, 9, 10, 11);”.

После всего этого мы можем приступит к передаче данных на ЖК дисплей. Сделать это можно, к примеру, с помощью следующей команды: “lcd.print(«hello, world!»);”. В результате выполнения этой команды на экран ЖК дисплея будет выведена строка ‘hello, world!’.

Плата Arduino Micro

Arduino Micro представляет собой устройство, основа которого построена на микроконтроллере ATmega 32u4, имеющем встроенный USB-контроллер. Это решение упрощает подключение платы к компьютеру, так как в системе устройство будет определяться как обычная клавиатура, мышь либо COM-порт. Состав устройства следующий:

  • количество входов/выходов – 20 (имеется возможность 7 из них использовать как ШИМ-выходы, а 12 – в роли входов аналогового типа); резонатор кварцевый, настроенный на 16 МГц;
  • micro-USB-разъём;
  • ICSP-разъём, предназначенный для проведения внутреннего программирования;
  • кнопка для сброса.

Все цифровые выводы изделия могут работать в качестве как входов, так и выходов благодаря наличию функций digital Read, pin Mode, digital Write. Напряжение на выводах составляет 5 вольт. Максимальная величина потребляемого или отдаваемого тока с одного вывода составляет 40 мА. Выводы сопрягаются с внутренними резисторами, которые по умолчанию находятся в отключенном состоянии. Они имеют номиналы в 20 кОм – 50 кОм. Отдельные выводы arduino micro, кроме основных, способны выполнять и ряд дополнительных функций:

  1. В последовательном интерфейсе выводы №0 (RX), №1 (TX) применяются для приёма (RX), а также передачи (TX) необходимых данных через встроенный аппаратный приёмопередатчик. Функция актуальна для arduino micro класса Serial. В других случаях связь осуществляется через соединение USB (CDC).
  2. Интерфейс TWI включает выводы микроконтроллера №2 (SDA) и №3 (SCL). Позволяют использовать данные библиотеки Wire.
  3. Выводы под номерами 0, 1, 2, 3 могут быть использованы в роли источников возникающих прерываний. К таковым относятся низкий уровень сигнала; прерывания по фронту, по спаду, при изменении уровня сигнала.
  4. Выводы под номерами 3, 5, 6, 9, 10, 11,13 при использовании функции analog Write способны выводить аналоговый ШИМ-сигнал в 8 бит.
  5. К SPI-интерфейсу относятся выводы на разъёме ICSP. Они не соединяются с цифровыми выводами на плате.
  6. Дополнительный вывод RX LED/SS, который соединён со светодиодом. Последний индицирует процесс по передаче данных с использованием USB. Этот вывод может быть использован при работе с интерфейсом SPI для вывода SS.
  7. Вывод №13 – светодиод, который включается при отправке данных HIGH и выключается при значениях LOW.
  8. Выводы A0 – A5 (отмечены на плате) и A6 – A11 (соответствуют цифровым выводам за номерами 4, 6, 8, 9, 10,12) являются аналоговыми.
  9. Вывод AREF позволяет изменять верхнее значение аналогового напряжения на вышеуказанных выводах. При этом используется функция analog Reference.
  10. С помощью вывода Reset формируется низкий уровень (LOW) и происходит перезагрузка микроконтроллера (кнопка сброса).

Аналоговые входы на Ардуино

Микроконтроллер Atmega в Arduino, содержит шестиканальный аналого-цифровой преобразователь (АЦП). Разрешение преобразователя составляет 10 бит, что позволяет получать значения от 0 до 1023. Основным применением аналоговых входов Ардуино (A0 — A5 в Arduino UNO) является снятие значений с аналоговых датчиков. Рассмотрим применение аналогового входа для снятия показаний с потенциометра.


Аналоговые порты можно настроить, как цифровые

Небольшая цена деления шкалы позволяет с большой точностью получать значения практически любой физической величины. Чтобы считать показания на аналоговом входе следует использовать функцию analogRead. Аналоговые порты, как цифровые Ардуино можно сделать с помощью команды — используется для считывания данных с кнопки и — можно подключить светодиод.

Оцените статью:
Оставить комментарий