forked from Tasssadar/3piLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3piLibPack.h
1998 lines (1656 loc) · 44.1 KB
/
3piLibPack.h
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define PI_LIB_VERSION 31
#ifndef PI_LIB_COMMON
#define PI_LIB_COMMON
#define JUNIOR_F_CPU 20000000
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>
#ifdef JUNIOR_ON_IDLE
#define JUNIOR_DO_IDLE() JUNIOR_ON_IDLE()
#else
#define JUNIOR_DO_IDLE()
#endif
inline void nop()
{
asm volatile ("nop");
}
#ifndef __cplusplus
# error Nezapomente si v nastaveni AVR studia zapnout "-x c++" !
#endif
#if !defined(F_CPU) && !defined(JUNIOR_F_CPU)
# error Nemate nastavenou frekvenci procesoru!
#endif
#ifndef JUNIOR_F_CPU
# define JUNIOR_F_CPU F_CPU
#endif
#ifndef F_CPU
# define F_CPU JUNIOR_F_CPU
#endif
#if defined(F_CPU) && F_CPU != JUNIOR_F_CPU
# error Mate v nastaveni spatne nastavenou frekvenci procesoru !
#endif
#define JUNIOR_CONCAT2(x, y) x ## y
#define JUNIOR_CONCAT(x, y) JUNIOR_CONCAT2(x, y)
template <typename T>
inline T abs(T num)
{
return (num < 0) ? -num : num;
}
template <typename T>
T load_eeprom(uint16_t address)
{
T res;
char * ptr = (char *) &res;
char * pend = ptr + sizeof res;
EEARH = (address >> 8);
EEARL = uint8_t(address);
while (ptr != pend)
{
EECR = (1<<EERE);
*ptr++ = EEDR;
++EEARL;
}
return res;
}
template <typename T>
void store_eeprom(uint16_t address, T value)
{
char * ptr = (char *) &value;
char * pend = ptr + sizeof value;
EEARH = (address >> 8);
EEARL = uint8_t(address);
while (ptr != pend)
{
EEDR = *ptr++;
EECR = (1<<EEMPE);
EECR = (1<<EEPE);
while (EECR & (1<<EEPE))
{
}
++EEARL;
}
}
#endif
#ifndef PI_LIB_BUZZER
#define PI_LIB_BUZZER
class buzzer_t
{
public:
buzzer_t()
{
m_running = m_emergencyEnabled = m_started = false;
m_freq = 2500;
m_time_on = m_time_off = 0;
}
void set(uint16_t time_on = 0, uint16_t time_off = 0, bool run = true)
{
m_running = false;
m_time_on = time_on;
m_time_off = time_off;
if(run)
start();
}
void start()
{
if(!m_freq)
return;
m_running = m_started = true;
if(!m_time_on)
m_timer = -1;
else
m_timer = m_time_on;
TCCR1B = (1 << WGM12) | (1 << CS11);
OCR1AH = (m_freq >> 8);
OCR1AL = (m_freq & 0xFF);
TCCR1A |= (1 << COM1B0);
}
void stop()
{
m_running = m_started = false;
TCCR1A = 0;
TCCR1B = 0;
TCCR1A &= ~(1 << COM1B0);
}
bool isStarted()
{
return m_started;
}
void setFreq(uint32_t hz)
{
m_freq = F_CPU/(hz*16);
if(m_running)
{
OCR1AH = (m_freq >> 8);
OCR1AL = (m_freq & 0xFF);
}
}
void update()
{
if(!m_started || m_timer == -1)
return;
--m_timer;
if(m_timer == 0)
{
if(m_running)
{
if(m_time_off == 0)
m_timer = -1;
else
m_timer = m_time_off;
TCCR1A &= ~(1 << COM1B0);
OCR1AH = (m_freq >> 8);
OCR1AL = (m_freq & 0xFF);
}
else
{
m_timer = m_time_on;
TCCR1A |= (1 << COM1B0);
OCR1AH = (m_freq >> 8);
OCR1AL = (m_freq & 0xFF);
}
m_running = !m_running;
}
}
void emergency(bool on)
{
if(!m_emergencyEnabled || m_emergency == on)
return;
m_emergency = on;
if(on)
set(1000, 500);
else
stop();
}
bool isEmergency() { return m_emergency; }
void setEmergencyEnabled(bool enable) { m_emergencyEnabled = enable; }
private:
uint16_t m_freq;
int16_t m_time_on;
int16_t m_time_off;
int16_t m_timer;
volatile bool m_running;
volatile bool m_started;
volatile bool m_emergency;
volatile bool m_emergencyEnabled;
};
buzzer_t buzzer;
void init_buzzer()
{
TCCR1B = (1 << WGM12) | (1 << CS11);
OCR1BH = 0;
OCR1BL = 0;
DDRB |= (1 << 2);
PORTB &= ~(1 << 2);
}
void clean_buzzer()
{
buzzer.stop();
}
#endif
#ifndef PI_LIB_MOTORS
#define PI_LIB_MOTORS
#define MOTORS_ACCELERATION 1
void init_motors()
{
// configure for inverted fast PWM output on motor control pins:
// set OCxx on compare match, clear on timer overflow
// Timer0 and Timer2 counts up from 0 to 255 and then overflows directly to 0
TCCR0A = TCCR2A = 0xF3;
// use the system clock/8 (=2.5 MHz) as the timer clock,
// which will produce a PWM frequency of 10 kHz
TCCR0B = TCCR2B = 0x02;
// use the system clock (=20 MHz) as the timer clock,
// which will produce a PWM frequency of 78 kHz. The Baby Orangutan B
// and 3Pi can support PWM frequencies this high. The
// Orangutan LV-168 cannot support frequencies above 10 kHz.
//TCCR0B = TCCR2B = 0x01;
// initialize all PWMs to 0% duty cycle (braking)
OCR0A = OCR0B = OCR2A = OCR2B = 0;
TIMSK0 |= (1 << TOIE0);
DDRD |= (1 << PIN5) | (1 << PIN6)| (1 << PIN3);
DDRB |= (1 << PIN3);
PORTD &= ~(1 << PIN5);
PORTD &= ~(1 << PIN6);
PORTD &= ~(1 << PIN3);
PORTB &= ~(1 << PIN3);
}
void clean_motors()
{
TCCR0A = 0;
TCCR2A = 0;
TCCR0B = 0;
TCCR2B = 0;
}
namespace detail
{
volatile int16_t g_speed[2] = {0, 0};
volatile int16_t g_speed_cur[2] = {0, 0};
volatile bool g_need_set_speed[2] = {false, false};
volatile bool g_soft_speed_set = true;
volatile bool g_speed_is_setted = false;
volatile uint8_t g_sub_timer = 0;
volatile uint32_t g_timer = 0;
void setLeftMotor(int16_t speed)
{
bool reverse = false;
if (speed < 0)
{
speed = -speed; // make speed a positive quantity
reverse = true; // preserve the direction
}
if (speed > 0xFF) // 0xFF = 255
speed = 0xFF;
if (reverse)
{
OCR0B = 0; // hold one driver input high
OCR0A = speed; // pwm the other input
}
else // forward
{
OCR0B = speed; // pwm one driver input
OCR0A = 0; // hold the other driver input high
}
}
void setRightMotor(int16_t speed)
{
bool reverse = false;
if (speed < 0)
{
speed = -speed; // make speed a positive quantity
reverse = true; // preserve the direction
}
if (speed > 0xFF) // 0xFF = 255
speed = 0xFF;
if (reverse)
{
OCR2B = 0; // hold one driver input high
OCR2A = speed; // pwm the other input
}
else // forward
{
OCR2B = speed; // pwm one driver input
OCR2A = 0; // hold the other driver input high
}
}
}
void setRightMotor(int16_t speed)
{
detail::g_speed[1] = speed;
if(detail::g_soft_speed_set)
detail::g_need_set_speed[1] = true;
else
detail::setRightMotor(speed);
}
void setLeftMotor(int16_t speed)
{
detail::g_speed[0] = speed;
if(detail::g_soft_speed_set)
detail::g_need_set_speed[0] = true;
else
detail::setLeftMotor(speed);
}
void setMotorPowerID(uint8_t motor, int16_t speed)
{
if(motor)
detail::setRightMotor(speed);
else
detail::setLeftMotor(speed);
}
inline void setMotorPower(int16_t left, int16_t right)
{
setLeftMotor(left);
setRightMotor(right);
}
int16_t getMotorPowerID(uint8_t motor)
{
return detail::g_speed[motor];
}
inline int16_t getLeftMotor()
{
return getMotorPowerID(0);
}
inline int16_t getRightMotor()
{
return getMotorPowerID(1);
}
inline void setSoftAccel(bool enabled)
{
detail::g_soft_speed_set = enabled;
}
ISR(TIMER0_OVF_vect)
{
if(++detail::g_sub_timer != 10)
return;
detail::g_sub_timer = 0;
++detail::g_timer;
buzzer.update();
if(detail::g_speed_is_setted)
return;
detail::g_speed_is_setted = true;
for(uint8_t i = 0; i < 2; ++i)
{
if(!detail::g_need_set_speed[i])
continue;
if(detail::g_speed[i] == detail::g_speed_cur[i])
{
detail::g_need_set_speed[i] = false;
continue;
}
int16_t val = abs(detail::g_speed[i]-detail::g_speed_cur[i]);
if(val >= MOTORS_ACCELERATION)
val = MOTORS_ACCELERATION;
if(detail::g_speed[i] < detail::g_speed_cur[i])
val *= -1;
detail::g_speed_cur[i] += val;
setMotorPowerID(i, detail::g_speed_cur[i]);
}
detail::g_speed_is_setted = false;
}
#endif
#ifndef PI_LIB_TIME
#define PI_LIB_TIME
// Delays for for the specified nubmer of microseconds.
inline void delayMicroseconds(uint16_t microseconds)
{
__asm__ volatile (
"1: push r22" "\n\t"
" ldi r22, 4" "\n\t"
"2: dec r22" "\n\t"
" brne 2b" "\n\t"
" pop r22" "\n\t"
" sbiw %0, 1" "\n\t"
" brne 1b"
: "=w" ( microseconds )
: "0" ( microseconds )
);
}
inline void delay(uint16_t ms)
{
while (ms--)
delayMicroseconds(1000);
}
uint32_t getTicksCount()
{
cli();
uint32_t time = detail::g_timer;
sei();
return time;
}
void resetTicks() __attribute__ ((deprecated));
void resetTicks()
{
cli();
detail::g_timer = 0;
sei();
}
class stopwatch
{
public:
stopwatch(bool running = true) : m_running(running)
{
clear();
}
void clear()
{
if(m_running)
m_base = getTicksCount();
else
m_base = 0;
}
void cancel()
{
m_running = false;
m_base = 0;
}
bool running() const
{
return m_running;
}
void restart()
{
m_running = true;
m_base = getTicksCount();
}
void start()
{
if(!m_running)
{
m_running = true;
m_base = getTicksCount() - m_base;
}
}
void stop()
{
if(m_running)
{
m_running = false;
m_base = getTicksCount() - m_base;
}
}
uint32_t operator()() const
{
return get();
}
uint32_t get() const
{
if(m_running)
return getTicksCount() - m_base;
else
return m_base;
}
void set(uint32_t val)
{
if(m_running)
m_base = getTicksCount() - val;
else
m_base = val;
}
void decrease(uint32_t val)
{
if(m_running)
m_base += val;
else
m_base -= val;
}
private:
volatile bool m_running;
volatile uint32_t m_base;
};
#endif
#ifndef PI_LIB_SENSORS
#define PI_LIB_SENSORS
// LOW_BATTERY = (((low_voltage_in_mv*2-1)/3)*1023-511)/5000;
// Current setting is 4200mV
#define LOW_BATTERY 560
#define PI_GRND_SENSOR_COUNT 5
#define PI_TOTAL_SENSORS 7
#define PI_BAT_VOLTAGE_SENSOR 6
#define PI_VCC 5000
struct ground_sensors_t
{
uint16_t value[PI_TOTAL_SENSORS];
};
volatile struct ground_sensors_t g_sensors;
volatile int16_t g_calibratedMinimum[PI_GRND_SENSOR_COUNT];
volatile int16_t g_calibratedMaximum[PI_GRND_SENSOR_COUNT];
ISR(ADC_vect)
{
static uint8_t currentSensor = 0;
static bool initSensor = false;
static const uint8_t sensorMap[PI_TOTAL_SENSORS] = { 0, 1, 2, 3, 4, 6, 7 };
if (initSensor)
{
uint8_t adcl = ADCL;
uint8_t adch = ADCH;
uint16_t value = (adch << 8) | (adcl);
g_sensors.value[currentSensor++] = value;
if (currentSensor == PI_BAT_VOLTAGE_SENSOR)
{
if(buzzer.isEmergency() && value > LOW_BATTERY)
buzzer.emergency(false);
else if(!buzzer.isEmergency() && value < LOW_BATTERY)
buzzer.emergency(true);
}
if(currentSensor == PI_TOTAL_SENSORS)
{
currentSensor = 0;
}
ADMUX = (1<<REFS0)|sensorMap[currentSensor];
}
initSensor = !initSensor;
// Start the next conversion
ADCSRA |= (1<<ADSC);
}
inline int16_t getSensorValue(uint8_t index, bool threshold = true)
{
cli();
while (g_sensors.value[index] == 1024)
{
sei();
nop();
cli();
}
int16_t res = g_sensors.value[index];
sei();
nop();
if(threshold)
{
int16_t denominator = g_calibratedMaximum[index] - g_calibratedMinimum[index];
int16_t val = res;
if(denominator)
val = int32_t(res - g_calibratedMinimum[index])*1000/denominator;
if(val < 0)
res = 0;
else if(val > 1024)
res = 1024;
else
res = val;
}
return res;
}
void resetCalibration()
{
for(uint8_t i = 0; i < PI_GRND_SENSOR_COUNT; ++i)
{
g_calibratedMaximum[i] = 0;
g_calibratedMinimum[i] = 1024;
}
}
void calibrate_sensors()
{
uint8_t i;
int16_t sensor_value;
int16_t max_sensor_values[PI_GRND_SENSOR_COUNT];
int16_t min_sensor_values[PI_GRND_SENSOR_COUNT];
for(uint8_t j = 0; j<10; ++j)
{
for(i = 0; i<PI_GRND_SENSOR_COUNT; ++i)
{
sensor_value = getSensorValue(i, false);
// set the max we found THIS time
if(j == 0 || max_sensor_values[i] < sensor_value)
max_sensor_values[i] = sensor_value;
// set the min we found THIS time
if(j == 0 || min_sensor_values[i] > sensor_value)
min_sensor_values[i] = sensor_value;
}
}
// record the min and max calibration values
for(i = 0; i < PI_GRND_SENSOR_COUNT; ++i)
{
if(min_sensor_values[i] > g_calibratedMaximum[i])
g_calibratedMaximum[i] = min_sensor_values[i];
if(max_sensor_values[i] < g_calibratedMinimum[i])
g_calibratedMinimum[i] = max_sensor_values[i];
}
}
void cal_round()
{
resetCalibration();
for(uint8_t counter = 0; counter < 80; ++counter)
{
if(counter < 20 || counter >= 60)
setMotorPower(40,-40);
else
setMotorPower(-40,40);
calibrate_sensors();
// 80*20 = 1600 ms.
delay(20);
}
setMotorPower(0, 0);
}
void store_sensor_cal(uint16_t address)
{
int32_t val = 0;
uint8_t bits = 0;
for(uint8_t i = 0; i < PI_GRND_SENSOR_COUNT*2;++i)
{
if(i < PI_GRND_SENSOR_COUNT)
val |= (int32_t(g_calibratedMinimum[i] & 0x7FF) << bits);
else
val |= (int32_t(g_calibratedMaximum[i-5] & 0x7FF) << bits);
bits += 11;
while(bits >= 8)
{
store_eeprom(address++, uint8_t(val & 0xFF));
val >>= 8;
bits -= 8;
}
}
if(bits)
store_eeprom(address, uint8_t(val));
}
void load_sensor_cal(uint16_t address)
{
int32_t val = 0;
uint8_t bits = 0;
for(uint8_t i = 0; i < PI_GRND_SENSOR_COUNT*2;)
{
val |= (int32_t(load_eeprom<uint8_t>(address++)) << bits);
bits += 8;
while(bits >= 11)
{
if(i < 5)
g_calibratedMinimum[i] = (val & 0x7FF);
else
g_calibratedMaximum[i-5] = (val & 0x7FF);
val >>= 11;
bits -= 11;
++i;
}
}
}
// int PololuQTRSensors::readLine(unsigned int *sensor_values,
// unsigned char readMode, unsigned char white_line)
// from Pololu lib, src/PololuQTRSensors/PololuQTRSensors.cpp
// Operates the same as read calibrated, but also returns an
// estimated position of the robot with respect to a line. The
// estimate is made using a weighted average of the sensor indices
// multiplied by 1000, so that a return value of 0 indicates that
// the line is directly below sensor 0, a return value of 1000
// indicates that the line is directly below sensor 1, 2000
// indicates that it's below sensor 2000, etc. Intermediate
// values indicate that the line is between two sensors. The
// formula is:
//
// 0*value0 + 1000*value1 + 2000*value2 + ...
// --------------------------------------------
// value0 + value1 + value2 + ...
//
// By default, this function assumes a dark line (high values)
// surrounded by white (low values). If your line is light on
// black, set the optional second argument white_line to true. In
// this case, each sensor value will be replaced by (1000-value)
// before the averaging.
int16_t getLinePos(bool white_line = false)
{
bool on_line = false;
uint8_t i;
uint32_t avg = 0; // this is for the weighted total, which is long
// before division
uint16_t sum = 0; // this is for the denominator which is <= 64000
static int16_t last_value = 0; // assume initially that the line is left.
for(i = 0; i < PI_GRND_SENSOR_COUNT; ++i)
{
int16_t value = getSensorValue(i);
if(white_line)
value = 1024-value;
// keep track of whether we see the line at all
if(value > 200)
on_line = 1;
// only average in values that are above a noise threshold
if(value > 50)
{
avg += (int32_t)(value) * (i * 1024);
sum += value;
}
}
if(!on_line)
{
// If it last read to the left of center, return 0.
if(last_value < (PI_GRND_SENSOR_COUNT-1)*1024/2)
return 0;
else // If it last read to the right of center, return the max.
return (PI_GRND_SENSOR_COUNT-1)*1024;
}
last_value = avg/sum;
return last_value;
}
inline uint16_t getBatteryVoltage()
{
return (((uint32_t(getSensorValue(5, false))*PI_VCC+511)/1023)*3+1)/2;
}
inline uint8_t getTrimPct()
{
return (uint32_t(getSensorValue(6, false))*100)/1023;
}
inline uint16_t getTrimMV()
{
return (uint32_t(getTrimPct()) * PI_VCC)/100;
}
void init_sensors()
{
DIDR0 = (1<<ADC0D)|(1<<ADC1D)|(1<<ADC2D)|(1<<ADC3D)|(1<<ADC4D)|(1<<ADC5D);
ADCSRA = (1<<ADEN)|(1<<ADSC)|(1<<ADIF)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
ADCSRB = 0;
ADMUX = (1<<REFS0);
PORTC |= (1 << 0)|(1 << 1)|(1 << 2)|(1 << 3)|(1 << 4)|(1 << 5);
g_sensors.value[0] = 1024;
g_sensors.value[1] = 1024;
g_sensors.value[2] = 1024;
g_sensors.value[3] = 1024;
g_sensors.value[4] = 1024;
g_sensors.value[5] = 1024;
g_sensors.value[6] = 1024;
resetCalibration();
}
void clean_sensors()
{
ADCSRA = 0;
}
#endif
#ifndef PI_LIB_DISPLAY
#define PI_LIB_DISPLAY
/*
Mostly from OrangutanLCD.cpp - Library for using the LCD on the Orangutan LV, SV, SVP, X2, or 3pi robot.
This library incorporates some code originally written by Tom Benedict as part of Orangutan-Lib.
Released into the public domain.
*/
/*
* Copyright (c) 2008 Pololu Corporation. For more information, see
*
* http://www.pololu.com
* http://forum.pololu.com
* http://www.pololu.com/docs/0J18
*
* You may freely modify and share this code, as long as you keep this
* notice intact (including the two links above). Licensed under the
* Creative Commons BY-SA 3.0 license:
*
* http://creativecommons.org/licenses/by-sa/3.0/
*
* Disclaimer: To the extent permitted by law, Pololu provides this work
* without any warranty. It might be defective, in which case you agree
* to be responsible for all resulting costs and damages.
*/
// Read and write timing:
//
// Write Read
//
// Set RS & R/W Set RS & R/W
// Wait >= 40ns Wait >= 40ns
// Set E High Set E High
// Wait >= 150ns Wait >= 120ns
// [Data must be valid by now] [Data is now valid for read]
// Wait >= 80ns Wait >= 210ns
// Set E Low Set E Low
// Wait >= 10ns RS & R/W can change
// [Data, RS, & R/W can change]
//
// In both cases, E cannot be brought high, then low, then high again
// in less than 500ns.
//
// Even though all that timing information is in nanoseconds, we need
// to be concerned about it. At 20MHz, each AVR instruction executes
// in 50ns. There are delays in there that must be longer than 50ns,
// so we must make sure we wait an appropriate amount of time.
//
// Initialization:
//
// 4-Bit 8-Bit
//
// Wait >= 15ms Wait >= 15ms
// Send 0x3 Send 0x30
// Wait >= 4.1ms Wait >= 4.1ms
// Send 0x3 Send 0x30
// Wait >= 100us Wait >= 100us
// Send 0x3 Send 0x30
// Wait >= 100us Wait >= 100us
// Send 0x2
// Wait >= 100us
// Send 0x2 0x8 Send 0x38
// [Busy Flag is now valid] [Busy Flag is now valid]
// Check BF Check BF
// Send 0x0 0x8 Send 0x08
// Check BF Check BF
// Send 0x0 0x1 Send 0x01
// Check BF Check BF
// Send 0x0 0x6 Send 0x06
// Check BF Check BF
// Send 0x0 0xC Send 0x0C
//
// A point to consider: Prior to a write, the busy flag (BF)
// must be clear. During the time BF is not valid, apparently
// it stays clear. So the BF check can apparently operate
// even when BF is not valid. It simply will not cause any
// delays in execution. I do not know if this is universally
// true, but it appears to be true for the two LCD used on the
// Orangutan LV-168.
//
// Another point: On 4-bit interfaces, reading the busy flag
// is a little tricky. The same command that returns the busy
// flag also returns the cursor's current memory address. This
// requires 8-bits of I/O, even if we're not interested in the
// cursor's address. So to check for the busy flag we have to
// do two 4-bit reads, complete with all the timing mentioned
// above, even though we're discarding the contents of the second
// 4-bit read.
//
// The Orangutan LV, SV, SVP and 3pi use the LCD in 4-bit mode with E,
// R/W, and RS control lines. The Orangutan X2 uses the LCD in 8-bit
// mode with E, R/W, and RS control lines.
#define LCD_WIDTH 8
#define LCD_HEIGHT 2
// On the Orangutan LV-168 and 3pi robot, the LCD control lines are split between
// ports B and D:
#define LCD_DB4 PORTB1 // PB1
#define LCD_DB5 PORTB4 // PB4
#define LCD_DB6 PORTB5 // PB5
#define LCD_DB7 PORTD7 // PD7
#define LCD_RS_DDR DDRD
#define LCD_RS_PORT PORTD
#define LCD_E_DDR DDRD
#define LCD_E_PORT PORTD
#define LCD_RW_DDR DDRB
#define LCD_RW_PORT PORTB
#define LCD_RW PORTB0
#define LCD_RS PORTD2
#define LCD_E PORTD4
#define LCD_BF_DDR DDRD
#define LCD_BF_PIN PIND
#define LCD_BF_PORT PORTD
#define LCD_BF_MASK (1 << LCD_DB7)
// Since we're only using four data lines, and since the pins they're
// wired up to don't start with 0, we need to shift them into
// position in order to load their values into the LCD. Port B uses
// bits 1, 4, and 5. We need to make our data line up like this:
//
// PortB: 7 6 5 4 3 2 1 0
// LCD Data: 2 1 0
//
// PortD: 7 6 5 4 3 2 1 0
// LCD Data: 3
//
// Pass your 4-bit LCD data value to the LCD_PORTB_DATA and LCD_PORTD_DATA
// macros to get the respective PORTB and PORTD values. You can use them
// as follows:
//
// PORTB &= ~LCD_PORTB_MASK;
// PORTB |= LCD_PORTB_DATA(lcdData);
// PORTD &= ~LCD_PORTD_MASK;
// PORTD |= LCD_PORTD_DATA(lcdData);
#define LCD_PORTB_MASK ((1 << LCD_DB4) | (1 << LCD_DB5) | (1 << LCD_DB6))
#define LCD_PORTD_MASK (1 << LCD_DB7)
#define LCD_PORTB_DATA(data) (((data & 0x01) <<1 ) | ((data & 0x06) << 3))
#define LCD_PORTD_DATA(data) ((data & 0x08) << 4)
#define LCD_PORTB_DATA(data) (((data & 0x01) <<1 ) | ((data & 0x06) << 3))