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
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
//     RustDuino : A generic HAL implementation for Arduino Boards in Rust
//     Copyright (C) 2021  Devansh Kumar Jha, 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/>

//! ATMEGA2560P has total of 4 USARTs.
//! This is the file which contains functions for initializing USART in various modes.
//! It has functions to check for the power reduction settings and start the USART in a user defined modes.
//! After setting into a particular USART the functions are available to generate the clock with given
//! frequency and baud rate. After which the frame for data tracking is set using various frame modes.
//! See the section 22 of ATMEGA2560P datasheet.

// Other source code files to be used.
use crate::atmega2560p::hal::interrupts;
use crate::atmega2560p::hal::port;
use crate::atmega2560p::hal::power;

// Crates which would be used in the implementation.
// We will be using standard volatile and bit_field crates now for a better read and write.
use crate::delay::delay_ms;
use bit_field::BitField;
use core::ptr::write_volatile;
use core::{f64, u32, u8};
use volatile::Volatile;

// Some useful constants regarding bit manipulation for USART.
// Position of clock mode adjuster (xck) bit.
const USART0_XCK: u8 = 2;
const USART1_XCK: u8 = 5;
const USART2_XCK: u8 = 2;
const USART3_XCK: u8 = 2;
// System Clock Crystal Oscillator Frequency in mHz.
const F_OSC: f64 = 1.0000;
const MULTIPLY: f64 = 1000000.00;

/// Selection of which USART is to be used.
#[derive(Clone, Copy)]
pub enum UsartNum {
    Usart0,
    Usart1,
    Usart2,
    Usart3,
}

/// Selection of synchronous or asynchronous modes for USART.
#[derive(Clone, Copy)]
pub enum UsartModes {
    Normasync,
    Douasync,
    Mastersync,
    Slavesync,
}

/// Selection of the parity mode for USART.
#[derive(Clone, Copy)]
pub enum UsartParity {
    No,
    Even,
    Odd,
}

/// Selection of the Amount of Data Bits to be transferred or recieved through USART.
#[derive(Clone, Copy)]
pub enum UsartDataSize {
    Five,
    Six,
    Seven,
    Eight,
    Nine,
}

/// Selection of number of stop bits for USART data.
#[derive(Clone, Copy)]
pub enum UsartStop {
    One,
    Two,
}

/// Selection of the clock parity mode.
#[derive(Clone, Copy)]
pub enum UsartPolarity {
    Outputrise,
    Inputrise,
}

/// This structure contains various registers needed to control usart communication
/// through ATMEGA2560P device.
/// Each USARTn ( n=0,1,2,3 ) is controlled by a total of 6 registers stored through this structure.
#[repr(C, packed)]
pub struct Usart {
    pub ucsra: Volatile<u8>,
    pub ucsrb: Volatile<u8>,
    pub ucsrc: Volatile<u8>,
    _pad: u8, // Padding to look for empty memory space.
    pub ubrrl: Volatile<u8>,
    pub ubrrh: Volatile<u8>,
    pub udr: Volatile<u8>,
}

/// Contains the Usart as a Raw Pointer along with it's name.
/// This controls a USART as a object for careful implementation.
#[repr(C, packed)]
pub struct UsartObject {
    pub usart: *mut Usart,
    pub name: UsartNum,
}

// new() functions to make the memory mapped IOs for both the structures.

impl Usart {
    /// This creates a new memory mapped structure of the type USART for it's control.
    /// # Arguments
    /// * `num` - a `UsartNum` object, which defines the USART for whom new reference is to be created.
    /// # Returns
    /// * `a reference to Usart` - which will be used to control the USART.
    pub unsafe fn new(num: UsartNum) -> &'static mut Usart {
        match num {
            UsartNum::Usart0 => &mut *(0xC0 as *mut Usart),
            UsartNum::Usart1 => &mut *(0xC8 as *mut Usart),
            UsartNum::Usart2 => &mut *(0xD0 as *mut Usart),
            UsartNum::Usart3 => &mut *(0x130 as *mut Usart),
        }
    }

    /// Returns the number (index) of the USART being used.
    /// Panics if the address is invalid.
    pub fn name(&self) -> UsartNum {
        let address = (self as *const Usart) as usize; // Gets address of port.
        match address {
            //  Return Usart Number based on the address read.
            0xC0 => UsartNum::Usart0,
            0xC8 => UsartNum::Usart1,
            0xD0 => UsartNum::Usart2,
            0x130 => UsartNum::Usart3,
            _ => unreachable!(),
        }
    }

    /// Creates a instance of UsartObject from the Usart instance available.
    pub fn create_object(&mut self) -> UsartObject {
        UsartObject {
            usart: self,
            name: self.name(),
        }
    }
}

