Arduino Serial object data type to create a variable containing a port reference

I am working on a project with ArduinoMega2560. Several serial ports are available, and I would like the variable to contain a link to one of them, something like this:

SerialPort port; if (something == somethingElse) port = Serial; else port = Serial1; byte b = 5; port.write(b); 

However, the Arduino documentation is either limited, or I did not find the information I'm looking for. I think I need it. "What is the type of Serial, Serial1, etc.?".

+6
source share
2 answers

The main C ++ type for Serial objects is HardwareSerial . You can find this in the files in <arduino path>\hardware\arduino\cores\arduino . Then you can use pointers using the following code:

 HardwareSerial *port; if (something == somethingElse) port = &Serial; else port = &Serial1; byte b = 5; port->write(b); 
+9
source

I don’t know anything about Arduino, but, as a rule, this is done on most microcontrollers, so this is what you point directly to the perigal register area, in this case the serial port. Suppose your MCU maps these registers as follows:

 // serial port 1 0x1234 SERIAL_CONTROL_REG 0x1235 SERIAL_DATA_REG 0x1236 SERIAL_STATUS_REG // serial port 2 0x2000 SERIAL_CONTROL_REG 0x2001 SERIAL_DATA_REG 0x2002 SERIAL_STATUS_REG 

Then you can monitor the port using a pointer, for example:

 #define SERIAL_PORT1 ((volatile uint8_t*)0x1234) #define SERIAL_PORT2 ((volatile uint8_t*)0x2000) typedef volatile uint8_t* serial_port_t; ... serial_port_t port; if (something == somethingElse) port = SERIAL_PORT1; else port = SERIAL_PORT2; 

Then it can be expanded so that you can use registers as variables, for example, using macros:

 #define SERIAL_CONTROL_REG(offset) (*(offset + 0)) #define SERIAL_DATA_REG(offset) (*(offset + 1)) #define SERIAL_STATUS_REG(offset) (*(offset + 2)) if(SERIAL_STATUS_REG(port) & some_mask) { SERIAL_DATA_REG(port) = 0xAA; } 

This is how you usually write common hardware drivers for MCU peripherals with more than one identical port on board.

0
source

Source: https://habr.com/ru/post/922361/


All Articles