chipKIT® Development Platform

Inspired by Arduino™

Last edit: 2021-03-21 22:34 by Majenko

HardwareSerial

HardwareSerial
Quick Look
Hardware (External hardware)
Core HardwareSerial.h

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

  1. Detailed Introduction

  2. Introductory Programs

    1. attachInterrupt Example

      1. Wiring Diagram

  3. Full library usage

    1. HardwareSerial

      1. Constructors

    2. Constructor Parameters

      1. Public Functions

        1. doSerialInt(void)

        2. attachInterrupt(void (*callback)(int))

        3. detachInterrupt()

        4. enableAddressDetection (void)

        5. disableAddressDetection(void)

        6. begin(unsigned long baudRate)

        7. begin(unsigned long baudRate, uint8_t address)

        8. end()

      2. Virtual Private Functions

        1. available(void)

        2. peek()

        3. read(void)

        4. flush(void)

        5. purge(void)

        6. write(uint8_t)

      3. Print Class Functions

        1. write(const char *str)

        2. write(const char *buffer, size_t size)

      4. Conversion Operator

        1. int()

  4. External Links

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

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

{{clear}}

/************************************************************************/
/*                                                                      */
/*   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:
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  
  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
        delay(5);
      }
    }
    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

Constructors

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


doSerialInt(void)

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.

Usage:

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

void setup() {
    Serial2.attachInterrupt(myCallback);
}

detachInterrupt()

void	detachInterrupt();

Detach the interrupt

enableAddressDetection (void)

void	enableAddressDetection (void);

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

disableAddressDetection(void)

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

end()

void	end();

Disable the UART and UART interrupts.

Virtual Private Functions


available(void)

virtual in	available(void);

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

peek()

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.

read(void)

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.

flush(void)

virtual void	flush(void);

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

purge(void)

virtual void	purge(void);

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

write(uint8_t)

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


int()

operator  int();

Returns 1

External Links