impl UsartObject {
    /// This creates a raw pointer for formation of the serial structure ahead
    /// to control all the USARTs of ATMEGA2560P at one place.
    /// # Arguments
    /// * `num` - a `UsartNum` object, which defines the USART for whom new reference is to be created.
    /// # Returns
    /// * `a UsartObject` - which will be used to control the USART.
    pub unsafe fn new(num: UsartNum) -> UsartObject {
        Usart::new(num).create_object()
    }
}

impl UsartObject {
    /// Disable global interrupts for smooth non-interrupted functioning of USART.
    pub fn disable(&self) {
        unsafe {
            // Disable global interrupts.
            interrupts::Interrupt::disable(&mut interrupts::Interrupt::new());
        }
    }

    /// Re-enable global interrupts.
    pub fn enable(&self) {
        unsafe {
            // Enable global interrupts.
            interrupts::Interrupt::enable(&mut interrupts::Interrupt::new());
        }
    }

    /// Gives the port containing bits to
    /// manipulate Recieve,Transmit and XCK bit of the particular USART.
    /// # Returns
    /// * `a tuple` - which contains -
    ///     * `a mutable reference to Port object` - The port which controls the given USART.
    ///     * `a u8` - The index location of XCK bit for mode specific implementation.
    fn get_port_xck(&mut self) -> (&mut port::Port, u8) {
        let num: UsartNum = unsafe { (*self.usart).name() };
        match num {
            UsartNum::Usart0 => (port::Port::new(port::PortName::E), USART0_XCK),
            UsartNum::Usart1 => (port::Port::new(port::PortName::D), USART1_XCK),
            UsartNum::Usart2 => (port::Port::new(port::PortName::H), USART2_XCK),
            UsartNum::Usart3 => (port::Port::new(port::PortName::J), USART3_XCK),
        }
    }

    /// Gives information about the current mode of USART.
    /// # Returns
    /// `a boolean` - which is false for asynchronous and true for synchronous.
    fn get_mode(&mut self) -> bool {
        let mut src = unsafe { (*self.usart).ucsrc.read() };
        src = src & (1 << 6);
        if src == 0 {
            return false;
        } else {
            return true;
        }
    }

    /// Set clock polarity mode according to input from user.
    /// # Arguments
    /// * `mode` - a `UsartPolarity` object, which will be set for the USART.
    pub unsafe fn set_polarity(&mut self, mode: UsartPolarity) {
        if self.get_mode() == false {
            (*self.usart).ucsrc.update(|src| {
                src.set_bit(0, false);
            });
        } else {
            match mode {
                UsartPolarity::Outputrise => {
                    (*self.usart).ucsrc.update(|src| {
                        src.set_bit(0, false);
                    });
                }
                UsartPolarity::Inputrise => {
                    (*self.usart).ucsrc.update(|src| {
                        src.set_bit(0, true);
                    });
                }
            }
        }
    }

    /// Set's various modes of the USART which is activated.
    /// # Arguments
    /// * `mode` - a `UsartModes` object, which will be set for the USART.
    pub unsafe fn mode_select(&mut self, mode: UsartModes) {
        match mode {
            UsartModes::Normasync                                  // Puts the USART into asynchronous mode.
            | UsartModes::Douasync => {
                    (*self.usart).ucsrc.update( |src| {
                        src.set_bit(6,false);
                        src.set_bit(7,false);
                    });
            },
            UsartModes::Mastersync
            | UsartModes::Slavesync => {                           // Puts the USART into synchronous mode.
                    (*self.usart).ucsrc.update( |src| {
                        src.set_bit(6,true);
                        src.set_bit(7,false);
                    });
                    (*self.usart).ucsra.update( |sra| {
                        sra.set_bit(1,false);
                    });
            },
        }
        match mode {
            UsartModes::Normasync => {
                // Keeps the USART into normal asynchronous mode.
                (*self.usart).ucsra.update(|sra| {
                    sra.set_bit(1, false);
                });
            }
            UsartModes::Douasync => {
                // Puts the USART into double speed asynchronous mode.
                (*self.usart).ucsra.update(|sra| {
                    sra.set_bit(1, true);
                });
            }
            UsartModes::Mastersync => {
                // Puts the USART into master synchronous mode
                let (port, xck) = self.get_port_xck();
                write_volatile(&mut port.ddr, port.ddr | 1 << xck);
                // port.ddr.update( |ddr| {
                //     ddr.set_bit(xck,true);
                // });
            }
            UsartModes::Slavesync => {
                // Puts the USART into slave synchronous mode
                let (port, xck) = self.get_port_xck();
                write_volatile(&mut port.ddr, port.ddr & !(1 << xck));
                // port.ddr.update( |ddr| {
                //     ddr.set_bit(xck,false);
                // });
            }
        }
    }

