Digispark i2c arduino

Обзор Digispark

Характеристики

Сам проект «народный», бабло на него собирали кажется на кикстартере. Суть сводится к тому, что в AVR микроконтроллер зашит загрузчик при загрузке изображающий из себя USB устройство. Это позволяет из стандартной среды Arduino IDE заливать скетчи (они же программы, они же прошивки) напрямую в AVR контроллер. На алиэкспрессе «аналоги» подобной платы стоят в районе 100 рублей за штутку:

Для работы с ним понадобится среда Arduino IDE, с сайта проекта нужно скачать драйвера, и выполнить небольшую настройку IDE. (на момент написания статьи сайт проекта не доступен, вероятно это результат спектакля роскомнадзор vs telegram) Расписывать тут не буду, так как если вы не сможете справиться с этим, то и читать дальше вам будет бессмысленно. Когда всё настроено, запускается прошивка скетча, при этом нужно отсоединить и подсоединить плату, загрузка при этом начнётся автоматически. Поскольку для передачи данных USB используются те же самые контакты, то при прошивке всё «лишнее» нужно отключать.

Теперь немного о возможностях контроллера ATtiny85 питание от 2.7 до 5 Вольт, в даташите ссылок на рабочую температуру не нашёл, но там есть несколько графиков зависимости от температуры, где график начинается с -40 градусов, отчего можно предположить, что с зимней эксплуатацией в России проблем быть не должно. Рабочая частота 16 Мгц, АЦП доступен на 4х выводах, при это сам АЦП 1, и соответственно одновременно может производится только один замер, ацп 10-битный. Из 6 выводов 5й использовать проблематично — при замыкании его на землю, контроллер перезагружается. К выводу 1 подключен светодиод. PWM доступен, но использовать его можно разве что для световых приборов — частота маленькая менее 1000 Гц, отчего механическая нагрузка неизбежно будет гудеть. Практически для каждого из выводов есть свои ограничения:

Pin number Output Voltage Analogue Port Number
analogRead()
PWM USB Test LED I2C SPI*
0 5 V Y — 504 Hz Rev 1 SDA MISO
1 5 V Y — 504 Hz Rev 2 / 4 MOSI
2 5 V 1 SCL SCK
3 3.6 V 3 Y — 1.5 кОм к 5 В
стабилитрон 3,6 В
4 3.6 V 2 Y — 1007 Hz Y
стабилитрон 3,6 В
5 3 V 0

Методики отладки

Теперь немного расскажу о способах отладки прошивок. Простейший из способов — моргание светодиодом на выводе p1. Скажем, по умолчанию моргаем 1 раз в секунду, при условии 2 — 2 раза и т.д. Однако это случай довольно примитвный. Мне же довелось отлаживать проект, использующий ЦАП (ADC), а там уже 1024 значения. Моргать конечно можно, но как считать :) ? И тут я решил поподробнее изучить шину i2c, она использует 2 провода, одно устройство — мастер, и куча рабов, до 127. И этот способ мне показался довольно перспективным. Можно сделать головное устройство на Arduino Mega, и на общую шину посадить не один десяток устройств, как исполнительных механизмов, так и датчиков.

Отладочный скетч для мастера на Arduino Mega. Используется библиотека для работы с i2c wire. В цикле запрашивается информация с i2c раба с номером 11. Полученную информацию можно выводить в COM-порт, или на экран, подключенный к мастеру.

Отладочный скетч для раба Digispark. Поскольку аппаратной поддержки i2c в digispark нет, для эмуляции i2c используются библиотеки TineWireS и TineWireM для раба и мастера соответственно. Нужную библиотеку нужно скачать и положить в папку проекта. Здесь для входа аналогового сигнала используется ADC2, он же p4.

Почти идеально для отладки подходит цифровой индикатор tm1637.

По итогу можно сказать, что преимущества данной платы — возможность использования части библиотек от ардуино, либо сторонних. В отличие от того же ассемблера. В сравнении с ардуино, digispark раза в полтора дешевле самой простой arduino nano.

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

Проблемы и решения

Алгоритм борьбы с дребезгом контактов описан в статье PWM регулятор.

Сложности использования Pin 3 в качестве кнопки и организация питания от павербанка изложены в статье Пульт ИК ДУ на Digispark.

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

Решение проблем (не)запуска изложено в статье Термостат с PWM и индикацией.

Источник

Digistump Wiki

User Tools

Site Tools

Table of Contents

Connecting and Programming Your Digispark

Bootloader:

The bootloader is the code that is pre-programmed on your Digispark and allows it to act as a USB device so that it can be programmed by the Arduino IDE.

The Digispark runs the “micronucleus tiny85” bootloader version 1.02, an open source project: https://github.com/micronucleus/micronucleus originally written by Bluebie: https://github.com/Bluebie.

CAUTION We are not at this point supporting upgrading the firmware, so if you decide to, you do so entirely at your own risk.

Software:

The Digispark uses the Arduino IDE 1.6.5+ (Arduino 1.6.5r2 — NOT 1.6.6 or 1.6.7 strongly recommended)

