반응형

 

Avr EEPROM 쓰고 읽는 예제. ( at24/fm24 모듈을 이용 )

 

1. TWI (I2C) 초기화

마스터가 초기화한다는 것은 TWI클럭 주파수(SCL)이 세팅된다는 것이다.

이 것은 TWBR에 bit reate를 설정하고 TWSR에 prescaller를 설정함으로써 이루어진다.

 

2. START condition 전송

 

3. 슬레이브의 주소 전송

나누어서 두번 전송된다.

 

4. 데이터 전송

5. STOP 상태를 보낸다.

 

 

6. START condition 전송

 

7. 슬레이브 주소 전송

 

8. SDA 버스로부터 데이터 수신

 

9. STOP condition 전송

 

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
 
#include <stdio.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/twi.h>
 
//usart
#define USART_BAUDRATE 9600
#define F_CPU 16000000 //16MHZ
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1
 
 
#define EEPAGES 128
#define EEPAGESIZE 16
#define EEMAXADDR 0x0800
#define ERROR 1
#define SUCCESS (!ERROR)
 
 
 
 
 
uint8_t EEWriteByte(uint16_t u16addr, uint8_t u8data)
{
 
    /////////////////////////////
    // send start signal
    /////////////////////////////
    begin:
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // SDA 선로 상에 start 신호를 보내기 위해서 TWSTA 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);  //버스 사용 가능시 start 시그널을 전송한다.
 
    //start 시그널 전송이 완료되면 TWINT비트는 0으로 세트된다. 
    while ((TWCR & (1<<TWINT)) == 0);
 
    //ACK 체크, start 시그널을 성공적으로 전송했는지 검사 
    //하위 3비트를 제외하고 체크한다.
        
    int status = TWSR & 0xF8
    switch( status )
    {
        case TW_REP_START: //repeated start condition transmitted 0x10
        case TW_START:    //start condition transmitted 0x08
        break;
        
        case TW_MT_ARB_LOST: //arbitration lost in SLA+W or data 0x38
        goto begin;
        
        default:
        printf"error:send start condition\n");
        return -1;
    }
    
    
 
    //////////////////////////////////////////
    //  슬레이브의 주소 전송 
    /////////////////////////////////////
    //1010은 EEPROM 고유의 디바이스를 인식 코드이다. 
    //주소의 상의 3비트인 A2 A1 A0을 전송한다. 
    TWDR = (0b10100000)|(uint8_t)((u16addr & 0x0700)>>7);
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWEN);  //버스 사용가능시 주소를 전송한다. 
    while ((TWCR & (1<<TWINT)) == 0);  //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다. 
 
    //ACK 체크, 주소를 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다. 
    
    status = TWSR & 0xF8;
    
    switch(status)
    {
        case TW_MT_SLA_ACK://SLA+W transmitted, ACK received 0x18
        break;
        
        case TW_MT_SLA_NACK: //SLA+W transmitted, NACK received 0x20
        goto begin;
        
        case TW_MT_ARB_LOST: //arbitration lost in SLA+W or data 0x38
        goto begin;
        
        default:
        printf"error: send address ");
        TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
        return -1;
    }
    
    
    ///////////////////////////////////////
    //나머지 주소를 전송한다. 
    ///////////////////////////////////////
    TWDR = (uint8_t)(u16addr);
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWEN); //버스 사용가능시 주소를 전송한다. 
    while ((TWCR & (1<<TWINT)) == 0); //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다.
    
    //ACK 체크, 나머지 주소를 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다. 
    status = TWSR & 0xF8;
    switch(status)
    {
        case TW_MT_DATA_ACK: //data transmitted, ACK received 0x28
        break;
        
        case TW_MT_DATA_NACK: //data transmitted, NACK received 0x30
        case TW_MT_ARB_LOST:  //arbitration lost in SLA+W or data 0x38
        default:
        printf"error: send address ");
        TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
        return -1;
         
    }
    
 
 
    ////////////////////////////////////////////////////////
    //  write byte to eeprom
    /////////////////////////////////////////////////////
    //8비트 데이터를 TWDR레지스터에 넣는다
    TWDR = u8data;      
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWEN);//데이터를 전송을 시작한다. 
    while ((TWCR & (1<<TWINT)) == 0); //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다. 
 
    //ACK 체크, 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    status = TWSR & 0xF8;
    switch(status)
    {
        case TW_MT_DATA_ACK: //data transmitted, ACK received 0x28
        break;
        
        case TW_MT_DATA_NACK: //data transmitted, NACK received 0x30
        printf"device write protected\n" );
        default:
        printf"error: send address ");
        TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
        return -1;
        
    }
 
 
 
    ///////////////////////////////////////////
    // send stop signal
    /////////////////////////////////////
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // SDA와 SCL 선로 상에 STOP 신호를 보내기 위해서 TWSTO 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    while (TWCR & (1<<TWSTO));//전송이 완료되면 TWSTO비트는 0으로 세트된다.
 
 
    return SUCCESS;
}
 
 
//write byte to 24C16
uint8_t EEWritePage(uint8_t page, uint8_t *u8data)
{
    //calculate page address
    uint8_t u8paddr = 0;
    uint8_t i;
    u8paddr = page<<4;
 
 
    /////////////////////////////
    // 2. send start signal
    /////////////////////////////
    begin:
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // SDA 선로 상에 start 신호를 보내기 위해서 TWSTA 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);  //버스 사용 가능시 start 시그널을 전송한다.
 
    //start 시그널 전송이 완료되면 TWINT비트는 0으로 세트된다.
    while ((TWCR & (1<<TWINT)) == 0);
 
    //ACK 체크, start 시그널을 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    
    int status = TWSR & 0xF8;
    switch( status )
    {
        case TW_REP_START: //repeated start condition transmitted 0x10
        case TW_START:    //start condition transmitted 0x08
        break;
        
        case TW_MT_ARB_LOST: //arbitration lost in SLA+W or data 0x38
        goto begin;
        
        default:
        printf"error:send start condition\n");
        return -1;
    }
 
 
    //////////////////////////////////////////
    // 3. 슬레이브의 주소 전송
    /////////////////////////////////////
    //1010은 EEPROM 고유의 디바이스를 인식 코드이다.
    //select page start address and send A2 A1 A0 bits send write command
    TWDR = ((0b10100000)|(u8paddr>>3))&(~1);
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN);  //버스 사용가능시 주소를 전송한다.
    while ((TWCR & (1<<TWINT)) == 0);  //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다.
 
    //ACK 체크, 주소를 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    
    status = TWSR & 0xF8;
    
    switch(status)
    {
        case TW_MT_SLA_ACK://SLA+W transmitted, ACK received 0x18
        break;
        
        case TW_MT_SLA_NACK: //SLA+W transmitted, NACK received 0x20
        goto begin;
        
        case TW_MT_ARB_LOST: //arbitration lost in SLA+W or data 0x38
        goto begin;
        
        default:
        printf"error: send address ");
        TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
        return -1;
    }
    
            
    //나머지 주소를 전송한다.
    TWDR = (u8paddr<<4);
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN); //버스 사용가능시 주소를 전송한다.
    while ((TWCR & (1<<TWINT)) == 0); //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다.
    
    //ACK 체크, 나머지 주소를 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    status = TWSR & 0xF8;
    switch(status)
    {
        case TW_MT_DATA_ACK: //data transmitted, ACK received 0x28
        break;
        
        case TW_MT_DATA_NACK: //data transmitted, NACK received 0x30
        case TW_MT_ARB_LOST:  //arbitration lost in SLA+W or data 0x38
        default:
        printf"error: send address ");
        TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
        return -1;
        
    }
    
            
        
        
        
    //write page to eeprom
    for (i=0; i<16; i++)
    {
        TWDR = *u8data++;
 
        // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
        // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
        TWCR = (1<<TWINT)|(1<<TWEN); //데이터 전송을 시작한다.
        while ((TWCR & (1<<TWINT)) == 0); //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다.
    
        //ACK 체크, 성공적으로 전송했는지 검사
        //하위 3비트를 제외하고 체크한다.
        status = TWSR & 0xF8;
        switch(status)
        {
            case TW_MT_DATA_ACK: //data transmitted, ACK received 0x28
            break;
                    
            case TW_MT_DATA_NACK: //data transmitted, NACK received 0x30
            printf"device write protected\n" );
            default:
            printf"error: send address ");
            TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
            return -1;
                    
        }
                
    }
 
    //send stop signal
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // SDA와 SCL 선로 상에 STOP 신호를 보내기 위해서 TWSTO 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    while (TWCR & (1<<TWSTO));
 
    return SUCCESS;
}
 
 
uint8_t EEReadByte(uint16_t u16addr, uint8_t *u8data)
{
    //uint8_t databyte;
 
    ///////////////////////
    // 1. send start signal
    ///////////////////////
 
    begin:
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // SDA 선로 상에 start 신호를 보내기 위해서 TWSTA 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); //버스사용가능시 start 상태를 전송
 
    //start 시그널 전송이 완료되면 TWINT비트는 0으로 세트된다. 
    while ((TWCR & (1<<TWINT)) == 0);
 
    //ACK 체크, start 시그널을 성공적으로 전송했는지 검사 
    //하위 3비트를 제외하고 체크한다. 
    int status = TWSR & 0xF8;
    switch(status)
    {
        case TW_START://start condition transmitted
            break;
            
        case TW_MT_ARB_LOST:
            goto begin;    
            
        default:
            printf"error:send start condition\n");
            return -1;
    }
    
    
 
    //////////////////////////////////////////
    // 슬레이브의 주소 전송
    /////////////////////////////////////
    //select devise and send A2 A1 A0 address bits
    //0x0700 = 0b 0000 0111 0000 0000
    TWDR = (0b10100000)|((uint8_t)((u16addr & 0x0700)>>7));
    
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN);
    
    while ((TWCR & (1<<TWINT)) == 0); //전송이 완료되면 TWINT비트는 0으로 세트된다.
 
    //ACK 체크, 주소 전송을 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    status = TWSR & 0xF8;
    
    if (status != 0x18//SLA+W transmitted, ACK received  TW_MT_SLA_ACK
        return ERROR;
 
 
    //send the rest of address
    TWDR = (uint8_t)(u16addr);
    
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN);
    while ((TWCR & (1<<TWINT)) == 0);
    
    //ACK 체크, 주소 전송을 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    status = TWSR & 0xF8;
    if (status != 0x28)  //data transmitted, ACK received  TW_MT_DATA_ACK
        return ERROR;
 
 
 
 
    /////////////////////////////////////////////////
    //repeated start condition
    /////////////////////////////////////////////////
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // SDA 선로 상에 start 신호를 보내기 위해서 TWSTA 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);  //버스 사용 가능시 start 시그널을 전송한다.
 
    //start 시그널 전송이 완료되면 TWINT비트는 0으로 세트된다. 
    while ((TWCR & (1<<TWINT)) == 0);
 
    //ACK 체크, start 시그널을 성공적으로 전송했는지 검사 
    //하위 3비트를 제외하고 체크한다. 
    if ( (TWSR & 0xF8!= 0x10)  //repeated start condition transmitted TW_REP_START
        return ERROR;
 
 
 
 
    //select devise and send read bit
    //Put the 8 bit data in TWDR
    //8 bits = 7 bit slave address + Data direction bit (read = 1)
    TWDR = (0b10100000)|((uint8_t)((u16addr & 0x0700)>>7))|1//TW_READ =1
 
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정 
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정 
    TWCR = (1<<TWINT)|(1<<TWEN); //Wait till complete TWDR byte received
 
    //수신이 완료되면 TWINT비트는 0으로 세트된다. 
    while ((TWCR & (1<<TWINT)) == 0);
 
    //ACK 체크, 주소를 성공적으로 전송했는지 검사 
    if ((TWSR & 0xF8!= 0x40)  //SLA+R transmitted, ACK received  TW_MR_SLA_ACK
        return ERROR;
 
 
    ///////////////////////////////
    //데이터를 읽어온다. 
    ////////////////////////////////////////
    TWCR = (1<<TWINT)|(1<<TWEN);
    while ((TWCR & (1<<TWINT)) == 0); //전송이 완료될때 까지 대기 
 
 
    *u8data = TWDR; //데이터를 읽어온다.
 
    //한바이트가 마지막 바이트 이기때문에 0x58 응답값을 얻는다. 
    if ((TWSR & 0xF8!= 0x58)  //data received, NACK returned  TW_MR_DATA_NACK
        return ERROR;
 
    ///////////////////////////
    //send stop signal
    //////////////////////////
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    while (TWCR & (1<<TWSTO));
 
    return SUCCESS;
}
uint8_t EEReadPage(uint8_t page, uint8_t *u8data)
{
    //calculate page address
    uint8_t u8paddr = 0;
    uint8_t i;
    u8paddr = page<<4;
    
    begin:
    ///////////////////////
    //send start signal
    ///////////////////////
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // SDA 선로 상에 start 신호를 보내기 위해서 TWSTA 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);  //버스 사용 가능시 start 시그널을 전송한다.
    
    ////start 시그널 전송이 완료되면 TWINT비트는 0으로 세트된다.
    while ((TWCR & (1<<TWINT)) == 0);
    int status = TWSR & 0xF8;
    switch( status )
    {
        case TW_REP_START: //repeated start condition transmitted 0x10
        case TW_START:    //start condition transmitted 0x08
        break;
        
        case TW_MT_ARB_LOST: //arbitration lost in SLA+W or data 0x38
        goto begin;
        
        default:
        printf"error:send start condition\n");
        return -1;
    }
 
 
    //////////////////////////////////////////
    // 슬레이브의 주소 전송
    /////////////////////////////////////
    //1010은 EEPROM 고유의 디바이스를 인식 코드이다.
    //select page start address and send A2 A1 A0 bits send write command
    TWDR = ((0b10100000)|(u8paddr>>3))&(~1);
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN);  //버스 사용가능시 주소를 전송한다.
    while ((TWCR & (1<<TWINT)) == 0);  //전송이 완료되면 TWINT비트는 0으로 세트된다. 즉 인터럽트 플레그가 세트된다.
 
    //ACK 체크, 주소를 성공적으로 전송했는지 검사
    //하위 3비트를 제외하고 체크한다.
    
    status = TWSR & 0xF8;
    
    switch(status)
    {
        case TW_MT_SLA_ACK://SLA+W transmitted, ACK received 0x18
        break;
        
        case TW_MT_SLA_NACK: //SLA+W transmitted, NACK received 0x20
        goto begin;
        
        case TW_MT_ARB_LOST: //arbitration lost in SLA+W or data 0x38
        goto begin;
        
        default:
        printf"error: send address ");
        TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
        return -1;
    }
 
 
    //send the rest of address
    TWDR = (u8paddr<<4);
    
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN); //Wait till complete TWDR byte received
 
    //수신이 완료되면 TWINT비트는 0으로 세트된다.
    while ((TWCR & (1<<TWINT)) == 0);
    status = TWSR & 0xF8;
    if (status != 0x28)   //data transmitted, ACK received  TW_MT_DATA_ACK
        return ERROR;
 
 
    //send start
    //send start signal
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
    while ((TWCR & (1<<TWINT)) == 0);
 
    status = TWSR & 0xF8;
    if (status != 0x10)  //repeated start condition transmitted TW_REP_START
        return ERROR;
 
 
    //select devise and send read bit
    TWDR = ((0b10100000)|(u8paddr>>3))|1;
    // TWI 인터럽트 플래그를 클리어하기 위해서 TWINT 비트를 1로 설정
    // TWI를 초기화 하기위해서 TWEN 비트를 1로 설정
    TWCR = (1<<TWINT)|(1<<TWEN); //Wait till complete TWDR byte received
 
    //수신이 완료되면 TWINT비트는 0으로 세트된다.
    while ((TWCR & (1<<TWINT)) == 0);
 
 
    status = TWSR & 0xF8;
    if (status != 0x40)  //SLA+R transmitted, ACK received  TW_MR_SLA_ACK
        return ERROR;
            
        
    for (i=0; i<16; i++)
    {
        //read byte with ACK
        //To acknowledge salve about last byte TWEA bit is used while transmitting the data. 
        //If TWEA bit is set, reception continuous from the MASTER side. And if TWEA bit is low, MASTER orders slave to send the last byte
        
        if ( i < 15 )
            TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
        else
            TWCR = (1<<TWINT)|(1<<TWEN);
        
        while ((TWCR & (1<<TWINT)) == 0);
        
        status = TWSR & 0xF8;
        
        switch(status)
        {
            case TW_MR_DATA_NACK: //data received, NACK returned  0x58 마지막 바이트 수신
                i=16//FALLTHROUGH 강제로 루프를 종료한다.
            case TW_MR_DATA_ACK://data received, ACK returned 0x50  다음바이트 계속 수신받아야함.
                *u8data++ = TWDR;
 
                break;
                
            default:
            printf"error: recevie data ");
            TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
            return -1;                
                
        }
        
 
    }    
    
    //send stop signal
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    while (TWCR & (1<<TWSTO));
 
    return SUCCESS;
}
 
 
 