    /// Set's the power reduction register so that USART functioning is allowed.
    /// # Arguments
    /// * `num` - a `UsartNum` object, for which the power configurations of the USART will be set.
    pub fn set_power(&mut self, num: UsartNum) {
        let pow: &mut power::Power;
        unsafe {
            pow = power::Power::new();
        }
        match num {
            UsartNum::Usart0 => {
                unsafe {
                    write_volatile(&mut pow.prr0, pow.prr0 & !(1 << 1));
                }
                // pow.prr0.update( |prr| {
                //     prr.set_bit(1,false);
                // });
            }
            UsartNum::Usart1 => {
                unsafe {
                    write_volatile(&mut pow.prr1, pow.prr1 & !(1));
                }
                // pow.prr1.update( |prr| {
                //     prr.set_bit(0,false);
                // });
            }
            UsartNum::Usart2 => {
                unsafe {
                    write_volatile(&mut pow.prr1, pow.prr1 & !(1 << 1));
                }
                // pow.prr1.update( |prr| {
                //     prr.set_bit(1,false);
                // });
            }
            UsartNum::Usart3 => {
                unsafe {
                    write_volatile(&mut pow.prr1, pow.prr1 & !(1 << 2));
                }
                // pow.prr1.update( |prr| {
                //     prr.set_bit(2,false);
                // });
            }
        }
    }

    /// Sets the interrupt bits in UCSRB so that ongoing data transfers can be tracked.
    unsafe fn _check(&mut self) {
        (*self.usart).ucsrb.update(|srb| {
            srb.set_bit(6, true);
            srb.set_bit(7, true);
        });
    }

    /// Checks for any currently undergoing recieval or transmission in the USART.
    /// # Returns
    /// * `a boolean` - Which is false if USART is busy otherwise true.
    unsafe fn check_ongoing(&self) -> bool {
        let ucsra = (*self.usart).ucsra.read();
        if ucsra.get_bit(6) == false && ucsra.get_bit(7) == false {
            true
        } else {
            false
        }
    }

    /// Set the appropriate bits for flushing out transmission and recieval.
    pub unsafe fn set_txn(&mut self) {
        (*self.usart).ucsra.update(|sra| {
            sra.set_bit(6, true);
        });
    }

    /// Reset the USART.
    pub unsafe fn reset(&mut self) {
        let sra: u8 = 0x00;
        (*self.usart).ucsra.write(sra);
    }

    /// Clock Generation is one of the initialization steps for the USART.
    /// If the USART is in Asynchronous mode or Master Synchronous mode then a internal
    /// clock generator is used while for Slave Synchronous mode we will use a external
    /// clock generator.
    /// Set the baud rate frequency for USART.
    /// Baud rate settings is used to set the clock for USART.
    /// # Arguments
    /// * `baud` - a i64, containing the baud rate frame to be set.
    /// * `mode` - a `UsartModes` object,
    fn set_clock(&mut self, baud: i64, mode: UsartModes) {
        let ubrr: u32;
        match mode {
            UsartModes::Normasync => {
                ubrr = (((F_OSC * MULTIPLY) / (16.00 * baud as f64)) - 1.00) as u32;
            }
            UsartModes::Douasync => {
                ubrr = (((F_OSC * MULTIPLY) / (8.00 * baud as f64)) - 1.00) as u32;
            }
            UsartModes::Mastersync => {
                ubrr = (((F_OSC * MULTIPLY) / (2.00 * baud as f64)) - 1.00) as u32;
            }
            _ => unreachable!(),
        }
        unsafe {
            (*self.usart).ubrrl.update(|ubrrl| {
                for i in 0..8 {
                    ubrrl.set_bit(i, ubrr.get_bit(i));
                }
            });
            (*self.usart).ubrrh.update(|ubrrh| {
                for i in 0..4 {
                    ubrrh.set_bit(i, ubrr.get_bit(i + 8));
                }
            });
        }
    }

