Touch memory (1-wire, ibutton)

Содержание

Switch Applications

On/Off Control

Among the most obvious of switch applications is simple on and off control. The type of control you perform every time you walk into a dark room. An on/off switch can be implemented by simply sticking an SPST switch in series with a power-line. Usually the on/off switch will be maintained, like a toggle or slide switch, but momentary on/off switches can have their purpose.

On this Breadboard Power Supply, an SPDT switch is used to turn the circuit on and off. (A second SPDT switch is used to select the adjustable voltage regulator’s output value by adjusting a voltage divider.)

When implementing such a switch, keep in mind that all the current your project consumes is going to run through that switch. Ideally a switch is a perfect conductor, but realistically it’s got a small amount of resistance between the two contacts. Because of that resistance, all switches are rated for a maximum amount of current they can withstand. Exceed a switch’s maximum current rating, and you can expect melted plastic and magic smoke.

For example, this SPDT slide switch is great for controlling current flow in small projects (like Simons or Metronomes), but don’t try using it to control beefy motor controllers, or strings of 100 LEDs. For that, consider using something like a 4A toggle switch or a 6A lamp switch.

User Input

Of course, user input is one of the more common applications for switches. For example, if you want to connect a switch to a microcontroller input pin, a simple circuit like this is all you’d need:

Схема

Компоненты и их предназначение:

  • IC1 — микроконтроллер ATMEGA8/ATMEGA8A/ATMEGA8L;
  • U1 — USB-контроллер FT232RL, нужен для подключения устройства к компьютеру;
  • CON1 — miniUSB разъём;
  • BT1 — батарейки, дающие 5 вольт;
  • D1 и D2 — диоды (желательно шоттки), которые изолируют питание от батареи от питания от USB;
  • P1 — «таблетка» iButton, используется для подключения к домофонам;
  • P2 — контакты считывателя ключей, используются для подключения к ключам;
  • R1 — резистор, подтягивающий линию 1-wire к VCC;
  • R2 — токопонижающий резистор для управления транзистором Q2;
  • R3 — резистор, ещё сильнее подтягивающий линию к VCC для считывания ключей Cyfral;
  • R4 — токопонижающий резистор, используется для открытия Q1 и определения подключения к USB;
  • R5 — подтягивает базу Q1 к земле, чтобы закрывать его, когда нет подключения к USB;
  • R6 — токопонижающий резистор для светодиодов, достаточно одного, т.к. одновременно они не горят;
  • R7 и R8 — делитель напряжения для одного из входов компаратора, чтобы считывать ключи Cyfral;
  • Q1 — транзистор для определения подключения к USB;
  • Q2 — транзистор для включения земли на считывателе и эмуляторе, чтобы не сажать батарейки, случайно замкнув контакты в кармане;
  • C1, C2 и C3 — конденсаторы для фильтрации питания;
  • SW1 — единственная кнопка для управления устройством;
  • LEDS — семь светодиодов в форме восьмёрочки для отображения номера ключа.

Вариант печатной платы:

HTML Теги

<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><menu><menuitem><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

2Считывание идентификатора ключа iButton с помощью Arduino

Для работы с интерфейсом 1-wire существуют готовые библиотеки для Ардуино. Можно воспользоваться, например, этой. Скачиваем архив и распаковываем в папку /libraries/, расположенную в каталоге Arduino IDE. Теперь мы можем очень просто работать с данным протоколом.

Загрузим в Ардуино стандартным способом этот скетч:

Скетч чтения ключа iButton с помощью Arduino (разворачивается)

#include <OneWire.h>
OneWire iButton(10); // создаём объект 1-wire на 10 выводе

void setup (void) {
  Serial.begin(9600);
}