Installation Instructions:

and click OK

Note: If you already have additional URLs entered in that box, then click the button on the right of the box and enter this URL on a new line.

Linux Install

Sources

Using the Digispark with the Arduino IDE:

The Digispark works a bit differently than some Arduino compatible products. The Digispark programs with a different procedure.

From the Tools menu select Board→Digispark (Default — 16.5Mhz)

(The Tools→Programmer selection does not matter)

Write some code, open your code, or open a Digispark example.

You do not need to plug in your Digispark before invoking upload

Hit the upload button. The bottom status box will now ask you to plug in your Digispark — at this point you need to plug it in — or unplug and replug it.

You’ll see the upload progress and then it will immediately run your code on the Digispark.

If you unplug the Digispark and plug it back in or attach it to another power source there will be a delay of 5 seconds before the code you programmed will run. This 5 second delay is the Digispark Pro checking to see if you are trying to program it.

Your first upload:

If you’re just getting started try the above procedure with the example you can find by going to File→Examples→Digispark→Start

Here is the code it will load:

This code will blink the BUILTIN LED (on either pin 0 or pin 1 depending on the Digispark model see:Model Identification).

As soon as it has uploaded you should see the LED start to blink!

For some sample code for the basic I/O function see here: Digispark Basics

Digispark Differences and Using Arduino/Processing with the Digispark:

The Arduino Environment introduction is a great start if you are new to the Arduino IDE: http://arduino.cc/en/Guide/Environment

The Digispark supports all features found in the IDE with the exception of the serial monitor and the burn bootloader functionality.

Many existing libraries will not work with the Digispark: For I2C devices check out the TinyWireM library, which makes it super simple to port an I2C based device library over to use with the Digispark.

For a handy pin reference flip over the Digispark — pin capabilities are listed on the back

For some sample code for the basic i/o function see here: Digispark Basics

Precautions:

The Digispark, due to its small size and low cost is not as robust as a full blown Arduino.

When testing a new circuit we recommend that you test it with an external power supply first. Connecting a shorted circuit to the Digispark and connecting it to your computer could damage your computer and/or its USB ports. We take no responsibility for damage to your machine as a result of the use of a Digispark.

We strongly recommend connecting your Digispark through a USB hub which will often limit the damage caused by a short circuit to the usb hub. For the record, we’ve found many computers have usb fuses built in, and when we blew them on our 27“ Mac monitor, thankfully they reset and everything worked after a power down.

The Digispark does not have short circuit or reverse polarity protection. Connecting power to the Digispark power pins backwards will almost certainly destroy it.

The Digispark is small enough to present a choking hazard and small enough to be inserted into some sockets. We take no responsibility for misuse of the product. Please treat electricity and electronics with respect and common sense.

Troubleshooting:

The Digispark pushes affordable, small components to their limits by using software to emulate USB functions generally served by a dedicated chip. For this reason much of the Digispark’s USB operation is considered borderline out of spec . Certain laptops, older machines, and just some cheaply made USB hubs/controllers do not like this. We tested and designed the Digispark for maximum compatibility but we can not guarantee it will work with everything.

In addition remember the Digispark only shows up as a programmable device for 5 seconds, after that it will start running its code (when it is new and un-programmed this means it will blink) and disappear or act like the USB device you programmed it to act like.

Always remember to unplug the Digispark before hitting upload and plug it in when the Arduino IDE requests you to. If you get an error that assertion failed or micronucleus crashed during upload then you probably did not unplug your Digispark before uploading.

If the computer will not recognize the Digispark try the following:

If it won’t upload:

Did you set your board AND programmer to Digispark in the Arduino IDE?

WINDOWS:

MAC

If your upload fails in the middle of it, you may also be using a bad USB cord and or a bad hub.

Источник

ATTINY85 – SIMULTANEOUSLY USING I2C AND SPI PROTOCOLS

Introduction: ATTINY85 – SIMULTANEOUSLY USING I2C AND SPI PROTOCOLS

The Attiny85 does not support specific hardware for SPI and I2C comunications as on ATmega series, instead there is a hardware module called UNIVERSAL SERIAL INTERFACE (USI) that can be only configured to perform SPI or I2C. In this small project, I’d like to share how to perform both SPI and I2C protocols simultaneously on the ATTiny85 by:

  • Using USI for I2C with TinyWireM library to read MPU-6050.
  • Using remaining pins for Software SPI to control one LED MATRIX 13×15.

Let’s getting started by video below.

Step 1: Bill of Materials and Tools

