From d3f9fa70b57e71c6a45f3412f1aa31838a12f259 Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Thu, 19 Nov 2026 20:59:40 +0100 Subject: [PATCH] avr nano: Support MLX90614 --- avr/nano/AGENTS.md | 11 +- avr/nano/Makefile | 4 +- avr/nano/i2c/group__pfleury__ic2master.html | 473 ++++++++++++++++++ avr/nano/i2c/i2cmaster.S | 298 ++++++++++++ avr/nano/i2c/i2cmaster.h | 178 +++++++ avr/nano/i2c/makefile | 392 +++++++++++++++ avr/nano/i2c/makefile.i2cmaster | 392 +++++++++++++++ avr/nano/i2c/makefile.twimaster | 502 ++++++++++++++++++++ avr/nano/i2c/test_i2cmaster.c | 78 +++ avr/nano/i2c/twimaster.c | 197 ++++++++ avr/nano/main.c | 39 +- avr/nano/mlx90614.c | 25 + avr/nano/mlx90614.h | 15 + 13 files changed, 2595 insertions(+), 9 deletions(-) create mode 100644 avr/nano/i2c/group__pfleury__ic2master.html create mode 100644 avr/nano/i2c/i2cmaster.S create mode 100644 avr/nano/i2c/i2cmaster.h create mode 100644 avr/nano/i2c/makefile create mode 100644 avr/nano/i2c/makefile.i2cmaster create mode 100644 avr/nano/i2c/makefile.twimaster create mode 100644 avr/nano/i2c/test_i2cmaster.c create mode 100644 avr/nano/i2c/twimaster.c create mode 100644 avr/nano/mlx90614.c create mode 100644 avr/nano/mlx90614.h diff --git a/avr/nano/AGENTS.md b/avr/nano/AGENTS.md index 043a7e3..616f1c5 100644 --- a/avr/nano/AGENTS.md +++ b/avr/nano/AGENTS.md @@ -1,27 +1,28 @@ # AGENTS.md -AVR firmware (ATmega328P, 16 MHz) for the "Wild Thumper" arm's **virtual servo**: a DYNAMIXEL bus slave with ID `0x21` on the half-duplex single-wire UART (PD2, picoUART, 115200 8N1). A protocol-2.0 1-byte WRITE (INS=0x03) to address 0x01 sets `OCR0A` (D6 LED PWM duty) and gets an 11-byte status reply; all other packets are silently ignored. The ROS 2 package side lives in the repo root and is documented in the root `AGENTS.md` — do not confuse the two. +AVR firmware (ATmega328P, 16 MHz) for the "Wild Thumper" arm's **virtual servo**: a DYNAMIXEL bus slave with ID `0x21` on the half-duplex single-wire UART (PD2, picoUART, 115200 8N1). Packets addressed to `0x21` are dispatched by `dynamixel_slave_poll()` to a callback registered from `main.c`; today that handles a protocol-2.0 1-byte WRITE (INS=0x03) to address 0x01 → `OCR0A = 255 - value` (D6 LED PWM duty, inverted — hardware-tuned, keep the inversion) and an 11-byte status reply, and a READ (INS=0x02) of address 0x02 → 13-byte status reply carrying the MLX90614 IR thermometer object temperature as a 16-bit value in 0.1 °C (214 == 21.4 °C, low byte first); everything else is silently ignored. The ROS 2 package side lives in the repo root and is documented in the root `AGENTS.md` — do not confuse the two. ## Build / verify -- `make` → `main.elf` / `main.hex` (WinAVR-style Makefile; sources in `SRC`/`SRCPP`: `main.c uart.c` + `dynamixel-avr/dynamixel.cpp picoUART/src/picoUART.cpp`). `make clean` removes all artifacts (`*.o *.elf *.hex *.map *.lss *.lst *.sym *.eep .dep`) — run it before committing. +- `make` → `main.elf` / `main.hex` (WinAVR-style Makefile; sources in `SRC`/`SRCPP`: `main.c uart.c mlx90614.c i2c/twimaster.c` + `dynamixel-avr/dynamixel.cpp picoUART/src/picoUART.cpp`). `make clean` removes all artifacts (`*.o *.elf *.hex *.map *.lss *.lst *.sym *.eep .dep`) — run it before committing. - **`picoUART/src/rxISR.cpp` is deliberately NOT in the build**: it targets the ATtiny (`GIMSK`/`PCMSK`/PCINT0, none exist on the 328P) and captures one byte only. Do not "fix" it into the build. - Flashing: `make program` (avrdude/avrisp2/usb). No programmer is attached in this environment; the user flashes elsewhere — do not attempt to flash here. - Debug console: 9600 baud on D0/D1 (`uart.c`, `printf`); prints "Start" at boot. - **No-hardware verification** (this environment has no python3, no host gcc, no simavr/qemu; shell is busybox ash): 1. `make` must finish with `Errors: none`. - 2. `sh tools/verify_slave.sh` — host-side check of the slave's CRC + decision logic: loads the real CRC table from `dynamixel-avr/dynamixel.cpp` (lines 40–71, line-range sensitive), replicates `update_crc` and the `dynamixel_slave_poll` decisions, and checks known-good Soll CRCs, valid writes, and negatives. + 2. `sh tools/verify_slave.sh` — host-side check of the slave's CRC + decision logic: loads the real CRC table from the `crc_table[]` definition in `dynamixel-avr/dynamixel.cpp`, replicates `update_crc` and the `dynamixel_slave_poll`/callback decisions, and checks known-good Soll CRCs, valid writes, the read-reply frame, and negatives. 3. ISR sanity: `avr-objdump -d -C main.elf | sed -n '/<__vector_5>:/,/^$/p'` (PCINT2_vect = `__vector_5`). 4. busybox ash gotcha: multi-digit positional params are broken (`$10` → `$1`+"0", also inside `$(( ))`) — use `shift`/named vars in shell scripts (see `tools/verify_slave.sh`). ## Architecture (non-obvious) -- `main.c`: sleep-based loop `if (!dynamixel_rxready) sleep_mode(); dynamixel_slave_poll();` — the rxready check **before** sleeping is load-bearing (a completed packet must be processed before the CPU can sleep). +- `main.c`: owns the application logic: `slave_cmd()` (registered via `dynamixel_slave_set_cb()`) implements 1-byte-write addr 0x01 → `OCR0A = 255 - value` and read addr 0x02 → 2-byte temperature result (low byte first, or ERR=0x04 on sensor failure); returns 1 (send the status reply with the given ERR + reply bytes) or 0 (stay silent). Also calls `i2c_init()` (MLX90614 bus) and runs the sleep-based loop `if (!dynamixel_rxready) sleep_mode(); dynamixel_slave_poll();` — the rxready check **before** sleeping is load-bearing (a completed packet must be processed before the CPU can sleep). - Capture: naked `ISR(PCINT2_vect, ISR_NAKED)` in `dynamixel-avr/dynamixel.cpp` with hand-rolled SREG save/restore. PD2 = PCINT18 → `PCMSK2` (0x6D) is in memory space, so mask ops are `lds`/`andi`/`sts`, not `cbi`. Per byte: disable mask at entry, sample 8 bits using the picoUART `PURXSTART - 18`/`PURXWAIT` delays (16 MHz constants), re-arm the mask at exit so the next start bit is caught. - Capture state (all `volatile`): `dynamixel_rxindex` (buffer is 128 — `DYNAMIXEL_PACKET_SIZE` is 128, not 24), `dxl_expected` (=LEN+7, parsed from the LEN field at byte 7, only for a header-valid packet), `dxl_last_tick` (stale watchdog), `dynamixel_rxready`. - Stale watchdog: Timer1 free-running, prescaler 64 (4 µs/tick, set in `dynamixel_listen_init`); gap > 375 ticks (~1.5 ms) since the last captured byte → buffer restarts. TCNT0 (8-bit, wraps at 1.024 ms) cannot be used for this. - **Skip guard**: at ISR entry, if `rxindex >= dxl_expected`, skip the capture and just re-arm — a complete packet cannot have more start bits (the master waits for the reply; `poll()` resets state right after sending it). Load-bearing: `PU_DISABLE_IRQ=1` makes `putx()` run with `cli()`, so falling edges of our own 11-byte reply TX latch and one spurious ISR fires right after the last `putx()` byte. Without the guard the captured command is processed again and a **second reply** goes on the bus. -- `dynamixel_slave_poll()`: validates header + CRC (`update_crc`, table in `dynamixel.cpp`), ID==0x21, INS==WRITE, len==13, addr==1 → `OCR0A = value`, then replies: wait for line idle, `_delay_us(50)` turnaround, 11× `putx`. Always restores idle state afterwards: PD2 pull-up (`putx` clears it, leaving the pin floating), re-arm PCMSK2, `rxindex = 0`, `dxl_expected = DYNAMIXEL_PACKET_SIZE`. +- `dynamixel_slave_poll()`: validates header + CRC (`update_crc`, table in `dynamixel.cpp`); if the packet is addressed to `DXL_SLAVE_ID` and has a 2-byte address field (total len ≥ 12) it calls the registered callback with `(INS, param field, param_len, &err, reply, &reply_len)` (param_len = len−10; for a write the param field is `{addr_lo, addr_hi, data...}`). Callback returns 1 → send the status reply with the callback's ERR and up to `DXL_SLAVE_REPLY_MAX` (8) reply bytes — LEN field = 4+reply_len, so 11 bytes with no data, 13 for a 16-bit read (wait for line idle, `_delay_us(50)` turnaround, `putx` per byte); 0 → stay silent. Always restores idle state afterwards: PD2 pull-up (`putx` clears it, leaving the pin floating), re-arm PCMSK2, `rxindex = 0`, `dxl_expected = DYNAMIXEL_PACKET_SIZE`. +- MLX90614 IR thermometer: `mlx90614.c` reads the raw object-temperature register (`0x07`, data low byte first, then an unchecked PEC byte) over I2C (A4 SDA / A5 SCL) using the `i2c/` library (hardware TWI, 100 kHz; `i2c_init()` at boot). 7-bit address `0x5A` = the Adafruit library's default (the datasheet PDF in this folder cannot be read in this environment — if the sensor does not ACK, verify the address against the datasheet; it is a single `#define`). Conversion: °C = raw×0.02 − 273.15 ⇒ 0.1 °C = (raw−13657)/5. A failed read (NACK/bus busy) returns 0. - Timer ownership: Timer0 = LED PWM (D6, ~1 kHz; `OCR0A` doubles as the virtual servo's "value" — do not reconfigure). Timer1 = stale watchdog — do not reconfigure. picoUART timing constants assume F_CPU = 16 MHz (hardcoded in the Makefile `CDEFS`). - `dxl_packet_length()` is inline asm because -Os with GCC 15.2 dropped the high byte of the 16-bit result (see the comment in the source) — keep it in asm if touched. diff --git a/avr/nano/Makefile b/avr/nano/Makefile index d01e57d..14a463e 100644 --- a/avr/nano/Makefile +++ b/avr/nano/Makefile @@ -52,7 +52,7 @@ TARGET = main # List C source files here. (C dependencies are automatically generated.) -SRC = $(TARGET).c uart.c +SRC = $(TARGET).c uart.c mlx90614.c i2c/twimaster.c SRCPP = dynamixel-avr/dynamixel.cpp picoUART/src/picoUART.cpp # List Assembler source files here. @@ -93,7 +93,7 @@ CSTANDARD = -std=gnu99 CDEFS = -DF_CPU=16000000 # Place -I options here -CINCS = -ILib_TWI_USI_Slave_EEProm_1v3 -IpicoUART/src +CINCS = -ILib_TWI_USI_Slave_EEProm_1v3 -IpicoUART/src -Ii2c # Compiler flags. diff --git a/avr/nano/i2c/group__pfleury__ic2master.html b/avr/nano/i2c/group__pfleury__ic2master.html new file mode 100644 index 0000000..23e3f8c --- /dev/null +++ b/avr/nano/i2c/group__pfleury__ic2master.html @@ -0,0 +1,473 @@ + + +AVR-GCC libraries: I2C Master library + + + +