    /// Set the limit of data to be handled by USART.
    /// # Arguments
    /// * `size` - a `UsartDatSize` object, the size of set of bits to transmit.
    unsafe fn set_size(&mut self, size: UsartDataSize) {
        match size {
            UsartDataSize::Five
            | UsartDataSize::Six
            | UsartDataSize::Seven
            | UsartDataSize::Eight => {
                (*self.usart).ucsrb.update(|srb| {
                    srb.set_bit(2, false);
                });
            }
            UsartDataSize::Nine => {
                (*self.usart).ucsrb.update(|srb| {
                    srb.set_bit(2, true);
                });
            }
        }
        match size {
            UsartDataSize::Five | UsartDataSize::Six => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(2, false);
                });
            }
            UsartDataSize::Nine | UsartDataSize::Seven | UsartDataSize::Eight => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(2, true);
                });
            }
        }
        match size {
            UsartDataSize::Five | UsartDataSize::Seven => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(1, false);
                });
            }
            UsartDataSize::Nine | UsartDataSize::Six | UsartDataSize::Eight => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(1, true);
                });
            }
        }
    }

    /// Set the parity bit for initializing frame of USART.
    /// # Arguments
    /// * `parity` - a `UsartParity` object, which gives the Parity bit mode for USART.
    unsafe fn set_parity(&mut self, parity: UsartParity) {
        match parity {
            UsartParity::No => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(4, false);
                    src.set_bit(5, false);
                });
            }
            UsartParity::Even => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(4, false);
                    src.set_bit(5, true);
                });
            }
            UsartParity::Odd => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(4, true);
                    src.set_bit(5, true);
                });
            }
        }
    }

    /// Set the number of stop bits in the USART frame.
    /// # Arguments
    /// * `stop` - a `UsartStop` object, which will be used to set the stop bits of data frame.
    unsafe fn set_stop(&mut self, stop: UsartStop) {
        match stop {
            UsartStop::One => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(3, false);
                });
            }
            UsartStop::Two => {
                (*self.usart).ucsrc.update(|src| {
                    src.set_bit(3, true);
                });
            }
        }
    }

    /// Set the frame format for USART.
    /// A serial frame is defined to be one character of data bits with
    /// synchronization bits (start and stop bits), and optionally
    /// a parity bit for error checking.
    /// The USART accepts all 30 combinations of the following as valid frame formats.
    /// # Arguments
    /// * `stop` - a `UsartStop` object, which will be used to set the stop bits of data frame.
    /// * `size` - a `UsartDatSize` object, the size of set of bits to transmit.
    /// * `parity` - a `UsartParity` object, which gives the Parity bit mode for USART.
    unsafe fn set_frame(&mut self, stop: UsartStop, size: UsartDataSize, parity: UsartParity) {
        self.set_size(size);
        self.set_parity(parity);
        self.set_stop(stop);
    }

    /// This is the cumulative function for initializing a particular
    /// USART and it will take all the necessary details about the mode
    /// in which the USART pin is to be used.
    /// # Arguments
    /// * `mode` - a `UsartModes` object, which defines the mode of USART to use.
    /// * `baud` - a i64, the baud rate of USART the user wants to set.
    /// * `size` - a `UsartDatSize` object, the size of set of bits to transmit.
    /// * `parity` - a `UsartParity` object, which gives the Parity bit mode for USART.
    /// * `stop` - a `UsartStop` object, which will be used to set the stop bits of data frame.
    pub unsafe fn initialize(
        &mut self,
        mode: UsartModes,
        baud: i64,
        stop: UsartStop,
        size: UsartDataSize,
        parity: UsartParity,
    ) {
        // Check that recieve and transmit buffers are completely cleared
        // and no transmission or recieve of data is already in process.
        let mut i: i32 = 100;
        while self.check_ongoing() == false {
            if i != 0 {
                delay_ms(1000);
                i = i - 1;
            } else {
                unreachable!()
            }
        }

        let num: UsartNum = (*self.usart).name();

        self.set_power(num); //  Set Power reduction register.
        self.reset();

        self.mode_select(mode); //  Set the USART at the given mode.

        //  Set the clock for USART according to user input.
        match mode {
            UsartModes::Slavesync => {}
            UsartModes::Normasync | UsartModes::Douasync | UsartModes::Mastersync => {
                self.set_clock(baud, mode);
            }
        }

        //  Set the frame format according to input.
        self.set_frame(stop, size, parity);
    }
}