rustduino 0.2.2

A generic HAL implementation for Arduino Boards in Rust
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
//     RustDuino : A generic HAL implementation for Arduino Boards in Rust
//     Copyright (C) 2021  Ayush Agarwal, Indian Institute of Technology Kanpur
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU Affero General Public License as published
//     by the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU Affero General Public License for more details.
//
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see <https://www.gnu.org/licenses/>

//! This is the implementation for Analog Referencing in Integrated circuit of AVR Chips.  
//! This code is written taking into account the features available in ATMEGA328P.
//! This code implements the Analog Read function to read from the buffer using analog signals.
//! This code implements the Analog Write function to write into the buffer using analog signals.
//! Refer to section 14,15,22 and 23 of ATMEGA328P datasheet.

// Crates to be used for the implementation.
use bit_field::BitField;
use core::ptr::write_volatile;
use volatile::Volatile;

// Source codes to be used here.
use crate::atmega328p::hal::pin::{AnalogPin, DigitalPin};
use crate::atmega328p::hal::power::Power;

/// Selection of reference type for the implementation of Analog Pins.
#[derive(Clone, Copy)]
pub enum RefType {
    DEFAULT,
    INTERNAL1V1,
    EXTERNAL,
}

/// Selection of timer mode for Timer 8 type.
#[derive(Clone, Copy)]
pub enum TimerNo8 {
    Timer0,
    Timer2,
}

/// Selection of timer mode for Timer 16 type.
#[derive(Clone, Copy)]
pub enum TimerNo16 {
    Timer1,
}

/// Structure to control the implementation of Integrated Analog Circuit.
#[repr(C, packed)]
pub struct AnalogComparator {
    acsr: Volatile<u8>,
}

/// Structure to control the digital signal access.
#[repr(C, packed)]
pub struct Digital {
    didr0: Volatile<u8>,
    didr1: Volatile<u8>,
}

/// Structure to control data transfer from Analog to Digital signal conversions.
#[repr(C, packed)]
pub struct Analog {
    adcl: Volatile<u8>,
    adch: Volatile<u8>,
    adcsra: Volatile<u8>,
    adcsrb: Volatile<u8>,
    admux: Volatile<u8>,
    didr0: Volatile<u8>,
    didr1: Volatile<u8>,
}

/// Structure to control the timer of type 8 for Analog Write.
pub struct Timer8 {
    tccra: Volatile<u8>,
    tccrb: Volatile<u8>,
    _tcnt: Volatile<u8>,
    ocra: Volatile<u8>,
    ocrb: Volatile<u8>,
}

/// Structure to control the timer of type 16 for Analog Write.
pub struct Timer16 {
    tccra: Volatile<u8>,
    tccrb: Volatile<u8>,
    _tccrc: Volatile<u8>,
    _pad0: u8,
    _tcntl: Volatile<u8>,
    _tcnth: Volatile<u8>,
    _icrl: Volatile<u8>,
    _icrh: Volatile<u8>,
    ocral: Volatile<u8>,
    _ocrah: Volatile<u8>,
    ocrbl: Volatile<u8>,
    _ocrbh: Volatile<u8>,
}

// Structure to control the timer of type 8 for Analog Write.
impl Timer8 {
    /// Create a memory mapped IO for timer 8 type which will assist in analog write.
    /// # Arguments
    /// * `timer` - a `TimerNo8` object, which defines the Timer number for which object is to be made.
    /// # Returns
    /// * `a reference to Timer8 object` - which will be used for further implementations.
    pub fn new(timer: TimerNo8) -> &'static mut Timer8 {
        match timer {
            TimerNo8::Timer0 => unsafe { &mut *(0x44 as *mut Timer8) },
            TimerNo8::Timer2 => unsafe { &mut *(0xB0 as *mut Timer8) },
        }
    }
}

