Lecture 04_05-IoT
C Programming Fundamentals
Primary Data Types:
char or unsigned char: 8-bit
int or unsigned int: 16-bit
short int: 8-bit
long int: 32-bit
float: 32-bit
double: 64-bit
long double: 80-bit
Operators in C
Mathematical Operators:
*: Multiplication/: Division%: Modulus (remainder)+: Addition-: Subtraction
Relational Operators:
<: Less than<=: Less than or equal to>: Greater than>=: Greater than or equal to==: Equal to!=: Not equal to
Logical Operators:
&&: Logical AND||: Logical OR!: Logical NOT
Assignment Operators:
=: Assign value+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=: Compound assignments
Control Structures
If Statement Syntax:
if (condition) { do this; }if (condition) { do this; } else { do this; }
Loop Structures:
While Loop:
while(condition) { do this; Increment; }For Loop:
for(initial; cond; incr) { do this; }
State Machine Design and TinkerCAD
Finite State Machine (FSM) Design for Arduino:
Components Required:
Inputs: Push Buttons (PB_ON and PB_OFF)
Output: LED
Design Steps:
Identify states (e.g., OFF, ON)
Create the hardware design using TinkerCAD
Write and test the code
Example State Machine Implementation
Declare Pins and States:
#define LED 2 #define Pb_ON 3 #define Pb_OFF 4 enum states {OFF, ON}; states currentstate = OFF;Setup Function:
void setup() { pinMode(LED, OUTPUT); pinMode(Pb_OFF, INPUT_PULLUP); pinMode(Pb_ON, INPUT_PULLUP); Serial.begin(9600); }Loop Function:
void loop() { switch(currentstate) { case OFF: if(digitalRead(Pb_ON) == LOW) { currentstate = ON; digitalWrite(LED, HIGH); } break; case ON: if(digitalRead(Pb_OFF) == LOW) { currentstate = OFF; digitalWrite(LED, LOW); } break; } }
Important Functions and Concepts
Serial Communication:
Serial.begin(9600);: Initializes serial communication at 9600 baud rateSerial.println(variable);: Sends variable data to the Serial Monitor
Input/Output Management:
digitalRead(pin): Reads the value from a specified digital pindigitalWrite(pin, value): Writes a value (HIGH or LOW) to a specified digital pin
Functional Decomposition:
It's often useful to encapsulate repetitive tasks in functions to promote code reuse and organization.
Pull-Up and Pull-Down Resistors
Pull-Up Configuration:
Button pressed = LOW (0)
Use Pull-Up Resistors or set
pinMode(pin, INPUT_PULLUP)in code.
Pull-Down Configuration:
Button pressed = HIGH (1)
Use Pull-Down Resistors or set
pinMode(pin, INPUT_PULLDOWN)in code (Arduino Zero family only).