void loop(void) {
  delay(1000); // задержка 1 сек
  byte addr; // массив для хранения данных ключа
  
  if ( !iButton.search(addr) ) { // если ключ не приложен
      Serial.println("No key connected..."); // сообщаем об этом
      return; // и прерываем программу
  }
  
  Serial.print("Key : ");
  for(int i=0; i}

Данный скетч показывает номер ключа для домофона, который подключён к схеме. Это то, что нам и нужно сейчас: мы должны узнать номер ключа, копию которого хотим сделать. Подключим Ардуино к компьютеру. Запустим монитор последовательного порта: Инструменты Монитор последовательного порта (или сочетание клавиш Ctrl+Shift+M).

Теперь подключим ключ к схеме. Монитор порта покажет номер ключа. Запомним этот номер.

Запоминаем номер ключа iButton, выводимый в монитор последовательного порта

А вот какой обмен происходит на однопроводной линии при чтении идентификатора ключа (подробнее – далее):

Диаграмма взаимодействия ключа Dallas с Arduino по однопроводному интерфейсу (1-wire)

На рисунке, конечно, не видны все детали реализации. Поэтому в конце статьи я прикладываю временную диаграмму в формате *.logicdata , снятую с помощью логического анализатора и программы Saleae Logic Analyzer и открываемую ей же. Программа бесплатная и скачивается с официального сайта Saleae. Чтобы открыть файл *.logicdata нужно запустить программу, нажать сочетание Ctrl+O или в меню Options (расположено вверху справа) выбрать пункт Open capture / setup.

HTML Reference

HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts

HTML Tags

<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>

Использование кнопок

Элементы не имеют поведения по умолчанию (их двоюродные братья, и используются для отправки и сброса форм соответственно). Чтобы кнопки делали что-либо, вы должны написать код JavaScript для выполнения работы.

Мы начнём с создания простой кнопки с обработчиком события , который запускает наш компьютер (ну, он переключает кнопки и текстовое содержимое следующего абзаца):

Сценарий получает ссылку на объект , представляющий в DOM, сохраняя этот параметр в переменной . Затем используется для установки функции, которая будет запускаться, когда на кнопке происходят события .

Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any for which it makes sense — you use the global attribute.

In this example, s is specified as the access key (you’ll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).

Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you’d have to provide this information in a way that doesn’t intefere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).

To disable a button, simply specify the global attribute on it, like so:

You can enable and disable buttons at run time by simply setting to or . In this example our button starts off enabled, but if you press it, it is disabled using . A function is then used to reset the button back to its enabled state after two seconds.

If the attribute isn’t specified, the button inherits its state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a element, and then setting on the container.

The example below shows this in action. This is very similar to the previous example, except that the attribute is set on the when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.

Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the attribute to control this feature.

Электронный ключ Touch Memory

Принцип работы

Популярные ключи Dallas Touch Memory, они же таблетки iButton, функционируют следующим образом.

В качестве считывателя выступает контактор, при соприкосновении которого с идентификатором замыкается электросхема и происходит передача на контроллер уникального 48-битного номера (+8 бит — код семейства, + 8 бит CRC — проверка) и на основании полученных данных принятие решения о допуске или отказе в доступе.

При этом таблетка Touch Memory выступает в качестве пассивного идентификатора, поскольку и питание, и опрос осуществляются через контроллер СКУД.

Конструктивные особенности таблеток iButton

Основой электронного ключа Touch Memory является, выполненный в виде таблетки диаметром 16 мм, герметичный корпус из нержавеющей стали, верхняя крышка которого электрически изолирована от нижней части при помощи полипропиленовой втулки. Толщина стали корпуса составляет 5,8 мм (корпус F5) или 3,2 мм (корпус F3). При этом верхняя крышка является контактом данных, а нижняя — общим контактом. Внутри корпуса размещается кремниевый чип (микросхема).

Эта конструкция обеспечивает высокую устойчивость ключей iButton к внешним воздействиям и неблагоприятным условиям окружающей среды. Например, они способны выдержать 11-килограммовую нагрузку на корпус, механический удар 500 г, падение с высоты 1,5 метров на бетонный пол. А, кроме того, могут работать в условиях повышенной влажности, не чувствительны к загрязнениям, вибрации и действию магнитных и статических полей. Рабочий диапазон температур составляет -40ºС до +85ºС для DS1990 и от -20ºС до +85ºС для остальных приборов семейства.