// Structure to control the timer of type 16 for Analog Write.
impl Timer16 {
    /// Create a memory mapped IO for timer 16 type which will assist in analog write.
    /// # Arguments
    /// * `timer` - a `TimerNo16` object, which defines the Timer number for which object is to be made.
    /// # Returns
    /// * `a reference to Timer16 object` - which will be used for further implementations.
    pub fn new(timer: TimerNo16) -> &'static mut Timer16 {
        match timer {
            TimerNo16::Timer1 => unsafe { &mut *(0x80 as *mut Timer16) },
        }
    }
}

impl AnalogComparator {
    /// New pointer object created for Analog Comparator Structure.
    /// # Returns
    /// * `a reference to AnalogComparator object` - which will be used for further implementations.
    pub unsafe fn new() -> &'static mut AnalogComparator {
        &mut *(0x50 as *mut AnalogComparator)
    }
}

impl Digital {
    /// Creates a pointer object for Digital Structure.
    /// # Returns
    /// * `a reference to Digital object` - which will be used further.
    pub unsafe fn new() -> &'static mut Digital {
        &mut *(0x7E as *mut Digital)
    }
}

impl AnalogPin {
    /// Read the signal input to the analog pin.
    /// Any analog pin can be freely used for this purpose.
    /// # Returns
    /// `a u32` - Value read from the analog pin.
    pub fn read(&mut self) -> u32 {
        let pin = self.pinno;
        unsafe {
            let analog = Analog::new();

            analog.power_adc_disable(); //To enable ADC

            analog.adc_enable();

            analog.adc_auto_trig();

            analog.analog_prescaler(2);

            match pin {
                0 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b000);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(0, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                1 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b001);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(1, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                2 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b010);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(2, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                3 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b011);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(3, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                4 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b100);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(4, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                5 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b101);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(5, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                6 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b110);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(6, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                7 => {
                    analog.admux.update(|admux| {
                        admux.set_bits(0..3, 0b111);
                    });
                    analog.didr0.update(|didr0| {
                        didr0.set_bit(7, true);
                    });
                    analog.adcsrb.update(|mux| {
                        mux.set_bit(3, false);
                    });
                }
                _ => unreachable!(),
            }

            analog.adc_con_start();

            // wait 25 ADC cycles
            let mut a: u32 = 0;
            a.set_bits(0..8, analog.adcl.read() as u32);

            a.set_bits(8..10, analog.adch.read() as u32); // check logic syntax correctness

            analog.adc_disable();

            a
        }
    }
}

impl DigitalPin {
    /// This is used to write a PWM wave to a digital pin.
    /// Only 2-13 and 44-46 digital pins can be used in this function, other pins will lead to crash.
    /// All pin except 4 and 13 are set to give output at 490 hertz.
    /// pin 4 and 13 will give output at 980 hertz.
    /// # Arguments
    /// * `value1` - a u8, value to be written on the analog pin for output.
    pub fn write(&mut self, value1: u8) {
        self.pin.set_output();
        let pin1 = self.pinno;
        match pin1 {
            5 | 6 => {
                unsafe {
                    let pow = Power::new();
                    write_volatile(&mut pow.prr, pow.prr & (247));
                }
                let timer = Timer8::new(TimerNo8::Timer0);
                timer.tccra.update(|ctrl| {
                    ctrl.set_bits(0..2, 0b11);
                });
                timer.tccrb.update(|ctrl| {
                    ctrl.set_bits(0..4, 0b0011);
                });

                if pin1 == 5 {
                    timer.tccra.update(|ctrl| {
                        ctrl.set_bits(4..8, 0b0010);
                    });
                    timer.ocrb.write(value1);
                } else {
                    timer.tccra.update(|ctrl| {
                        ctrl.set_bits(4..8, 0b1000);
                    });
                    timer.ocra.write(value1);
                }
            }
            11 | 3 => {
                unsafe {
                    let pow = Power::new();
                    write_volatile(&mut pow.prr, pow.prr & (247));
                }
                let timer = Timer8::new(TimerNo8::Timer2);
                timer.tccra.update(|ctrl| {
                    ctrl.set_bits(0..2, 0b01);
                });
                timer.tccrb.update(|ctrl| {
                    ctrl.set_bits(0..4, 0b0100);
                });

                if pin1 == 11 {
                    timer.tccra.update(|ctrl| {
                        ctrl.set_bits(4..8, 0b0010);
                    });
                    timer.ocrb.write(value1);
                } else {
                    timer.tccra.update(|ctrl| {
                        ctrl.set_bits(4..8, 0b1000);
                    });
                    timer.ocra.write(value1);
                }
            }
            9 | 10 => {
                unsafe {
                    let pow = Power::new();
                    write_volatile(&mut pow.prr, pow.prr & (247));
                }
                let timer = Timer16::new(TimerNo16::Timer1);
                timer.tccra.update(|ctrl| {
                    ctrl.set_bits(0..2, 0b01);
                });
                timer.tccrb.update(|ctrl| {
                    ctrl.set_bits(0..5, 0b00011);
                });

                if pin1 == 9 {
                    timer.tccra.update(|ctrl| {
                        ctrl.set_bits(4..8, 0b0010);
                    });
                    timer.ocrbl.write(value1);
                } else if pin1 == 10 {
                    timer.tccra.update(|ctrl| {
                        ctrl.set_bits(4..8, 0b1000);
                    });
                    timer.ocral.write(value1);
                }
            }
            _ => unreachable!(),
        }
    }
}