I2C Master library


Detailed Description

+I2C (TWI) Master Software Library. +

+

 #include <i2cmaster.h> 
+

+Basic routines for communicating with I2C slave devices. This single master implementation is limited to one bus master on the I2C bus.

+This I2c library is implemented as a compact assembler software implementation of the I2C protocol which runs on any AVR (i2cmaster.S) and as a TWI hardware interface for all AVR with built-in TWI hardware (twimaster.c). Since the API for these two implementations is exactly the same, an application can be linked either against the software I2C implementation or the hardware I2C implementation.

+Use 4.7k pull-up resistor on the SDA and SCL pin.

+Adapt the SCL and SDA port and pin definitions and eventually the delay routine in the module i2cmaster.S to your target when using the software I2C implementation !

+Adjust the CPU clock frequence F_CPU in twimaster.c or in the Makfile when using the TWI hardware implementaion.

+

Note:
The module i2cmaster.S is based on the Atmel Application Note AVR300, corrected and adapted to GNU assembler and AVR-GCC C call interface. Replaced the incorrect quarter period delays found in AVR300 with half period delays.
+
Author:
Peter Fleury pfleury@gmx.ch http://jump.to/fleury
+
API Usage Example
The following code shows typical usage of this library, see example test_i2cmaster.c
+
 #include <i2cmaster.h>
+
+
+ #define Dev24C02  0xA2      // device address of EEPROM 24C02, see datasheet
+
+ int main(void)
+ {
+     unsigned char ret;
+
+     i2c_init();                             // initialize I2C library
+
+     // write 0x75 to EEPROM address 5 (Byte Write) 
+     i2c_start_wait(Dev24C02+I2C_WRITE);     // set device address and write mode
+     i2c_write(0x05);                        // write address = 5
+     i2c_write(0x75);                        // write value 0x75 to EEPROM
+     i2c_stop();                             // set stop conditon = release bus
+
+
+     // read previously written value back from EEPROM address 5 
+     i2c_start_wait(Dev24C02+I2C_WRITE);     // set device address and write mode
+
+     i2c_write(0x05);                        // write address = 5
+     i2c_rep_start(Dev24C02+I2C_READ);       // set device address and read mode
+
+     ret = i2c_readNak();                    // read one byte from EEPROM
+     i2c_stop();
+
+     for(;;);
+ }
+
+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Defines

#define I2C_READ   1
#define I2C_WRITE   0
+#define i2c_read(ack)   (ack) ? i2c_readAck() : i2c_readNak();

Functions

void i2c_init (void)
 initialize the I2C master interace. Need to be called only once
void i2c_stop (void)
 Terminates the data transfer and releases the I2C bus.
unsigned char i2c_start (unsigned char addr)
 Issues a start condition and sends address and transfer direction.
unsigned char i2c_rep_start (unsigned char addr)
 Issues a repeated start condition and sends address and transfer direction.
void i2c_start_wait (unsigned char addr)
 Issues a start condition and sends address and transfer direction.
unsigned char i2c_write (unsigned char data)
 Send one byte to I2C device.
unsigned char i2c_readAck (void)
 read one byte from the I2C device, request more data from device
unsigned char i2c_readNak (void)
 read one byte from the I2C device, read is followed by a stop condition
unsigned char i2c_read (unsigned char ack)
 read one byte from the I2C device
+


Define Documentation

+

+ + + + +
+ + + + +
#define I2C_READ   1
+
+ + + + + +
+   + + +

+defines the data direction (reading from I2C device) in i2c_start(),i2c_rep_start()

+

+ + + + +
+ + + + +
#define I2C_WRITE   0
+
+ + + + + +
+   + + +

+defines the data direction (writing to I2C device) in i2c_start(),i2c_rep_start()

+


Function Documentation

+

+ + + + +
+ + + + + + + + + +
void i2c_init ( void   ) 
+
+ + + + + +
+   + + +

+initialize the I2C master interace. Need to be called only once +

+

Parameters:
+ + +
void 
+
+
Returns:
none
+
+

+ + + + +
+ + + + + + + + + +
void i2c_stop ( void   ) 
+
+ + + + + +
+   + + +

+Terminates the data transfer and releases the I2C bus. +

+

Parameters:
+ + +
void 
+
+
Returns:
none
+
+

+ + + + +
+ + + + + + + + + +
unsigned char i2c_start ( unsigned char  addr  ) 
+
+ + + + + +
+   + + +

+Issues a start condition and sends address and transfer direction. +

+

Parameters:
+ + +
addr address and transfer direction of I2C device
+
+
Return values:
+ + + +
0 device accessible
1 failed to access device
+
+
+

+ + + + +
+ + + + + + + + + +
unsigned char i2c_rep_start ( unsigned char  addr  ) 
+
+ + + + + +
+   + + +

+Issues a repeated start condition and sends address and transfer direction. +

+

Parameters:
+ + +
addr address and transfer direction of I2C device
+
+
Return values:
+ + + +
0 device accessible
1 failed to access device
+
+
+

+ + + + +
+ + + + + + + + + +
void i2c_start_wait ( unsigned char  addr  ) 
+
+ + + + + +
+   + + +

+Issues a start condition and sends address and transfer direction. +

+If device is busy, use ack polling to wait until device ready

Parameters:
+ + +
addr address and transfer direction of I2C device
+
+
Returns:
none
+
+

+ + + + +
+ + + + + + + + + +
unsigned char i2c_write ( unsigned char  data  ) 
+
+ + + + + +
+   + + +

+Send one byte to I2C device. +

+

Parameters:
+ + +
data byte to be transfered
+
+
Return values:
+ + + +
0 write successful
1 write failed
+
+
+

+ + + + +
+ + + + + + + + + +
unsigned char i2c_readAck ( void   ) 
+
+ + + + + +
+   + + +

+read one byte from the I2C device, request more data from device +

+

Returns:
byte read from I2C device
+
+

+ + + + +
+ + + + + + + + + +
unsigned char i2c_readNak ( void   ) 
+
+ + + + + +
+   + + +

+read one byte from the I2C device, read is followed by a stop condition +

+

Returns:
byte read from I2C device
+
+

+ + + + +
+ + + + + + + + + +
unsigned char i2c_read ( unsigned char  ack  ) 
+
+ + + + + +
+   + + +

+read one byte from the I2C device +

+Implemented as a macro, which calls either i2c_readAck or i2c_readNak

+

Parameters:
+ + +
ack 1 send ack, request more data from device
+ 0 send nak, read is followed by a stop condition
+
+
Returns:
byte read from I2C device
+
+