Достоинства электронных ключей Dallas Touch Memory

  • небольшой размер;
  • возможность работы в агрессивных условиях окружающей среды;
  • высокая скорость считывания (менее 5 мс);
  • простой и быстрый обмен данными по протоколу 1-Wire;
  • идентификация по касанию;
  • удобство совмещения ключа с контактором, за счет чашевидной формы последнего;
  • возможность простого закрепления таблетки iButton на различных поверхностях или в различных аксессуарах.

Сфера применения iButton

В силу невысокой стоимости, надежности, простоты считывающих устройств и открытому протоколу этот тип iButton (DS1990) получил массовое внедрение в качестве электронного ключа в системах охранной сигнализации, разграничения доступа к информации и физическим объектам, электронным проходным, электронным замкам и в системах безопасности для банков и офисов.

Также применяется для маркировки объектов и маршрутов в системах контроля патрульно-постовой службы, контроля передвижения транспорта, системах инвентарного и складского учёта и в качестве кредитных карт в локальных платежных системах. Но наиболее частым применением идентификаторов Touch Memory остаются домофонные системы.

Недостатки использования электронных идентификаторов

  • недостаточная защищенность ключа от изготовления дубликата;
  • недостаточная защищенность контактора.

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


Особенно печальные последствия могут быть от воздействия электрошокера у проводной клавиатуры: электрический разряд может уничтожить ПКП, нарушив работу всей системы. Да и вообще, считыватель можно просто-напросто замазать краской или залепить жвачкой.


Многие клавиатуры со считывателями Touch Memory не защищены от воздействия ключа-вездехода, иногда называемого «ключом почтальона», а это не добавляет надежности в работе системы. Ну и, наконец, ключ можно потерять, или, что достаточно часто случается у меня лично, теряется сама «таблетка», а пластиковый корпус остается, —
говорит Мария ЛИВЕНЦОВА специалист по ОПС, компании «Альтоника».

Атрибуты

Элемент поддерживает глобальные атрибуты.

HTML5
Данный булевый атрибут позволяет указать, будет ли кнопка автоматически сфокусирована после загрузки страницы, до тех пор, пока пользователь не изменит фокус в ручную, например выбрав другой элемент. Только один связанный с формой элемент в документе может иметь данный атрибут.
Использование данного атрибута на элементе не описано в стандарте и используется только в Firefox браузере. По умолчанию, в отличие от прочих браузеров, Firefox сохраняет назначенное динамически отключённое состояние для элемента при последующих загрузках страницы. Установка для данного атрибута значения  отключает подобное поведение. Смотрите баг 654072.

Булевый атрибут, указывающий, что пользователь не может взаимодействовать с кнопкой. Если атрибут не установлен, то кнопка наследует его от элемента-контейнера, в котором она расположена, например от ; если отсутствует элемент-контейнер, с установленным атрибутом disabled, то кнопка доступна для взаимодействия.

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

HTML5
Атрибут form позволяет указать элемент , с которым связана кнопка. Данный атрибут должен хранить значение id элемента . Если данный атрибут не установлен, то элемент  будет связан с родительским элементом , если последний существует.
Атрибут работает независимо от расположения элементов в документе, поэтому он позволяет связать элемент  с формой, даже в случае, если не является наследником элемента .
HTML5
Ссылка на обработчик формы. Если атрибут определён — он переопределит атрибут  у формы-родителя.
HTML5
Если имеет тип , то этот атрибут определяет тип контента, отправляемого на сервер. Возможные значения данного атрибута:
  • : значение по умолчанию, если атрибут не указан.
  • : следует использовать это значение, если форма содержит элемент со значением атрибута  .