impl Analog {
    /// New pointer object created for Analog Structure.
    /// # Returns
    /// * `a reference to Analog object` - which will be used for further implementations.
    pub unsafe fn new() -> &'static mut Analog {
        &mut *(0x78 as *mut Analog)
    }

    /// Used to enable the Analog to Digital Converter.
    pub fn adc_enable(&mut self) {
        self.adcsra.update(|aden| {
            aden.set_bit(7, true);
        });
    }

    /// Function to enable power after using ADC.
    pub fn power_adc_enable(&mut self) {
        {
            let pow = Power::new();
            pow.prr.set_bit(0, true);
            // self.prr.update(|aden| {
            //     aden.set_bit(0, true);
            // });
        }
    }

    /// Function to disable power after using ADC.
    pub fn power_adc_disable(&mut self) {
        {
            let pow = Power::new();
            pow.prr.set_bit(0, false);
            // self.prr.update(|aden| {
            //     aden.set_bit(0, false);
            // });
        }
    }

    /// Used to start a conversion in the ADC.
    pub fn adc_con_start(&mut self) {
        self.adcsra.update(|aden| {
            aden.set_bit(6, true);
        });
    }

    /// Used to stop auto triggering in the ADC.
    pub fn adc_auto_trig(&mut self) {
        self.adcsra.update(|aden| {
            aden.set_bit(5, false);
        });
    }

    /// Used to disable the ADC.
    pub fn adc_disable(&mut self) {
        self.adcsra.update(|aden| {
            aden.set_bit(7, false);
        });
    }

    /// Set prescaler for the ADC.
    /// # Arguments
    /// * `factor` - a u8, the prescaler power frequency factor to be set.
    pub fn analog_prescaler(&mut self, factor: u8) {
        match factor {
            2 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b000);
                });
            }
            4 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b010);
                });
            }
            8 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b011);
                });
            }
            16 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b100);
                });
            }
            32 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b101);
                });
            }
            64 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b110);
                });
            }
            128 => {
                self.adcsra.update(|adcsra| {
                    adcsra.set_bits(0..3, 0b111);
                });
            }
            _ => unreachable!(),
        }
    }
}

/// Function to create a reference for Analog signals.
/// # Arguments
/// * `reftype` - a `RefType` object, the type of reference setup required for the analog pins.
pub fn analog_reference(reftype: RefType) {
    let analog = unsafe { Analog::new() };
    match reftype {
        RefType::DEFAULT => {
            analog.admux.update(|admux| {
                admux.set_bits(6..8, 0b01);
            });
        }
        RefType::INTERNAL1V1 => {
            analog.admux.update(|admux| {
                admux.set_bits(6..8, 0b10);
            });
        }
        RefType::EXTERNAL => {
            analog.admux.update(|admux| {
                admux.set_bits(6..8, 0b00);
            });
        }
    }
}