Generated on Tue Mar 29 16:54:08 2005 for AVR-GCC libraries by  + +doxygen 1.4.1
+ + diff --git a/avr/nano/i2c/i2cmaster.S b/avr/nano/i2c/i2cmaster.S new file mode 100644 index 0000000..82652f3 --- /dev/null +++ b/avr/nano/i2c/i2cmaster.S @@ -0,0 +1,298 @@ +;************************************************************************* +; Title : I2C (Single) Master Implementation +; Author: Peter Fleury http://jump.to/fleury +; based on Atmel Appl. Note AVR300 +; File: $Id: i2cmaster.S,v 1.11 2003/10/16 18:16:07 peter Exp $ +; Software: AVR-GCC 3.3 +; Target: any AVR device +; +; DESCRIPTION +; Basic routines for communicating with I2C slave devices. This +; "single" master implementation is limited to one bus master on the +; I2C bus. +; +; Based on the Atmel Application Note AVR300, corrected and adapted +; to GNU assembler and AVR-GCC C call interface +; Replaced the incorrect quarter period delays found in AVR300 with +; half period delays. +; +; USAGE +; These routines can be called from C, refere to file i2cmaster.h. +; See example test_i2cmaster.c +; Adapt the SCL and SDA port and pin definitions and eventually +; the delay routine to your target ! +; Use 4.7k pull-up resistor on the SDA and SCL pin. +; +; NOTES +; The I2C routines can be called either from non-interrupt or +; interrupt routines, not both. +; +;************************************************************************* + +#if (__GNUC__ * 100 + __GNUC_MINOR__) < 303 +#error "This library requires AVR-GCC 3.3 or later, update to newer AVR-GCC compiler !" +#endif + + +#include + + + +;***** Adapt these SCA and SCL port and pin definition to your target !! +; +#define SDA 4 // SDA Port D, Pin 4 +#define SCL 5 // SCL Port D, Pin 5 +#define SDA_PORT PORTD // SDA Port D +#define SCL_PORT PORTD // SCL Port D + +;****** + +;-- map the IO register back into the IO address space +#define SDA_DDR (_SFR_IO_ADDR(SDA_PORT) - 1) +#define SCL_DDR (_SFR_IO_ADDR(SCL_PORT) - 1) +#define SDA_OUT _SFR_IO_ADDR(SDA_PORT) +#define SCL_OUT _SFR_IO_ADDR(SCL_PORT) +#define SDA_IN (_SFR_IO_ADDR(SDA_PORT) - 2) +#define SCL_IN (_SFR_IO_ADDR(SCL_PORT) - 2) + + +#ifndef __tmp_reg__ +#define __tmp_reg__ 0 +#endif + + + .section .text + +;************************************************************************* +; delay half period +; For I2C in normal mode (100kHz), use T/2 > 5us +; For I2C in fast mode (400kHz), use T/2 > 1.3us +;************************************************************************* + .stabs "",100,0,0,i2c_delay_T2 + .stabs "i2cmaster.S",100,0,0,i2c_delay_T2 + .func i2c_delay_T2 ; delay 5.0 microsec with 4 Mhz crystal +i2c_delay_T2: ; 4 cycles + rjmp 1f ; 2 " +1: rjmp 2f ; 2 " +2: rjmp 3f ; 2 " +3: rjmp 4f ; 2 " +4: rjmp 5f ; 2 " +5: rjmp 6f ; 2 " +6: nop ; 1 " + ret ; 3 " + .endfunc ; total 20 cyles = 5.0 microsec with 4 Mhz crystal + + +;************************************************************************* +; Initialization of the I2C bus interface. Need to be called only once +; +; extern void i2c_init(void) +;************************************************************************* + .global i2c_init + .func i2c_init +i2c_init: + cbi SDA_DDR,SDA ;release SDA + cbi SCL_DDR,SCL ;release SCL + cbi SDA_OUT,SDA + cbi SCL_OUT,SCL + ret + .endfunc + + +;************************************************************************* +; Issues a start condition and sends address and transfer direction. +; return 0 = device accessible, 1= failed to access device +; +; extern unsigned char i2c_start(unsigned char addr); +; addr = r24, return = r25(=0):r24 +;************************************************************************* + + .global i2c_start + .func i2c_start +i2c_start: + sbi SDA_DDR,SDA ;force SDA low + rcall i2c_delay_T2 ;delay T/2 + + rcall i2c_write ;write address + ret + .endfunc + + +;************************************************************************* +; Issues a repeated start condition and sends address and transfer direction. +; return 0 = device accessible, 1= failed to access device +; +; extern unsigned char i2c_rep_start(unsigned char addr); +; addr = r24, return = r25(=0):r24 +;************************************************************************* + + .global i2c_rep_start + .func i2c_rep_start +i2c_rep_start: + sbi SCL_DDR,SCL ;force SCL low + rcall i2c_delay_T2 ;delay T/2 + cbi SDA_DDR,SDA ;release SDA + rcall i2c_delay_T2 ;delay T/2 + cbi SCL_DDR,SCL ;release SCL + rcall i2c_delay_T2 ;delay T/2 + sbi SDA_DDR,SDA ;force SDA low + rcall i2c_delay_T2 ;delay T/2 + + rcall i2c_write ;write address + ret + .endfunc + + +;************************************************************************* +; Issues a start condition and sends address and transfer direction. +; If device is busy, use ack polling to wait until device is ready +; +; extern void i2c_start_wait(unsigned char addr); +; addr = r24 +;************************************************************************* + + .global i2c_start_wait + .func i2c_start_wait +i2c_start_wait: + mov __tmp_reg__,r24 +i2c_start_wait1: + sbi SDA_DDR,SDA ;force SDA low + rcall i2c_delay_T2 ;delay T/2 + mov r24,__tmp_reg__ + rcall i2c_write ;write address + tst r24 ;if device not busy -> done + breq i2c_start_wait_done + rcall i2c_stop ;terminate write operation + rjmp i2c_start_wait1 ;device busy, poll ack again +i2c_start_wait_done: + ret + .endfunc + + +;************************************************************************* +; Terminates the data transfer and releases the I2C bus +; +; extern void i2c_stop(void) +;************************************************************************* + + .global i2c_stop + .func i2c_stop +i2c_stop: + sbi SCL_DDR,SCL ;force SCL low + sbi SDA_DDR,SDA ;force SDA low + rcall i2c_delay_T2 ;delay T/2 + cbi SCL_DDR,SCL ;release SCL + rcall i2c_delay_T2 ;delay T/2 + cbi SDA_DDR,SDA ;release SDA + rcall i2c_delay_T2 ;delay T/2 + ret + .endfunc + + +;************************************************************************* +; Send one byte to I2C device +; return 0 = write successful, 1 = write failed +; +; extern unsigned char i2c_write( unsigned char data ); +; data = r24, return = r25(=0):r24 +;************************************************************************* + .global i2c_write + .func i2c_write +i2c_write: + sec ;set carry flag + rol r24 ;shift in carry and out bit one + rjmp i2c_write_first +i2c_write_bit: + lsl r24 ;if transmit register empty +i2c_write_first: + breq i2c_get_ack + sbi SCL_DDR,SCL ;force SCL low + brcc i2c_write_low + nop + cbi SDA_DDR,SDA ;release SDA + rjmp i2c_write_high +i2c_write_low: + sbi SDA_DDR,SDA ;force SDA low + rjmp i2c_write_high +i2c_write_high: + rcall i2c_delay_T2 ;delay T/2 + cbi SCL_DDR,SCL ;release SCL + rcall i2c_delay_T2 ;delay T/2 + rjmp i2c_write_bit + +i2c_get_ack: + sbi SCL_DDR,SCL ;force SCL low + cbi SDA_DDR,SDA ;release SDA + rcall i2c_delay_T2 ;delay T/2 + cbi SCL_DDR,SCL ;release SCL +i2c_ack_wait: + sbis SCL_IN,SCL ;wait SCL high (in case wait states are inserted) + rjmp i2c_ack_wait + + clr r24 ;return 0 + sbic SDA_IN,SDA ;if SDA high -> return 1 + ldi r24,1 + rcall i2c_delay_T2 ;delay T/2 + clr r25 + ret + .endfunc + + + +;************************************************************************* +; read one byte from the I2C device, send ack or nak to device +; (ack=1, send ack, request more data from device +; ack=0, send nak, read is followed by a stop condition) +; +; extern unsigned char i2c_read(unsigned char ack); +; ack = r24, return = r25(=0):r24 +; extern unsigned char i2c_readAck(void); +; extern unsigned char i2c_readNak(void); +; return = r25(=0):r24 +;************************************************************************* + .global i2c_readAck + .global i2c_readNak + .global i2c_read + .func i2c_read +i2c_readNak: + clr r24 + rjmp i2c_read +i2c_readAck: + ldi r24,0x01 +i2c_read: + ldi r23,0x01 ;data = 0x01 +i2c_read_bit: + sbi SCL_DDR,SCL ;force SCL low + cbi SDA_DDR,SDA ;release SDA (from previous ACK) + rcall i2c_delay_T2 ;delay T/2 + + cbi SCL_DDR,SCL ;release SCL + rcall i2c_delay_T2 ;delay T/2 + + clc ;clear carry flag + sbic SDA_IN,SDA ;if SDA is high + sec ; set carry flag + + rol r23 ;store bit + brcc i2c_read_bit ;while receive register not full + +i2c_put_ack: + sbi SCL_DDR,SCL ;force SCL low + cpi r24,1 + breq i2c_put_ack_low ;if (ack=0) + cbi SDA_DDR,SDA ; release SDA + rjmp i2c_put_ack_high +i2c_put_ack_low: ;else + sbi SDA_DDR,SDA ; force SDA low +i2c_put_ack_high: + rcall i2c_delay_T2 ;delay T/2 + cbi SCL_DDR,SCL ;release SCL +i2c_put_ack_wait: + sbis SCL_IN,SCL ;wait SCL high + rjmp i2c_put_ack_wait + rcall i2c_delay_T2 ;delay T/2 + mov r24,r23 + clr r25 + ret + .endfunc + diff --git a/avr/nano/i2c/i2cmaster.h b/avr/nano/i2c/i2cmaster.h new file mode 100644 index 0000000..70f51fd --- /dev/null +++ b/avr/nano/i2c/i2cmaster.h @@ -0,0 +1,178 @@ +#ifndef _I2CMASTER_H +#define _I2CMASTER_H 1 +/************************************************************************* +* Title: C include file for the I2C master interface +* (i2cmaster.S or twimaster.c) +* Author: Peter Fleury http://jump.to/fleury +* File: $Id: i2cmaster.h,v 1.10 2005/03/06 22:39:57 Peter Exp $ +* Software: AVR-GCC 3.4.3 / avr-libc 1.2.3 +* Target: any AVR device +* Usage: see Doxygen manual +**************************************************************************/ + +#ifdef DOXYGEN +/** + @defgroup pfleury_ic2master I2C Master library + @code #include @endcode + + @brief I2C (TWI) Master Software Library + + Basic routines for communicating with I2C slave devices. This single master + implementation is limited to one bus master on the I2C bus. + + This I2c library is implemented as a compact assembler software implementation of the I2C protocol + which runs on any AVR (i2cmaster.S) and as a TWI hardware interface for all AVR with built-in TWI hardware (twimaster.c). + Since the API for these two implementations is exactly the same, an application can be linked either against the + software I2C implementation or the hardware I2C implementation. + + Use 4.7k pull-up resistor on the SDA and SCL pin. + + Adapt the SCL and SDA port and pin definitions and eventually the delay routine in the module + i2cmaster.S to your target when using the software I2C implementation ! + + Adjust the CPU clock frequence F_CPU in twimaster.c or in the Makfile when using the TWI hardware implementaion. + + @note + The module i2cmaster.S is based on the Atmel Application Note AVR300, corrected and adapted + to GNU assembler and AVR-GCC C call interface. + Replaced the incorrect quarter period delays found in AVR300 with + half period delays. + + @author Peter Fleury pfleury@gmx.ch http://jump.to/fleury + + @par API Usage Example + The following code shows typical usage of this library, see example test_i2cmaster.c + + @code + + #include + + + #define Dev24C02 0xA2 // device address of EEPROM 24C02, see datasheet + + int main(void) + { + unsigned char ret; + + i2c_init(); // initialize I2C library + + // write 0x75 to EEPROM address 5 (Byte Write) + i2c_start_wait(Dev24C02+I2C_WRITE); // set device address and write mode + i2c_write(0x05); // write address = 5 + i2c_write(0x75); // write value 0x75 to EEPROM + i2c_stop(); // set stop conditon = release bus + + + // read previously written value back from EEPROM address 5 + i2c_start_wait(Dev24C02+I2C_WRITE); // set device address and write mode + + i2c_write(0x05); // write address = 5 + i2c_rep_start(Dev24C02+I2C_READ); // set device address and read mode + + ret = i2c_readNak(); // read one byte from EEPROM + i2c_stop(); + + for(;;); + } + @endcode + +*/ +#endif /* DOXYGEN */ + +/**@{*/ + +#if (__GNUC__ * 100 + __GNUC_MINOR__) < 304 +#error "This library requires AVR-GCC 3.4 or later, update to newer AVR-GCC compiler !" +#endif + +#include + +/** defines the data direction (reading from I2C device) in i2c_start(),i2c_rep_start() */ +#define I2C_READ 1 + +/** defines the data direction (writing to I2C device) in i2c_start(),i2c_rep_start() */ +#define I2C_WRITE 0 + + +/** + @brief initialize the I2C master interace. Need to be called only once + @param void + @return none + */ +extern void i2c_init(void); + + +/** + @brief Terminates the data transfer and releases the I2C bus + @param void + @return none + */ +extern void i2c_stop(void); + + +/** + @brief Issues a start condition and sends address and transfer direction + + @param addr address and transfer direction of I2C device + @retval 0 device accessible + @retval 1 failed to access device + */ +extern unsigned char i2c_start(unsigned char addr); + + +/** + @brief Issues a repeated start condition and sends address and transfer direction + + @param addr address and transfer direction of I2C device + @retval 0 device accessible + @retval 1 failed to access device + */ +extern unsigned char i2c_rep_start(unsigned char addr); + + +/** + @brief Issues a start condition and sends address and transfer direction + + If device is busy, use ack polling to wait until device ready + @param addr address and transfer direction of I2C device + @return none + */ +extern void i2c_start_wait(unsigned char addr); + + +/** + @brief Send one byte to I2C device + @param data byte to be transfered + @retval 0 write successful + @retval 1 write failed + */ +extern unsigned char i2c_write(unsigned char data); + + +/** + @brief read one byte from the I2C device, request more data from device + @return byte read from I2C device + */ +extern unsigned char i2c_readAck(void); + +/** + @brief read one byte from the I2C device, read is followed by a stop condition + @return byte read from I2C device + */ +extern unsigned char i2c_readNak(void); + +/** + @brief read one byte from the I2C device + + Implemented as a macro, which calls either i2c_readAck or i2c_readNak + + @param ack 1 send ack, request more data from device
+ 0 send nak, read is followed by a stop condition + @return byte read from I2C device + */ +extern unsigned char i2c_read(unsigned char ack); +#define i2c_read(ack) (ack) ? i2c_readAck() : i2c_readNak(); + + +/**@}*/ +#endif diff --git a/avr/nano/i2c/makefile b/avr/nano/i2c/makefile new file mode 100644 index 0000000..c8206b8 --- /dev/null +++ b/avr/nano/i2c/makefile @@ -0,0 +1,392 @@ +# Makefile to compile and link the I2C Master library and test program +# +# based on +# WinAVR Sample makefile written by Eric B. Weddington, Jörg Wunsch, et al. +# +# Note: +# The warnings which appear while converting ELF to AVR Extended COFF (make extcoff) +# can be ignored +# +# +# On command line: +# +# make all = Make software. +# +# make clean = Clean out built project files. +# +# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB). +# +# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio +# 4.07 or greater). +# +# make program = Download the hex file to the device, using avrdude. Please +# customize the avrdude settings below first! +# +# make filename.s = Just compile filename.c into the assembler code only +# +# To rebuild project do "make clean" then "make all". +# + + +# MCU name +MCU = at90s8515 + +# Output format. (can be srec, ihex, binary) +FORMAT = ihex + +# Optimization level, can be [0, 1, 2, 3, s]. 0 turns off optimization. +# (Note: 3 is not always the best optimization level. See avr-libc FAQ.) +OPT = s + + +# Target file name (without extension). +TARGET = test_i2cmaster + + +# List C source files here. (C dependencies are automatically generated.) +SRC = $(TARGET).c + +# List Assembler source files here. +# Make them always end in a capital .S. Files ending in a lowercase .s +# will not be considered source files but generated files (assembler +# output from the compiler), and will be deleted upon "make clean"! +# Even though the DOS/Win* filesystem matches both .s and .S the same, +# it will preserve the spelling of the filenames, and gcc itself does +# care about how the name is spelled on its command-line. +ASRC = i2cmaster.S + + +# List any extra directories to look for include files here. +# Each directory must be seperated by a space. +EXTRAINCDIRS = + + +# Optional compiler flags. +# -g: generate debugging information (for GDB, or for COFF conversion) +# -O*: optimization level +# -f...: tuning, see gcc manual and avr-libc documentation +# -Wall...: warning level +# -Wa,...: tell GCC to pass this to the assembler. +# -ahlms: create assembler listing +CFLAGS = -g -O$(OPT) \ +-funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums \ +-Wall -Wstrict-prototypes \ +-Wa,-adhlns=$(<:.c=.lst) \ +$(patsubst %,-I%,$(EXTRAINCDIRS)) + + +# Set a "language standard" compiler flag. +# Unremark just one line below to set the language standard to use. +# gnu99 = C99 + GNU extensions. See GCC manual for more information. +#CFLAGS += -std=c89 +#CFLAGS += -std=gnu89 +#CFLAGS += -std=c99 +CFLAGS += -std=gnu99 + + + +# Optional assembler flags. +# -Wa,...: tell GCC to pass this to the assembler. +# -ahlms: create listing +# -gstabs: have the assembler create line number information; note that +# for use in COFF files, additional information about filenames +# and function names needs to be present in the assembler source +# files -- see avr-libc docs [FIXME: not yet described there] +ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs + + + +# Optional linker flags. +# -Wl,...: tell GCC to pass this to linker. +# -Map: create map file +# --cref: add cross reference to map file +LDFLAGS = -Wl,-Map=$(TARGET).map,--cref + + + +# Additional libraries + +# Minimalistic printf version +#LDFLAGS += -Wl,-u,vfprintf -lprintf_min + +# Floating point printf version (requires -lm below) +#LDFLAGS += -Wl,-u,vfprintf -lprintf_flt + +# -lm = math library +LDFLAGS += -lm + + + + +# Programming support using avrdude. Settings and variables. + +# Programming hardware: alf avr910 avrisp bascom bsd +# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500 +# +# Type: avrdude -c ? +# to get a full listing. +# +AVRDUDE_PROGRAMMER = stk500 + + +AVRDUDE_PORT = com1 # programmer connected to serial device +#AVRDUDE_PORT = lpt1 # programmer connected to parallel port + +AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex +#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep + +AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) + +# Uncomment the following if you want avrdude's erase cycle counter. +# Note that this counter needs to be initialized first using -Yn, +# see avrdude manual. +#AVRDUDE_ERASE += -y + +# Uncomment the following if you do /not/ wish a verification to be +# performed after programming the device. +#AVRDUDE_FLAGS += -V + +# Increase verbosity level. Please use this when submitting bug +# reports about avrdude. See +# to submit bug reports. +#AVRDUDE_FLAGS += -v -v + + + + +# --------------------------------------------------------------------------- + +# Define directories, if needed. +DIRAVR = c:/winavr +DIRAVRBIN = $(DIRAVR)/bin +DIRAVRUTILS = $(DIRAVR)/utils/bin +DIRINC = . +DIRLIB = $(DIRAVR)/avr/lib + + +# Define programs and commands. +SHELL = sh + +CC = avr-gcc + +OBJCOPY = avr-objcopy +OBJDUMP = avr-objdump +SIZE = avr-size + + +# Programming support using avrdude. +AVRDUDE = avrdude + + +REMOVE = rm -f +COPY = cp + +HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex +ELFSIZE = $(SIZE) -A $(TARGET).elf + + + +# Define Messages +# English +MSG_ERRORS_NONE = Errors: none +MSG_BEGIN = -------- begin -------- +MSG_END = -------- end -------- +MSG_SIZE_BEFORE = Size before: +MSG_SIZE_AFTER = Size after: +MSG_COFF = Converting to AVR COFF: +MSG_EXTENDED_COFF = Converting to AVR Extended COFF: +MSG_FLASH = Creating load file for Flash: +MSG_EEPROM = Creating load file for EEPROM: +MSG_EXTENDED_LISTING = Creating Extended Listing: +MSG_SYMBOL_TABLE = Creating Symbol Table: +MSG_LINKING = Linking: +MSG_COMPILING = Compiling: +MSG_ASSEMBLING = Assembling: +MSG_CLEANING = Cleaning project: + + + + +# Define all object files. +OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) + +# Define all listing files. +LST = $(ASRC:.S=.lst) $(SRC:.c=.lst) + +# Combine all necessary flags and optional flags. +# Add target processor to flags. +ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) +ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) + + + +# Default target. +all: begin gccversion sizebefore $(TARGET).elf $(TARGET).hex $(TARGET).eep \ + $(TARGET).lss $(TARGET).sym sizeafter finished end + + +# Eye candy. +# AVR Studio 3.x does not check make's exit code but relies on +# the following magic strings to be generated by the compile job. +begin: + @echo + @echo $(MSG_BEGIN) + +finished: + @echo $(MSG_ERRORS_NONE) + +end: + @echo $(MSG_END) + @echo + + +# Display size of file. +sizebefore: + @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); echo; fi + +sizeafter: + @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi + + + +# Display compiler version information. +gccversion : + @$(CC) --version + + + + +# Convert ELF to COFF for use in debugging / simulating in +# AVR Studio or VMLAB. +COFFCONVERT=$(OBJCOPY) --debugging \ + --change-section-address .data-0x800000 \ + --change-section-address .bss-0x800000 \ + --change-section-address .noinit-0x800000 \ + --change-section-address .eeprom-0x810000 + + +coff: $(TARGET).elf + @echo + @echo $(MSG_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-avr $< $(TARGET).cof + + +extcoff: $(TARGET).elf + @echo + @echo $(MSG_EXTENDED_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof + + + + +# Program the device. +program: $(TARGET).hex $(TARGET).eep + $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM) + + + + +# Create final output files (.hex, .eep) from ELF output file. +%.hex: %.elf + @echo + @echo $(MSG_FLASH) $@ + $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ + +%.eep: %.elf + @echo + @echo $(MSG_EEPROM) $@ + -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ + --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ + +# Create extended listing file from ELF output file. +%.lss: %.elf + @echo + @echo $(MSG_EXTENDED_LISTING) $@ + $(OBJDUMP) -h -S $< > $@ + +# Create a symbol table from ELF output file. +%.sym: %.elf + @echo + @echo $(MSG_SYMBOL_TABLE) $@ + avr-nm -n $< > $@ + + + +# Link: create ELF output file from object files. +.SECONDARY : $(TARGET).elf +.PRECIOUS : $(OBJ) +%.elf: $(OBJ) + @echo + @echo $(MSG_LINKING) $@ + $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) + + +# Compile: create object files from C source files. +%.o : %.c + @echo + @echo $(MSG_COMPILING) $< + $(CC) -c $(ALL_CFLAGS) $< -o $@ + + +# Compile: create assembler files from C source files. +%.s : %.c + $(CC) -S $(ALL_CFLAGS) $< -o $@ + + +# Assemble: create object files from assembler source files. +%.o : %.S + @echo + @echo $(MSG_ASSEMBLING) $< + $(CC) -c $(ALL_ASFLAGS) $< -o $@ + + + + + + +# Target: clean project. +clean: begin clean_list finished end + +clean_list : + @echo + @echo $(MSG_CLEANING) + $(REMOVE) $(TARGET).hex + $(REMOVE) $(TARGET).eep + $(REMOVE) $(TARGET).obj + $(REMOVE) $(TARGET).cof + $(REMOVE) $(TARGET).elf + $(REMOVE) $(TARGET).map + $(REMOVE) $(TARGET).obj + $(REMOVE) $(TARGET).a90 + $(REMOVE) $(TARGET).sym + $(REMOVE) $(TARGET).lnk + $(REMOVE) $(TARGET).lss + $(REMOVE) $(OBJ) + $(REMOVE) $(LST) + $(REMOVE) $(SRC:.c=.s) + $(REMOVE) $(SRC:.c=.d) + + +# Automatically generate C source code dependencies. +# (Code originally taken from the GNU make user manual and modified +# (See README.txt Credits).) +# +# Note that this will work with sh (bash) and sed that is shipped with WinAVR +# (see the SHELL variable defined above). +# This may not work with other shells or other seds. +# +%.d: %.c + set -e; $(CC) -MM $(ALL_CFLAGS) $< \ + | sed 's,\(.*\)\.o[ :]*,\1.o \1.d : ,g' > $@; \ + [ -s $@ ] || rm -f $@ + + +# Remove the '-' if you want to see the dependency files generated. +-include $(SRC:.c=.d) + + + +# Listing of phony targets. +.PHONY : all begin finish end sizebefore sizeafter gccversion coff extcoff \ + clean clean_list program + diff --git a/avr/nano/i2c/makefile.i2cmaster b/avr/nano/i2c/makefile.i2cmaster new file mode 100644 index 0000000..c8206b8 --- /dev/null +++ b/avr/nano/i2c/makefile.i2cmaster @@ -0,0 +1,392 @@ +# Makefile to compile and link the I2C Master library and test program +# +# based on +# WinAVR Sample makefile written by Eric B. Weddington, Jörg Wunsch, et al. +# +# Note: +# The warnings which appear while converting ELF to AVR Extended COFF (make extcoff) +# can be ignored +# +# +# On command line: +# +# make all = Make software. +# +# make clean = Clean out built project files. +# +# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB). +# +# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio +# 4.07 or greater). +# +# make program = Download the hex file to the device, using avrdude. Please +# customize the avrdude settings below first! +# +# make filename.s = Just compile filename.c into the assembler code only +# +# To rebuild project do "make clean" then "make all". +# + + +# MCU name +MCU = at90s8515 + +# Output format. (can be srec, ihex, binary) +FORMAT = ihex + +# Optimization level, can be [0, 1, 2, 3, s]. 0 turns off optimization. +# (Note: 3 is not always the best optimization level. See avr-libc FAQ.) +OPT = s + + +# Target file name (without extension). +TARGET = test_i2cmaster + + +# List C source files here. (C dependencies are automatically generated.) +SRC = $(TARGET).c + +# List Assembler source files here. +# Make them always end in a capital .S. Files ending in a lowercase .s +# will not be considered source files but generated files (assembler +# output from the compiler), and will be deleted upon "make clean"! +# Even though the DOS/Win* filesystem matches both .s and .S the same, +# it will preserve the spelling of the filenames, and gcc itself does +# care about how the name is spelled on its command-line. +ASRC = i2cmaster.S + + +# List any extra directories to look for include files here. +# Each directory must be seperated by a space. +EXTRAINCDIRS = + + +# Optional compiler flags. +# -g: generate debugging information (for GDB, or for COFF conversion) +# -O*: optimization level +# -f...: tuning, see gcc manual and avr-libc documentation +# -Wall...: warning level +# -Wa,...: tell GCC to pass this to the assembler. +# -ahlms: create assembler listing +CFLAGS = -g -O$(OPT) \ +-funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums \ +-Wall -Wstrict-prototypes \ +-Wa,-adhlns=$(<:.c=.lst) \ +$(patsubst %,-I%,$(EXTRAINCDIRS)) + + +# Set a "language standard" compiler flag. +# Unremark just one line below to set the language standard to use. +# gnu99 = C99 + GNU extensions. See GCC manual for more information. +#CFLAGS += -std=c89 +#CFLAGS += -std=gnu89 +#CFLAGS += -std=c99 +CFLAGS += -std=gnu99 + + + +# Optional assembler flags. +# -Wa,...: tell GCC to pass this to the assembler. +# -ahlms: create listing +# -gstabs: have the assembler create line number information; note that +# for use in COFF files, additional information about filenames +# and function names needs to be present in the assembler source +# files -- see avr-libc docs [FIXME: not yet described there] +ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs + + + +# Optional linker flags. +# -Wl,...: tell GCC to pass this to linker. +# -Map: create map file +# --cref: add cross reference to map file +LDFLAGS = -Wl,-Map=$(TARGET).map,--cref + + + +# Additional libraries + +# Minimalistic printf version +#LDFLAGS += -Wl,-u,vfprintf -lprintf_min + +# Floating point printf version (requires -lm below) +#LDFLAGS += -Wl,-u,vfprintf -lprintf_flt + +# -lm = math library +LDFLAGS += -lm + + + + +# Programming support using avrdude. Settings and variables. + +# Programming hardware: alf avr910 avrisp bascom bsd +# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500 +# +# Type: avrdude -c ? +# to get a full listing. +# +AVRDUDE_PROGRAMMER = stk500 + + +AVRDUDE_PORT = com1 # programmer connected to serial device +#AVRDUDE_PORT = lpt1 # programmer connected to parallel port + +AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex +#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep + +AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) + +# Uncomment the following if you want avrdude's erase cycle counter. +# Note that this counter needs to be initialized first using -Yn, +# see avrdude manual. +#AVRDUDE_ERASE += -y + +# Uncomment the following if you do /not/ wish a verification to be +# performed after programming the device. +#AVRDUDE_FLAGS += -V + +# Increase verbosity level. Please use this when submitting bug +# reports about avrdude. See +# to submit bug reports. +#AVRDUDE_FLAGS += -v -v + + + + +# --------------------------------------------------------------------------- + +# Define directories, if needed. +DIRAVR = c:/winavr +DIRAVRBIN = $(DIRAVR)/bin +DIRAVRUTILS = $(DIRAVR)/utils/bin +DIRINC = . +DIRLIB = $(DIRAVR)/avr/lib + + +# Define programs and commands. +SHELL = sh + +CC = avr-gcc + +OBJCOPY = avr-objcopy +OBJDUMP = avr-objdump +SIZE = avr-size + + +# Programming support using avrdude. +AVRDUDE = avrdude + + +REMOVE = rm -f +COPY = cp + +HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex +ELFSIZE = $(SIZE) -A $(TARGET).elf + + + +# Define Messages +# English +MSG_ERRORS_NONE = Errors: none +MSG_BEGIN = -------- begin -------- +MSG_END = -------- end -------- +MSG_SIZE_BEFORE = Size before: +MSG_SIZE_AFTER = Size after: +MSG_COFF = Converting to AVR COFF: +MSG_EXTENDED_COFF = Converting to AVR Extended COFF: +MSG_FLASH = Creating load file for Flash: +MSG_EEPROM = Creating load file for EEPROM: +MSG_EXTENDED_LISTING = Creating Extended Listing: +MSG_SYMBOL_TABLE = Creating Symbol Table: +MSG_LINKING = Linking: +MSG_COMPILING = Compiling: +MSG_ASSEMBLING = Assembling: +MSG_CLEANING = Cleaning project: + + + + +# Define all object files. +OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) + +# Define all listing files. +LST = $(ASRC:.S=.lst) $(SRC:.c=.lst) + +# Combine all necessary flags and optional flags. +# Add target processor to flags. +ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) +ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) + + + +# Default target. +all: begin gccversion sizebefore $(TARGET).elf $(TARGET).hex $(TARGET).eep \ + $(TARGET).lss $(TARGET).sym sizeafter finished end + + +# Eye candy. +# AVR Studio 3.x does not check make's exit code but relies on +# the following magic strings to be generated by the compile job. +begin: + @echo + @echo $(MSG_BEGIN) + +finished: + @echo $(MSG_ERRORS_NONE) + +end: + @echo $(MSG_END) + @echo + + +# Display size of file. +sizebefore: + @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); echo; fi + +sizeafter: + @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi + + + +# Display compiler version information. +gccversion : + @$(CC) --version + + + + +# Convert ELF to COFF for use in debugging / simulating in +# AVR Studio or VMLAB. +COFFCONVERT=$(OBJCOPY) --debugging \ + --change-section-address .data-0x800000 \ + --change-section-address .bss-0x800000 \ + --change-section-address .noinit-0x800000 \ + --change-section-address .eeprom-0x810000 + + +coff: $(TARGET).elf + @echo + @echo $(MSG_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-avr $< $(TARGET).cof + + +extcoff: $(TARGET).elf + @echo + @echo $(MSG_EXTENDED_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof + + + + +# Program the device. +program: $(TARGET).hex $(TARGET).eep + $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM) + + + + +# Create final output files (.hex, .eep) from ELF output file. +%.hex: %.elf + @echo + @echo $(MSG_FLASH) $@ + $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ + +%.eep: %.elf + @echo + @echo $(MSG_EEPROM) $@ + -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ + --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ + +# Create extended listing file from ELF output file. +%.lss: %.elf + @echo + @echo $(MSG_EXTENDED_LISTING) $@ + $(OBJDUMP) -h -S $< > $@ + +# Create a symbol table from ELF output file. +%.sym: %.elf + @echo + @echo $(MSG_SYMBOL_TABLE) $@ + avr-nm -n $< > $@ + + + +# Link: create ELF output file from object files. +.SECONDARY : $(TARGET).elf +.PRECIOUS : $(OBJ) +%.elf: $(OBJ) + @echo + @echo $(MSG_LINKING) $@ + $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) + + +# Compile: create object files from C source files. +%.o : %.c + @echo + @echo $(MSG_COMPILING) $< + $(CC) -c $(ALL_CFLAGS) $< -o $@ + + +# Compile: create assembler files from C source files. +%.s : %.c + $(CC) -S $(ALL_CFLAGS) $< -o $@ + + +# Assemble: create object files from assembler source files. +%.o : %.S + @echo + @echo $(MSG_ASSEMBLING) $< + $(CC) -c $(ALL_ASFLAGS) $< -o $@ + + + + + + +# Target: clean project. +clean: begin clean_list finished end + +clean_list : + @echo + @echo $(MSG_CLEANING) + $(REMOVE) $(TARGET).hex + $(REMOVE) $(TARGET).eep + $(REMOVE) $(TARGET).obj + $(REMOVE) $(TARGET).cof + $(REMOVE) $(TARGET).elf + $(REMOVE) $(TARGET).map + $(REMOVE) $(TARGET).obj + $(REMOVE) $(TARGET).a90 + $(REMOVE) $(TARGET).sym + $(REMOVE) $(TARGET).lnk + $(REMOVE) $(TARGET).lss + $(REMOVE) $(OBJ) + $(REMOVE) $(LST) + $(REMOVE) $(SRC:.c=.s) + $(REMOVE) $(SRC:.c=.d) + + +# Automatically generate C source code dependencies. +# (Code originally taken from the GNU make user manual and modified +# (See README.txt Credits).) +# +# Note that this will work with sh (bash) and sed that is shipped with WinAVR +# (see the SHELL variable defined above). +# This may not work with other shells or other seds. +# +%.d: %.c + set -e; $(CC) -MM $(ALL_CFLAGS) $< \ + | sed 's,\(.*\)\.o[ :]*,\1.o \1.d : ,g' > $@; \ + [ -s $@ ] || rm -f $@ + + +# Remove the '-' if you want to see the dependency files generated. +-include $(SRC:.c=.d) + + + +# Listing of phony targets. +.PHONY : all begin finish end sizebefore sizeafter gccversion coff extcoff \ + clean clean_list program + diff --git a/avr/nano/i2c/makefile.twimaster b/avr/nano/i2c/makefile.twimaster new file mode 100644 index 0000000..593ca45 --- /dev/null +++ b/avr/nano/i2c/makefile.twimaster @@ -0,0 +1,502 @@ +# ---------------------------------------------------------------------------- +# Makefile to compile and link the TWImaster library and test program +# Author: Peter Fleury +# File: $Id: makefile.twimaster,v 1.1 2005/03/29 14:50:05 Peter Exp $ +# based on WinAVR Makefile Template written by Eric B. Weddington, Jörg Wunsch, et al. +# +# Adjust F_CPU below to the clock frequency in Mhz of your AVR target +# +# rename this file to "makefile" or invoke with "make -f makefile.twimaster" +# +#---------------------------------------------------------------------------- +# On command line: +# +# make all = Make software. +# +# make clean = Clean out built project files. +# +# make coff = Convert ELF to AVR COFF. +# +# make extcoff = Convert ELF to AVR Extended COFF. +# +# make program = Download the hex file to the device, using avrdude. +# Please customize the avrdude settings below first! +# +# make debug = Start either simulavr or avarice as specified for debugging, +# with avr-gdb or avr-insight as the front end for debugging. +# +# make filename.s = Just compile filename.c into the assembler code only. +# +# make filename.i = Create a preprocessed source file for use in submitting +# bug reports to the GCC project. +# +# To rebuild project do "make clean" then "make all". +#---------------------------------------------------------------------------- + + +# MCU name +MCU = atmega8 + + +# Processor frequency. +# This will define a symbol, F_CPU, in all source code files equal to the +# processor frequency. You can then use this symbol in your source code to +# calculate timings. Do NOT tack on a 'UL' at the end, this will be done +# automatically to create a 32-bit value in your source code. +F_CPU = 4000000 + + +# Output format. (can be srec, ihex, binary) +FORMAT = ihex + + +# Target file name (without extension). +TARGET = test_i2cmaster + + +# List C source files here. (C dependencies are automatically generated.) +SRC = $(TARGET).c twimaster.c + + +# List Assembler source files here. +# Make them always end in a capital .S. Files ending in a lowercase .s +# will not be considered source files but generated files (assembler +# output from the compiler), and will be deleted upon "make clean"! +# Even though the DOS/Win* filesystem matches both .s and .S the same, +# it will preserve the spelling of the filenames, and gcc itself does +# care about how the name is spelled on its command-line. +ASRC = + + +# Optimization level, can be [0, 1, 2, 3, s]. +# 0 = turn off optimization. s = optimize for size. +# (Note: 3 is not always the best optimization level. See avr-libc FAQ.) +OPT = s + + +# Debugging format. +# Native formats for AVR-GCC's -g are dwarf-2 [default] or stabs. +# AVR Studio 4.10 requires dwarf-2. +# AVR [Extended] COFF format requires stabs, plus an avr-objcopy run. +DEBUG = dwarf-2 + + +# List any extra directories to look for include files here. +# Each directory must be seperated by a space. +# Use forward slashes for directory separators. +# For a directory that has spaces, enclose it in quotes. +EXTRAINCDIRS = + + +# Compiler flag to set the C Standard level. +# c89 = "ANSI" C +# gnu89 = c89 plus GCC extensions +# c99 = ISO C99 standard (not yet fully implemented) +# gnu99 = c99 plus GCC extensions +CSTANDARD = -std=gnu99 + + +# Place -D or -U options here +CDEFS = -DF_CPU=$(F_CPU)UL + + +# Place -I options here +CINCS = + + + +#---------------- Compiler Options ---------------- +# -g*: generate debugging information +# -O*: optimization level +# -f...: tuning, see GCC manual and avr-libc documentation +# -Wall...: warning level +# -Wa,...: tell GCC to pass this to the assembler. +# -adhlns...: create assembler listing +CFLAGS = -g$(DEBUG) +CFLAGS += $(CDEFS) $(CINCS) +CFLAGS += -O$(OPT) +CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums +CFLAGS += -Wall -Wstrict-prototypes +CFLAGS += -Wa,-adhlns=$(<:.c=.lst) +CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) +CFLAGS += $(CSTANDARD) + + +#---------------- Assembler Options ---------------- +# -Wa,...: tell GCC to pass this to the assembler. +# -ahlms: create listing +# -gstabs: have the assembler create line number information; note that +# for use in COFF files, additional information about filenames +# and function names needs to be present in the assembler source +# files -- see avr-libc docs [FIXME: not yet described there] +ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs + + +#---------------- Library Options ---------------- +# Minimalistic printf version +PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min + +# Floating point printf version (requires MATH_LIB = -lm below) +PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt + +# If this is left blank, then it will use the Standard printf version. +PRINTF_LIB = +#PRINTF_LIB = $(PRINTF_LIB_MIN) +#PRINTF_LIB = $(PRINTF_LIB_FLOAT) + + +# Minimalistic scanf version +SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min + +# Floating point + %[ scanf version (requires MATH_LIB = -lm below) +SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt + +# If this is left blank, then it will use the Standard scanf version. +SCANF_LIB = +#SCANF_LIB = $(SCANF_LIB_MIN) +#SCANF_LIB = $(SCANF_LIB_FLOAT) + + +MATH_LIB = -lm + + + +#---------------- External Memory Options ---------------- + +# 64 KB of external RAM, starting after internal RAM (ATmega128!), +# used for variables (.data/.bss) and heap (malloc()). +#EXTMEMOPTS = -Wl,-Tdata=0x801100,--defsym=__heap_end=0x80ffff + +# 64 KB of external RAM, starting after internal RAM (ATmega128!), +# only used for heap (malloc()). +#EXTMEMOPTS = -Wl,--defsym=__heap_start=0x801100,--defsym=__heap_end=0x80ffff + +EXTMEMOPTS = + + + +#---------------- Linker Options ---------------- +# -Wl,...: tell GCC to pass this to linker. +# -Map: create map file +# --cref: add cross reference to map file +LDFLAGS = -Wl,-Map=$(TARGET).map,--cref +LDFLAGS += $(EXTMEMOPTS) +LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB) + + + +#---------------- Programming Options (avrdude) ---------------- + +# Programming hardware: alf avr910 avrisp bascom bsd +# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500 +# +# Type: avrdude -c ? +# to get a full listing. +# +AVRDUDE_PROGRAMMER = stk500 + +# com1 = serial port. Use lpt1 to connect to parallel port. +AVRDUDE_PORT = com1 # programmer connected to serial device + +AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex +#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep + + +# Uncomment the following if you want avrdude's erase cycle counter. +# Note that this counter needs to be initialized first using -Yn, +# see avrdude manual. +#AVRDUDE_ERASE_COUNTER = -y + +# Uncomment the following if you do /not/ wish a verification to be +# performed after programming the device. +#AVRDUDE_NO_VERIFY = -V + +# Increase verbosity level. Please use this when submitting bug +# reports about avrdude. See +# to submit bug reports. +#AVRDUDE_VERBOSE = -v -v + +AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) +AVRDUDE_FLAGS += $(AVRDUDE_NO_VERIFY) +AVRDUDE_FLAGS += $(AVRDUDE_VERBOSE) +AVRDUDE_FLAGS += $(AVRDUDE_ERASE_COUNTER) + + + +#---------------- Debugging Options ---------------- + +# For simulavr only - target MCU frequency. +DEBUG_MFREQ = $(F_CPU) + +# Set the DEBUG_UI to either gdb or insight. +# DEBUG_UI = gdb +DEBUG_UI = insight + +# Set the debugging back-end to either avarice, simulavr. +DEBUG_BACKEND = avarice +#DEBUG_BACKEND = simulavr + +# GDB Init Filename. +GDBINIT_FILE = __avr_gdbinit + +# When using avarice settings for the JTAG +JTAG_DEV = /dev/com1 + +# Debugging port used to communicate between GDB / avarice / simulavr. +DEBUG_PORT = 4242 + +# Debugging host used to communicate between GDB / avarice / simulavr, normally +# just set to localhost unless doing some sort of crazy debugging when +# avarice is running on a different computer. +DEBUG_HOST = localhost + + + +#============================================================================ + + +# Define programs and commands. +SHELL = sh +CC = avr-gcc +OBJCOPY = avr-objcopy +OBJDUMP = avr-objdump +SIZE = avr-size +NM = avr-nm +AVRDUDE = avrdude +REMOVE = rm -f +COPY = cp +WINSHELL = cmd + + +# Define Messages +# English +MSG_ERRORS_NONE = Errors: none +MSG_BEGIN = -------- begin -------- +MSG_END = -------- end -------- +MSG_SIZE_BEFORE = Size before: +MSG_SIZE_AFTER = Size after: +MSG_COFF = Converting to AVR COFF: +MSG_EXTENDED_COFF = Converting to AVR Extended COFF: +MSG_FLASH = Creating load file for Flash: +MSG_EEPROM = Creating load file for EEPROM: +MSG_EXTENDED_LISTING = Creating Extended Listing: +MSG_SYMBOL_TABLE = Creating Symbol Table: +MSG_LINKING = Linking: +MSG_COMPILING = Compiling: +MSG_ASSEMBLING = Assembling: +MSG_CLEANING = Cleaning project: + + + + +# Define all object files. +OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) + +# Define all listing files. +LST = $(SRC:.c=.lst) $(ASRC:.S=.lst) + + +# Compiler flags to generate dependency files. +GENDEPFLAGS = -MD -MP -MF .dep/$(@F).d + + +# Combine all necessary flags and optional flags. +# Add target processor to flags. +ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS) +ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) + + + + + +# Default target. +all: begin gccversion sizebefore build sizeafter end + +build: elf hex eep lss sym + +elf: $(TARGET).elf +hex: $(TARGET).hex +eep: $(TARGET).eep +lss: $(TARGET).lss +sym: $(TARGET).sym + + + +# Eye candy. +# AVR Studio 3.x does not check make's exit code but relies on +# the following magic strings to be generated by the compile job. +begin: + @echo + @echo $(MSG_BEGIN) + +end: + @echo $(MSG_END) + @echo + + +# Display size of file. +HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex +ELFSIZE = $(SIZE) -A $(TARGET).elf +AVRMEM = avr-mem.sh $(TARGET).elf $(MCU) + +sizebefore: + @if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \ + $(AVRMEM) 2>/dev/null; echo; fi + +sizeafter: + @if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \ + $(AVRMEM) 2>/dev/null; echo; fi + + + +# Display compiler version information. +gccversion : + @$(CC) --version + + + +# Program the device. +program: $(TARGET).hex $(TARGET).eep + $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM) + + +# Generate avr-gdb config/init file which does the following: +# define the reset signal, load the target file, connect to target, and set +# a breakpoint at main(). +gdb-config: + @$(REMOVE) $(GDBINIT_FILE) + @echo define reset >> $(GDBINIT_FILE) + @echo SIGNAL SIGHUP >> $(GDBINIT_FILE) + @echo end >> $(GDBINIT_FILE) + @echo file $(TARGET).elf >> $(GDBINIT_FILE) + @echo target remote $(DEBUG_HOST):$(DEBUG_PORT) >> $(GDBINIT_FILE) +ifeq ($(DEBUG_BACKEND),simulavr) + @echo load >> $(GDBINIT_FILE) +endif + @echo break main >> $(GDBINIT_FILE) + +debug: gdb-config $(TARGET).elf +ifeq ($(DEBUG_BACKEND), avarice) + @echo Starting AVaRICE - Press enter when "waiting to connect" message displays. + @$(WINSHELL) /c start avarice --jtag $(JTAG_DEV) --erase --program --file \ + $(TARGET).elf $(DEBUG_HOST):$(DEBUG_PORT) + @$(WINSHELL) /c pause + +else + @$(WINSHELL) /c start simulavr --gdbserver --device $(MCU) --clock-freq \ + $(DEBUG_MFREQ) --port $(DEBUG_PORT) +endif + @$(WINSHELL) /c start avr-$(DEBUG_UI) --command=$(GDBINIT_FILE) + + + + +# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. +COFFCONVERT=$(OBJCOPY) --debugging \ +--change-section-address .data-0x800000 \ +--change-section-address .bss-0x800000 \ +--change-section-address .noinit-0x800000 \ +--change-section-address .eeprom-0x810000 + + +coff: $(TARGET).elf + @echo + @echo $(MSG_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-avr $< $(TARGET).cof + + +extcoff: $(TARGET).elf + @echo + @echo $(MSG_EXTENDED_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof + + + +# Create final output files (.hex, .eep) from ELF output file. +%.hex: %.elf + @echo + @echo $(MSG_FLASH) $@ + $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ + +%.eep: %.elf + @echo + @echo $(MSG_EEPROM) $@ + -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ + --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ + +# Create extended listing file from ELF output file. +%.lss: %.elf + @echo + @echo $(MSG_EXTENDED_LISTING) $@ + $(OBJDUMP) -h -S $< > $@ + +# Create a symbol table from ELF output file. +%.sym: %.elf + @echo + @echo $(MSG_SYMBOL_TABLE) $@ + $(NM) -n $< > $@ + + + +# Link: create ELF output file from object files. +.SECONDARY : $(TARGET).elf +.PRECIOUS : $(OBJ) +%.elf: $(OBJ) + @echo + @echo $(MSG_LINKING) $@ + $(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS) + + +# Compile: create object files from C source files. +%.o : %.c + @echo + @echo $(MSG_COMPILING) $< + $(CC) -c $(ALL_CFLAGS) $< -o $@ + + +# Compile: create assembler files from C source files. +%.s : %.c + $(CC) -S $(ALL_CFLAGS) $< -o $@ + + +# Assemble: create object files from assembler source files. +%.o : %.S + @echo + @echo $(MSG_ASSEMBLING) $< + $(CC) -c $(ALL_ASFLAGS) $< -o $@ + +# Create preprocessed source for use in sending a bug report. +%.i : %.c + $(CC) -E -mmcu=$(MCU) -I. $(CFLAGS) $< -o $@ + + +# Target: clean project. +clean: begin clean_list end + +clean_list : + @echo + @echo $(MSG_CLEANING) + $(REMOVE) $(TARGET).hex + $(REMOVE) $(TARGET).eep + $(REMOVE) $(TARGET).cof + $(REMOVE) $(TARGET).elf + $(REMOVE) $(TARGET).map + $(REMOVE) $(TARGET).sym + $(REMOVE) $(TARGET).lss + $(REMOVE) $(OBJ) + $(REMOVE) $(LST) + $(REMOVE) $(SRC:.c=.s) + $(REMOVE) $(SRC:.c=.d) + $(REMOVE) .dep/* + + + +# Include the dependency files. +-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*) + + +# Listing of phony targets. +.PHONY : all begin finish end sizebefore sizeafter gccversion \ +build elf hex eep lss sym coff extcoff \ +clean clean_list program debug gdb-config + diff --git a/avr/nano/i2c/test_i2cmaster.c b/avr/nano/i2c/test_i2cmaster.c new file mode 100644 index 0000000..fdeda29 --- /dev/null +++ b/avr/nano/i2c/test_i2cmaster.c @@ -0,0 +1,78 @@ +/**************************************************************************** +Title: Access serial EEPROM 24C02 using I2C interace +Author: Peter Fleury http://jump.to/fleury +File: $Id: test_i2cmaster.c,v 1.2 2003/12/06 17:07:18 peter Exp $ +Software: AVR-GCC 3.3 +Hardware: AT90S8515 at 4 Mhz, any AVR device can be used + +Description: + This example shows how the I2C library i2cmaster.S can be used to + access a serial eeprom. + Based on Atmel Application Note AVR300, adapted to AVR-GCC C interface + +*****************************************************************************/ +#include +#include "i2cmaster.h" + + +#define Dev24C02 0xA2 // device address of EEPROM 24C02, see datasheet + + +int main(void) +{ + unsigned char ret; + + + DDRB = 0xff; // use all pins on port B for output + PORTB = 0xff; // (active low LED's ) + + i2c_init(); // init I2C interface + + /* write 0x75 to eeprom address 0x05 (Byte Write) */ + ret = i2c_start(Dev24C02+I2C_WRITE); // set device address and write mode + if ( ret ) { + /* failed to issue start condition, possibly no device found */ + i2c_stop(); + PORTB=0x00; // activate all 8 LED to show error */ + }else { + /* issuing start condition ok, device accessible */ + i2c_write(0x05); // write address = 5 + i2c_write(0x75); // ret=0 -> Ok, ret=1 -> no ACK + i2c_stop(); // set stop conditon = release bus + + /* write ok, read value back from eeprom address 0x05, wait until + the device is no longer busy from the previous write operation */ + i2c_start_wait(Dev24C02+I2C_WRITE); // set device address and write mode + i2c_write(0x05); // write address = 5 + i2c_rep_start(Dev24C02+I2C_READ); // set device address and read mode + ret = i2c_readNak(); // read one byte + i2c_stop(); + + PORTB = ~ret; // output byte on the LED's + + /* write 0x70,0x71,072,073 to eeprom address 0x00..0x03 (Page Write), + wait until the device is no longer busy from the previous write operation */ + i2c_start_wait(Dev24C02+I2C_WRITE); // set device address and write mode + i2c_write(0x00); // write start address = 0 + i2c_write(0x70); // write data to address 0 + i2c_write(0x71); // " " " " 1 + i2c_write(0x72); // " " " " 2 + i2c_write(0x74); // " " " " 3 + i2c_stop(); // set stop conditon = release bus + + /* write ok, read value back from eeprom address 0..3 (Sequencial Read), + wait until the device is no longer busy from the previous write operation */ + i2c_start_wait(Dev24C02+I2C_WRITE); // set device address and write mode + i2c_write(0x00); // write address = 0 + i2c_rep_start(Dev24C02+I2C_READ); // set device address and read mode + ret = i2c_readAck(); // read one byte form address 0 + ret = i2c_readAck(); // " " " " " 1 + ret = i2c_readAck(); // " " " " " 2 + ret = i2c_readNak(); // " " " " " 3 + i2c_stop(); // set stop condition = release bus + + PORTB = ~ret; // output byte on the LED's + } + + for(;;); +} diff --git a/avr/nano/i2c/twimaster.c b/avr/nano/i2c/twimaster.c new file mode 100644 index 0000000..07b898d --- /dev/null +++ b/avr/nano/i2c/twimaster.c @@ -0,0 +1,197 @@ +/************************************************************************* + * Title: I2C master library using hardware TWI interface + * Author: Peter Fleury http://jump.to/fleury + * File: $Id: twimaster.c,v 1.3 2005/07/02 11:14:21 Peter Exp $ + * Software: AVR-GCC 3.4.3 / avr-libc 1.2.3 + * Target: any AVR device with hardware TWI + * Usage: API compatible with I2C Software Library i2cmaster.h + **************************************************************************/ +#include +#include + +#include + + +/* I2C clock in Hz */ +#define SCL_CLOCK 100000L + + +/************************************************************************* + Initialization of the I2C bus interface. Need to be called only once + *************************************************************************/ +void i2c_init(void) +{ + /* initialize TWI clock: 100 kHz clock, TWPS = 0 => prescaler = 1 */ + + TWSR = 0; /* no prescaler */ + TWBR = ((F_CPU/SCL_CLOCK)-16)/2; /* must be > 10 for stable operation */ + +}/* i2c_init */ + + +/************************************************************************* + Issues a start condition and sends address and transfer direction. + return 0 = device accessible, 1= failed to access device + *************************************************************************/ +unsigned char i2c_start(unsigned char address) +{ + uint8_t twst; + + // send START condition + TWCR = (1<> 8); + *reply_len = 2; + } + return 1; + } + return 0; // stay silent +} + int main(void) { DDRD = (1<<6); PORTD = (1<<6); + PORTC = (1<<4) | (1<<5); // I2C Pullups setup_uart(9600); uart_setup_stdout(); dynamixel_init(); dynamixel_listen_init(); + dynamixel_slave_set_cb(slave_cmd); + // MLX90614 IR thermometer on the I2C bus (A4 SDA / A5 SCL) + i2c_init(); // LED // Timer 0: Fast PWM non-inverting mode, Top=255 => ~1kHz diff --git a/avr/nano/mlx90614.c b/avr/nano/mlx90614.c new file mode 100644 index 0000000..168894d --- /dev/null +++ b/avr/nano/mlx90614.c @@ -0,0 +1,25 @@ +#include +#include "mlx90614.h" +#include "i2cmaster.h" + +// MLX90614: raw object temperature register (0x07), data low byte first, +// followed by a PEC byte (not checked). +// deg C = raw * 0.02 - 273.15 => 0.1 deg C = (raw - 13657) / 5 +uint16_t mlx90614_read_temp_tenths(void) +{ + uint16_t raw; + uint8_t lo, hi; + + if (i2c_start((MLX90614_ADDR << 1) | I2C_WRITE) || + i2c_write(MLX90614_REG_TOBJ1) || + i2c_rep_start((MLX90614_ADDR << 1) | I2C_READ)) + return 0; // sensor absent or bus busy + + lo = i2c_readAck(); + hi = i2c_readAck(); + i2c_readNak(); // PEC byte + raw = (uint16_t) lo | ((uint16_t) hi << 8); + if (raw == 0) + return 0; + return (uint16_t) (((int16_t) raw - 13657) / 5); +} diff --git a/avr/nano/mlx90614.h b/avr/nano/mlx90614.h new file mode 100644 index 0000000..3a72f18 --- /dev/null +++ b/avr/nano/mlx90614.h @@ -0,0 +1,15 @@ +#ifndef MLX90614_H +#define MLX90614_H + +#include + +// MLX90614 IR thermometer on the I2C bus (A4 SDA / A5 SCL), driven with +// the i2c/ library (hardware TWI, 100 kHz). Call i2c_init() once at boot. +#define MLX90614_ADDR 0x5A // 7-bit I2C address (Adafruit library default) +#define MLX90614_REG_TOBJ1 0x07 // raw object temperature register + +// Object temperature in 0.1 deg C (214 == 21.4 deg C). +// Returns 0 if the sensor does not answer. +uint16_t mlx90614_read_temp_tenths(void); + +#endif -- 2.39.5