int USART0SendByte(char u8Data, FILE *stream)
{
   if(u8Data == '\n')
   {
      USART0SendByte('\r'0);
   } 
//wait while previous byte is completed
while(!(UCSR0A&(1<<UDRE0))){};
// Transmit data
UDR0 = u8Data;
return 0;
}
int USART0ReceiveByte(FILE *stream)
{
uint8_t u8Data;
// Wait for byte to be received
while(!(UCSR0A&(1<<RXC0))){};
u8Data=UDR0;
//echo input data
USART0SendByte(u8Data,stream); 
// Return received data
return u8Data;
}
 
 
 
//set stream pointer
FILE usart0_str = FDEV_SETUP_STREAM(USART0SendByte, USART0ReceiveByte, _FDEV_SETUP_RW);
 
 
int main(void)
{
    uint8_t u8ebyte;
    uint8_t u8erbyte;
    uint16_t u16eaddress = 0xa0;
    uint8_t page = 5;
    uint8_t i;
    uint8_t eereadpage[16= {0,};
    uint8_t eewritepage[16= { 0x014425546808743130,
                                21023158461501246 };
    
 
    //Initialize USART0
    // Set baud rate
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    // Set frame format to 8 data bits, no parity, 1 stop bit
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //enable transmission and reception
    UCSR0B |= (1<<RXEN0)|(1<<TXEN0);
    
 
 
    /////////////////////////////////
    //1.set SCL to 400kHz for i2c
    ////////////////////////////////
    TWSR = 0x00//추가적인 prescaller를 필요하지 않기 때문에 0으로 설정 -> pewscaler value = 1
    TWBR = 0x0C//SCL을 400KHz로 설정한다. 
    //SCL frequency = CPU Clock frequency / ( 16 + 2 x TWBR x Prescalervalue )
    //16000000Hz/(16+2x12x1) = 16000000Hz/40 = 400000 Hz = 400KHz
 
 
    //enable TWI
    TWCR = (1<<TWEN);
    ///////////////////////////////////////////////
 
 
 
    //assign our stream to standard I/O streams
    stdin=stdout=&usart0_str;
 
 
    printf("\nWrite byte %#04x to eeprom address %#04x"0x58, u16eaddress);
    
    //u16eaddress = 0x07F0 = 0b111 11110000
    if (EEWriteByte(u16eaddress, 0x58!= ERROR)
    {
        printf_P(PSTR("\nRead byte From eeprom"));
        if (EEReadByte(u16eaddress, &u8ebyte) != ERROR)
        {
            printf("\n*%#04x = %#04x", u16eaddress, u8ebyte);
        }
        else printf_P(PSTR("\nStatus fail!"));
 
    }    
    else printf_P(PSTR("\nStatus fail!"));
        
    printf_P(PSTR("\nWriting 16 bytes to page 5\n"));
    if(EEWritePage(page, eewritepage) != ERROR)
    {
        printf_P(PSTR("\nReading 16 bytes from page 5\n"));
        if (EEReadPage(page, eereadpage) != ERROR)
        {
            //compare send and read buffers
            for (i=0; i<16; i++)
            {
                if (eereadpage[i] != eewritepage[i])
                    break;
                else 
                {
                    printf ( "%02X--%02X\n", eereadpage[i], eewritepage[i]);
                    continue;
                }
            }
            if (i==16)
                printf_P(PSTR("\nPage write and read success!"));
            else
                printf_P(PSTR("\nPage write and read fail!"));
        } else printf_P(PSTR("\nStatus fail!"));
 
    }else printf_P(PSTR("\nStatus fail!"));
 
    printf_P(PSTR("\nContinue testing EEPROM from terminal!"));
        while(1)
        {
            printf("\nEnter EEPROM address to write (MAX = %u): ", EEMAXADDR);
            scanf("%d",&u16eaddress);
            printf("Enter data to write to EEPROM at address %u: ", u16eaddress);
            scanf("%c",&u8ebyte);
            printf_P(PSTR("\nWriting..."));
            EEWriteByte(u16eaddress, u8ebyte);
            printf_P(PSTR("\nTesting..."));
            if (EEReadByte(u16eaddress, &u8erbyte) !=ERROR)
                {
                    if (u8ebyte==u8erbyte)
                        printf_P(PSTR("\nSuccess!"));
                    else
                        printf_P(PSTR("\nFail!"));
                }
                else printf_P(PSTR("\nStatus fail!"));
 
            //TODO:: Please write your application code 
        }
}
cs

 

참고

http://www.embedds.com/programming-avr-i2c-interface/

http://www.ermicro.com/blog/?p=744

http://www.engineersgarage.com/embedded/avr-microcontroller-projects/atmega32-twi-two-wire-interface

https://learn.sparkfun.com/tutorials/i2c

http://www.nongnu.org/avr-libc/user-manual/group__twi__demo.html

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts