User Tools

Site Tools


bok:sw:cpp:main

C++

Types

char

  • char for declaring 8 bits.
  • Typically used for a single character

Following are legal

char c1;
char c2 = 'A';
char c3 = 65
char str1[];
char str2[] = {'h', 'i'};
char str3[3];
char str4[3] = {'h', 'i'};
char str5[3] = {'h', 'i', '\0'}; 

If want to clear a character then

c1 = 0;

If want to clear a character array then

str1[0] = 0;

bool

bool boolSomeBoolean;

Can be initialized with…

bool boolSomeBoolean1 = false;
bool boolSomeBoolean2 = 1;

Functions

Changing type formats

char c = 'A';
Serial.print((byte)c); //prints 41
 
Serial.print(c, HEX); //prints 41
Serial.print(c, BIN); //prints 01000001
Serial.print(c, DEC); //prints 65

Strings

Serial.print("Hi"); //Hi
Serial.println("Hi); //Hi then new line
Serial.print("Hi\n"); //Hi then new line. No space needed between text and \n

Structure

if ... else

if (condition) {statement;}
if else (condition) {statement;}
else {statement;}

A shorthand is available for simple if…else statements

variable = (condition) ? trueStatement : falseStatement;

E.g.

variable = ( today == birthday ) ? "Happy Birthday" : "Good day!";

for

for(int i = 0; i < limit; i++) {
statement;
}

Boolean Operators

&& // logical AND
|| // logical OR
! // logical NOT

Compound Operators

^= // compound bitwise XOR
+= // compound addition
-= // compound substraction

C++ for Arduino

SoftwareSerial

To use a Digital Pin as either Rx or Tx, other than the hardware designated Rx and Tx pins (pin 0 and pin 1), then shall use SoftwareSerial.

To do so to

#include <SoftwareSerial.h>
 
SoftwareSerial mySerial(2,3); // Rx, Tx
 
void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
}
 
void loop() {
  while( mySerial.available() ) {
    int i = mySerial.read();
    mySerial.write(i);
    Serial.print("Some text");
  }
}
bok/sw/cpp/main.txt · Last modified: 2021/08/12 01:27 by anwlur