From chipKIT
Jump to: navigation, search
Quick Look
Hardware (External hardware)
Core HardwareSerial.h

The HardwareSerial class implements methods for communicating with Hardware UARTs (Universal Asynchronous Receiver / Transmitter )

Detailed Introduction

The HardwareSerial class is derived from class Stream. It's purpose is to provide methods for sending and receiving data over the available UARTs.

Introductory Programs

attachInterrupt Example

Wiring Diagram

Fritzing Wiring Diagram

This example uses the chipKIT Max32 board by tying pins 17 (RX2) and 18 (TX1) with a short jumper wire.

/*                                                                      */
/*   attachInterrupt Example                                            */
/*                                                                      */
/*   Demonstrates how to use the attachInterrupt() function             */
/*   from HardwareSerial.h. Tthis example akes an input from Serial     */
/*   (Serial Monitor) then passes it to Serial1 (TX) which              */
/*   is connected via a physical wire to Serial2 (RX). Each time        */
/*   Serial2 receives a byte the myCallback function is fired.          */
/*   The callback appends the received character to a character         */
/*   array (inString) and increments a counter. When a newline          */
/*   character is received or when the character array is filled,       */
/*   the character array is printed to Serial Monitor.                  */
/*   Author:     David Powell                                           */
/*   Created:    3/31/2017                                              */
/*  Revision History:  None                                             */
/*  Test String:                                                        */
/*     abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ             */
#include <string.h>
// Maximum number of characters our character string can hold
#define MAX_STRING_LEN 26 
char inByte;
int printFlag = false;
char inString[MAX_STRING_LEN] = "";
volatile int count = 0;
/* Used by myISR to Append Characters*/
void appendChar(char* s, char c)
    int len = strlen(s);  // Get the current length of our string  
    s[len] = c;           // Place our new character at the end of the string
    s[len+1] = '\0';      // Add string terminator to end of string
void myCallback(int c) 
    appendChar(inString, c); // Add character c to the inString character array
    count++;                 // Count is equal to the number of times the interrupt appended a character
void setup() {
  // Initialize the serial ports:
  Serial2.attachInterrupt(myCallback); // When char received on RX line fire callback
void loop() {
  while (Serial.available())
    if(count < MAX_STRING_LEN)
      inByte = Serial.read();     // Read a byte from the hardware buffer
      if(inByte != '\r' && inByte != '\n')
        Serial.print(inByte);     // Echo the Serial Monitor Input to Monitor Output         
        Serial1.print(inByte);    // Send the byte fom Serial1 to Serial2 via physical wire
    if(count == MAX_STRING_LEN || (count !=0 && inByte == '\r'))
      Serial.println("");                 // Blank line for formatting
      Serial.print("Received String: ");  // Label the character string array output
      Serial.println(inString);           // Print our character string array
      Serial.print("Count: ");            // Label the count output
      Serial.println(count);              // Print the number of times our callback was fired
      Serial.println("");                 // Blank line for formatting
      inString[0] = '\0';                 // Move string terminator to the beginning of the character array
      count = 0;                          // Reset the counter

Full library usage



HardwareSerial(p32_uart * uartP, int irq, int vec, int ipl, int spl, isrFunc isrHandler, int pinT, int pinR, ppsFunctionType ppsT, ppsFunctionType ppsR);

Create a new HardwareSerial object for PIC32MX1XX, PIC32MX2XX, PIC32MZXX, PIC32MX47X based boards

HardwareSerial(p32_uart * uartP, int irq, int vec, int ipl, int spl, isrFunc isrHandler);

Create a new HardwareSerial object for boards based on microcontrollers not listed above.

Constructor Parameters

Parameter Description
uartP Pointer to base register for UART
irq Base IRQ number for UART
vec Interrupt vector for the UART
ipl Interrupt priority level
spl Interrupt sub-priority level
isrHandler Interrupt Service Routine Handler
pinT Digital pin number of TX
pinR Digital pin number of RX
ppsT Peripheral Pin Select for UART TX
ppsR Peripheral Pin Select for UART RX

Public Functions


void	doSerialInt(void);

This function is called by the interrupt service routine for the UART being used by this object. It's purpose is to process receive interrupts and place the received characters into the receive buffer.

attachInterrupt(void (*callback)(int))

void	attachInterrupt(void (*callback)(int));

Attach the interrupt. The callback parameter takes a funtion pointer.


void myCallback(int c) {
    //Do Something Quick
void setup() {


void	detachInterrupt();

Detach the interrupt

enableAddressDetection (void)

void	enableAddressDetection (void);

Sets the bit in the UART status register that enables address detection


void	disableAddressDetection(void);

Clears the bit in the UART status register that enables address detection

begin(unsigned long baudRate)

void	begin(unsigned long baudRate);

Initialize the UART for use, setting the baud rate to the requested value, data size of 8-bits, and no parity.

begin(unsigned long baudRate, uint8_t address)

void	begin(unsigned long baudRate, uint8_t address);

Initialize the UART for use, setting the baud rate to the requested value, data size of 9-bits, and no parity and address detection mode


void	end();

Disable the UART and UART interrupts.

Virtual Private Functions


virtual in	available(void);

Return the number of characters currently available in the receive buffer.


virtual int	peek();

This returns the next character in the receive buffer without removing it from the buffer, or -1 if no characters are in the buffer.


virtual int	read(void);

Return the next character from the receive buffer and remove it from the buffer, or -1 if no characters are available in the buffer.


virtual void	flush(void);

Empty the send buffer by waiting for the fifo to empty and the transmitter to become idle


virtual void	purge(void);

Empty the receive buffer by discarding any characters in the buffer.


virtual	size_t	write(uint8_t);

Wait until the transmitter is idle, and then transmit thespecified character.

Print Class Functions

The following write functions are pulled in from the Print class.

write(const char *str)

size_t   write(const char *str);

write(const char *buffer, size_t size)

size_t   write(const char *buffer, size_t size);

Conversion Operator


operator  int();

Returns 1

External Links