Если этот атрибут определён, он переопределяет атрибут  у формы-родителя.

HTML5
Если имеет тип , то этот атрибут определяет метод HTTP-запроса для отправки данных на сервер. Возможные варианты:
  • : данные формы включаются в тело сообщения и отправляются на сервер.
  • : данные формы отправляются на сервер в виде ссылки, состоящей из URI атрибута  и непосредственно данных, отделённых знаком ‘?’. Данные формы будут иметь вид ключ/значение и разделены амперсандом, например name=Name&id=35. Следует использовать этот метод только если нет побочных эффектов и данные формы содержат лишь ASCII-символы.

Если этот атрибут определён, он переопределяет атрибут у формы-родителя.

HTML5
Булевый атрибут. Указывает, что данные формы не будут валидироваться при отправке.
Если этот атрибут определён, он переопределяет атрибут у формы-родителя.
HTML5
Если имеет тип , этот атрибут является именем или ключевым словом,

указывающим, где отображать ответ, полученный после отправки формы. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the attribute of the button’s form owner. The following keywords have special meanings:

  • : Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • : Load the response into a new unnamed browsing context.
  • : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as .
  • : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as .
The name of the button, which is submitted with the form data.
The type of the button. Possible values are:
  • : The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
  • : The button resets all the controls to their initial values.
  • : The button has no default behavior. It can have client-side scripts associated with the element’s events, which are triggered when the events occur.
  • menu: The button opens a popup menu defined via its designated element.
The initial value of the button.

vs.

