Microcontroller basics Lesson 2 Serial communication via USB
Microcontroller basics
Lesson 2 • Serial communication via USB • Sensors
Serial communication over USB • Can be used for multiple things • Communicating with computer programs • Debugging – Serial Monitor is used for outputs with text and outputs that are less frequent – Serial Plotter is very useful for plotting data in real time quickly • Outputting sensor data for example • Requires the use of Serial library • Serial library is automatically included when Serial. begin() function is called
Arduino C – Serial functions Serial. begin(baud, config) Starts the serial communication over the USB. Baud is the desired speed of communication (baud rate) and config is the configuration mode (optional). Serial. println(”text”) Serial. println(var) Print a line to the serial port. After printing send a new line character (“n”). With quotes it sends text and without, it prints the contents of the variable. Serial. print(”text”) Serial. print(var) Same as the Serial. println() except it doesn’t send the new line character. MORE INFO: • http: //arduino. cc/en/reference/serial
Example 1 - Serial Using Serial communication over USB byte led. Pin = 13; void setup() { pin. Mode(led. Pin, OUTPUT); digital. Write(led. Pin, LOW); Serial. begin(9600); //Begin serial communication with baud rate 9600 } void loop() { digital. Write(led. Pin, HIGH); Serial. println(“LED ON”); //Send a line of text to serial port delay(1000); digital. Write(led. Pin, LOW); Serial. println(“LED OFF”); delay(1000); }
Sensors Temperature Magnetic field (Hall effect) Light Flex Acceleration Force Humidity Much more
Sensors • Used for measuring the environment • Measurements can be for example logged, displayed or used for controlling actuators • Using sensors outside their intended range may cause errors in the measurements or even break the sensor
Sensors • Sensors have a resolution that determines the smallest change the sensor can detect. • For sensors like the flex and force sensors this resolution is determined by the ADC (Analog Digital Converter) you use – Example: Potentiometer turns 270° and you measure it with a 10 -bit ADC • Resolution is 270° / 2^10 ≈ 0. 264°
Example 2 – Photoresistor Reading a photoresistor and printing to serial
Example 1 - Photoresistor Reading a photosensitive resistor and printing to serial byte pot. Pin = A 0; float LDR_Volts; void setup() { pin. Mode(pot. Pin, INPUT); Serial. begin(9600); } void loop() { LDR_Volts = analog. Read(pot. Pin) * (5. 0 / 1023. 0); Serial. print(”Voltage over the photoresistor: ” ); // Start of the line. No newline character Serial. print(LDR_Volts); // Voltage value Serial. println(“V”); // Units with a newline char from Serial. println() delay(1000); } Example Voltage Voltage of the serial output: over the photoresistor: over the photoresistor: 1. 18 V 0. 94 V 0. 76 V 0. 63 V 0. 51 V
In next lesson • Actuators • Control • PID
- Slides: 11