Main components:

  • 200pcs x LED 3mm, optional color, blue in my case.
  • 2pcs x Double Sided DIY Protoboard Circuit 7x9cm.
  • 1pcs x DigiSpark ATTiny85.
  • 1pcs x MPU-6050 Accelerometer + Gyro.
  • 2pcs x Shift Register 74HC595N.
  • 2pcs x Power Logic 8-Bit Shift Register TPIC6B595N.
  • 16pcs x Transistor A1013.
  • 300pcs x R100.
  • 16pcs x R1K.
  • 4pcs x Capacitor 0.1uF.
  • 4pcs x Copper Standoff Spacers 15mm.
  • 2pcs x Female 40pin 2.54mm Header.
  • 2pcs x Male 40pin 2.54mm Header.
  • 1pcs x XH2.54mm – 3P 10cm Wire Cable Double Connector.
  • 1pcs x XH2.54mm – 4P 10cm Wire Cable Double Connector.
  • 1pcs x XH2.54mm – 6P 10cm Wire Cable Double Connector.
  • 1pcs x Power Bank 5V, minimum 2A.
  • 1meter x 8P Rainbow Ribbon Cable.
  • Some small bolts and nuts.

Tools:

  • Intelligent Digital Oscilloscope Multimeter. This is an useful multimeter tool with reasonable price and it is integrated waveform signal display within 20KHz.

Step 2: Idea and Schematic

My idea is to use only one ATTiny85 to make an auto-rotating message led matrix — size 13×15. It uses an MPU-6050 Accelerometer + Gyro to calculate the angle and detect whenever led matrix is in upside-down position, then it will carry out the correction by rotating the message on led matrix and its direction as well.

You can download schematic with high resolution PDF file HERE.

Step 3: Protoboards Soldering

I soldered the led matrix shield and control circuit on 2 prototype boards 7x9cm as diagram shown on STEP 2.

1. Soldering led matrix shield 13×15

I cut led pins short enough and ensure all led anodes/ cathodes to be soldered together without any extension wires. Led matrix shield have all 15 rows and each row has 13 leds. At the bottom, male headers for led anodes (rows) and cathodes (columns) were soldered to plug on the control board.

2. Soldering control circuit

I soldered the control circuit to another DIY protoboard 7x9cm. All the wires were arranged on PCB top and they will be hidden when led matrix shield is plugged.

  • Plugging ATTiny85 and MPU6050 into their female headers.

  • Connecting the wires from ATTiny85 male header to SPI and MPU-6050 male headers. Control board is DONE. The ATTiny85 USB port is protruded from the protoboard so that it can be plugged into a computer or power bank.

3. Connecting protoboards together

  • Plugging matrix shield to control board.

  • DigiSpark ATTiny85 was glued into the control protoboard to avoid wobbling.

Step 4: Eagle Design

Because the protoboard 7x9cm has limited space so I took my times to design this project in Eagle software. With the same hardware configuration, Eagle PCB can control led matrix 16×16 with auto-rotating function.

I have just finished designing and did not send to fabrication company. I think it should work as same as my protoboards.

And here is my design.

  • PDF print file for Clothes Iron Toner Transfer

To make a circuit board at home, we can use Clothes Iron Toner Transfer method that simply print below circuit designs out on a laser printer, iron it onto the copper, and etch by Ferric Chloride.

Step 5: Programming

The Arduino code for this project is available at my GitHub.

The first scrolling text testing is shown in below video and led board is powered from the laptop.

Step 6: ATTinyCore & TinyWireM Library

The following core, library and driver need to be installed in this project:

This core allows sketches to be uploaded directly to DigiSpark ATTiny85 via USB and it can be installed using the Boards Manager in Arduino IDE. The Boards Manager URL is:

— File Preferences on Arduino IDE, enter the above URL in «Additional Boards Manager URLs«

— Tools Boards Boards Manager.

— Select «ATTinyCore by Spence Konde» and click «Install«.

2. TinyWireM (I2C library) at https://github.com/adafruit/TinyWireM

— Open Aduino IDE

— Sketch Include Library Manage Libraries. Search «TinyWireM«

3. Digistump Driver:

Step 7: How It Works

1. DigiSpark ATTiny Pin Usage

  • SPI connection

— Serial data (DATA_PIN) — ATTiny85 PIN P1

— Shift register clock (CLOCK_PIN) — ATTiny85 PIN P3

— Storage register clock (LATCH_PIN) — ATTiny85 PIN P4

— Output enable (BLANK_PIN): For this version, it is connected to GND.

  • I2C connection

— SCL — ATTiny85 PIN P2

— SDA — ATTiny85 PIN P0

2. Program explanations:

  • Compare Match Interrupt setup for SPI protocol, take note that in CTC mode, the timer clears the counter after it reaches OCR1C.
  • I2C and MPU-6050 setup
  • Led matrix can be adjusted brightness via Bit Angle Modulation (BAM) mode, or constant brightness mode. This option can be set by parameter «BAM_USE«.
  • In constant brightness mode, we can choose 4 options brightness level, for example:
  • There are 4 set of fonts for scrolling texts as follows: FONT 3×5, FONT 5×7, FONT 8×8 and FONT 8×16. We can check auto-rotating function in a specific case, like FONT8x16:

ATTiny85 read the value «AccX« from MPU-6050 via I2C and compare with «0» (pos = (AccX >0 ? 1:0)) to determine auto-rotating function.

Источник

Adblock
detector