In addition to the type of input, there is a separate element which is functionally very similar. By default, they are both displayed as buttons, and they both usually rely on JavaScript for their utility — neither one of them has much use in a strict form-input and submission paradigm. The difference is that the element can have content, while the element is (that is, it does not have a closing tag and cannot contain any content. This means that the element can have a picture, or marked-up text, while the input cannot have either.

Why use the

So, if the element is basically the same, except better, why use the input type at all? The answer is the attribute. With the type input, the is displayed on the button itself. With the element, the button displays its content. This means that if you want to update or use the and the displayed content in concert, you would need to use the input, or else do a lot more scripting to sync the value with its content. If the is irrelevant, either element works just fine.

Adam Wood

Attributes

Attribute Value Description
autofocus autofocus Specifies that a button should automatically get focus when the page loads
disabled disabled Specifies that a button should be disabled
form form_id Specifies which form the button belongs to
formaction URL Specifies where to send the form-data when a form is submitted. Only for type=»submit»
formenctype application/x-www-form-urlencoded
multipart/form-data
text/plain
Specifies how form-data should be encoded before sending it to a server. Only for type=»submit»
formmethod getpost Specifies how to send the form-data (which HTTP method to use). Only for type=»submit»
formnovalidate formnovalidate Specifies that the form-data should not be validated on submission. Only for type=»submit»
formtarget _blank
_self
_parent
_topframename
Specifies where to display the response after submitting the form. Only for type=»submit»
name name Specifies a name for the button
type button
reset
submit
Specifies the type of button
value text Specifies an initial value for the button

Momentary Switches

Momentary switches are switches which only remain in their on state as long as they’re being actuated (pressed, held, magnetized, etc.). Most often momentary switches are best used for intermittent user-input cases; stuff like reset or keypad buttons.

Push-button

Push-button switches are the classic momentary switch. Typically these switches have a really nice, tactile, “clicky” feedback when you press them. They come in all sorts of flavors: big, small, colorful, illuminated (when an LED shines up through the button). They might be terminated as through-hole, surface-mount, or even panel-mount.

An assortment of tactile push-button switches. Starting top-left, clockwise: blue and pink arcade buttons, 12mm push button, white capped button, orange illuminated, right-angle, panel-mount, and a mini push button.

Button Matrices

Large arrays of momentary buttons, like your keyboard or even smaller groupings like a keypad, usually arrange all of their switches into a big matrix. Every button on the pad is assigned a row and column . This requires some extra button-press-processing on the microcontroller end, but frees up a big chunk of I/O pins.

Etc.

Momentary switches don’t always have to be actuated by a pushdown. It could be push-sideways, like the movement action in a handful of joysticks.

An arcade joystick uses four microswitches to sense up, down, left and right movements. The tiny little surface-mount 5-way tactile switch is an SP5T directional switch (up, down, left, right, and press-down).

On the other end of the spectrum, reed switches open or close when exposed to the presence of a magnetic field. These are great for making a non-contact switch.

Attributes

This element’s attributes include the global attributes.

This Boolean attribute specifies that the button should have input focus when the page loads. Only one element in a document can have this attribute.
This attribute on a is nonstandard and Firefox-specific. Unlike other browsers, Firefox persists the dynamic disabled state of a across page loads. Setting on the button disables this feature; see bug 654072.

This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or focused.

Firefox, unlike other browsers, persists the dynamic disabled state of a across page loads. Use the attribute to control this feature.

The element to associate the button with (its form owner). The value of this attribute must be the of a in the same document. (If this attribute is not set, the is associated with its ancestor element, if any.)

This attribute lets you associate elements to s anywhere in the document, not just inside a . It can also override an ancestor element.

The URL that processes the information submitted by the button. Overrides the attribute of the button’s form owner. Does nothing if there is no form owner.
If the button is a submit button (it’s inside/associated with a and doesn’t have ), specifies how to encode the form data that is submitted. Possible values:
  • : The default if the attribute is not used.
  • : Use to submit elements with their attributes set to .
  • : Specified as a debugging aid; shouldn’t be used for real form submission.

If this attribute is specified, it overrides the attribute of the button’s form owner.

If the button is a submit button (it’s inside/associated with a and doesn’t have ), this attribute specifies the HTTP method used to submit the form. Possible values:
  • : The data from the form are included in the body of the HTTP request when sent to the server. Use when the form contains information that shouldn’t be public, like login credentials.
  • : The form data are appended to the form’s URL, with a as a separator, and the resulting URL is sent to the server. Use this method when the form has no side effects, like search forms.

If specified, this attribute overrides the attribute of the button’s form owner.

If the button is a submit button, this Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the attribute of the button’s form owner.

This attribute is also available on and elements.

If the button is a submit button, this attribute is a author-defined name or standardized, underscore-prefixed keyword indicating where to display the response from submitting the form. This is the of, or keyword for, a browsing context (a tab, window, or ). If this attribute is specified, it overrides the attribute of the button’s form owner. The following keywords have special meanings:
  • : Load the response into the same browsing context as the current one. This is the default if the attribute is not specified.
  • : Load the response into a new unnamed browsing context — usually a new tab or window, depending on the user’s browser settings.
  • : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as .
  • : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as .
The name of the button, submitted as a pair with the button’s as part of the form data, when that button is used to submit the form.
The default behavior of the button. Possible values are:
  • : The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a , or if the attribute is an empty or invalid value.
  • : The button resets all the controls to their initial values, like <input type=»reset»>. (This behavior tends to annoy users.)
  • : The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element’s events, which are triggered when the events occur.
Defines the value associated with the button’s when it’s submitted with the form data. This value is passed to the server in params when the form is submitted using this button.

Описание

HTML-элемент  создаёт кликабельную кнопку, которая может быть использована в формах или в любом другом месте документа, который требует простой, стандартной кнопки. По умолчанию, кнопки HTML обычно представлены в стиле, аналогичном стилю хост-платформы, на которой работает user agent, но вы можете изменить внешний вид кнопки, используя CSS.

Категории контента , , , , , и   элемент, очевидный контент.
Разрешённый контент .
Tag omission Нет, открывающий и закрывающий теги обязательны. 
Разрешённый родительский контент Любой элемент с поддержкой .
Разрешённые роли ARIA

, , , , , , ,

DOM interface
Тип Строчный