|
实际上,与Arduino开发板进行串口通信非常简单。在本篇文章中,我们将介绍如何进行温度测量,然后通过串口发送测量结果。
与其他设备不同,Arduino串口通信非常易于使用。串口通信可以是有线或无线的,例如串口蓝牙连接。 Arduino编程环境有一个串口监视器的工具,专门用于查看串口数据通信。要激活通信,使用以下方法:
1. 转到工具栏; 2. 单击串口监视器(Serial Monitor)菜单; 3. 选择Serial.begin()函数设定的波特率。
以下是一些Arduino串口通信函数。
Serial.begin(speed) 此函数设置串行通信速度。它有一个参数speed,通常设置为9600。
Serial.read() 此函数从串口接收数据。
Serial.write(VAL) 该函数通过串口发送数据。参数val可以是单个变量、字符串或数组。
Serial.printIn(val,format) 此函数使用某种特定格式将val打印到Arduino IDE串口监视器。
使用LM35进行温度测量 LM35是一款用于测量环境温度的温度传感器。该设备的不同封装如下所示。
LM35提供与温度成比例的线性输出,0 V对应0℃,每度C变化输出电压变化10 mV。 LM35比热敏电阻和热电偶更容易使用,因为它们是线性的,不需要信号调制。
LM35的输出可以直接连接到Arduino模拟输入。由于Arduino模数转换器(ADC)的分辨率为1024位,参考电压为5 V,因此用于根据ADC值计算温度的公式为: - temp = ((5.0 * analogRead(pin)) / 1024) * 100.0
复制代码
实验所需的硬件 ● LM35温度传感器 ● LED指示灯 ● 220欧姆电阻器 ● Arduino Mega2560开发板 ● 面包板 ● 连接导线
电路原理图
按照上面的电路图所示连接组件。传感器由Arduino的5V和GND引脚供电。其输出端子连接到Arduino的引脚A0。当使用函数analogRead(0)读取该模拟电压的值时,程序返回0到1023之间的值。程序使用以下公式计算温度: - temp = ((5.0 * analogRead(pin)) / 1024) * 100.0
复制代码或者 - temp = analogRead(pin) * 0.48828125;
复制代码
最后,温度读数使用Serial.print()函数打印输出到IDE串口监视器。如下面的截图所示:
代码 该实验的代码如下所示。除了在IDE串口监视器上显示温度之外,如果测量温度约为70摄氏度,程序将点亮黄色LED指示灯,如果低于70摄氏度,程序将点亮绿色LED指示灯。通过使用if-else条件语句和digitalWrite(pin,status)实现。 - const int adc = 0 ; //naming pin 0 of analog input side as adc
- const int high = 8 ; // For turning on and off yellow LED
- const int low = 9 ; // For turning on and off Green LED
- void setup()
- {
- Serial.begin(9600) ; //Starting serial Communication at baud rate of 9600
-
- pinMode(high,OUTPUT); //declaring LED pins as OUTPUT
- pinMode(low,OUTPUT);
- }
- void loop()
- {
- int adc = analogRead(0) ; //reading analog voltage and storing it in an integer
- adc = adc * 0.48828125; //converting reading into Celsius
- Serial.print("TEMPRATURE = "); //to Display on serial monitor
- Serial.print(adc); //this will show the actualtemp
- Serial.print("*C"); //TEMPRATURE = 27*C ETC
- Serial.println(); //To end the line
- delay(1000); //1 Sec delay
-
- /*
- if (temperature (adc) > 70 ° C )
- turn on Yellow Leds
- turn off Green Leds
- else
- turn off Yellow Leds
- turn on Green Led
- */
-
- if(adc>70) // This is the control statement
- {
- digitalWrite(high,HIGH) ;
- digitalWrite(low,LOW) ;
- }
- else
- {
- digitalWrite(high,LOW) ;
- digitalWrite(low,HIGH) ;
- }
- }
复制代码
|