多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
串口通信是arduino和PC机通信最简单的方式之一。以前的PC带有真正的串口,但是和arduino的电平标准不一样。后来,随着USB端口的出现,基本PC端就没有串口了。但是我们一般都可以通过USB模拟PC端的串口,因此现在依然可以让arduino和PC通过这个“串口”通信。 如果使用无线蓝牙模块和PC端通信也是可行的。其实我们的arduino下载程序的过程就是通过USB接口模拟串口实现的。 ![](https://img.kancloud.cn/12/60/1260ee4e89b7844e38a3bbcfe25d797f_621x722.png) 这个程序实现的功能描述如下:硬件包含一个四位拨码开关,通过数字输入端口将拨码信息输入arduino。拨码开关可以输入四位二进制数字,比如 1101,0101等等。而这个数字将被由串口从arduino传递给PC端;同时在串口监视器,PC端输入“1,2,3,4”控制显示的格式。1对应二进制格式,2对应16进制格式,3对应10进制格式,4对应8进制格式。这样我们实现两个设备(,arduino和PC端)的通信,这个通信上叫做双工通信。 ``` // constants won't change. They're used here to set pin numbers: const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin int dip=0; bool keyPressed=true; // variables will change: int buttonState = 0; // variable for reading the pushbutton status int incomingByte = 49; void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("1:BIN 2: HEX 3:DEC 4:OCT"); Serial.println("move the dip to change the data"); Serial.println("input 1,or 2,or 3,or 4 in the serial send window"); } void loop() { // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. If it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, HIGH); if(keyPressed==true) { dip=digitalRead(9); dip=dip*2+digitalRead(8); dip=dip*2+digitalRead(7); dip=dip*2+digitalRead(6); //Serial.println("1:BIN 2: HEX 3:DEC 4:OCT"); if(incomingByte==49) { Serial.println(dip,BIN); } else if(incomingByte==50) { Serial.println(dip,HEX); } else if(incomingByte==51) { Serial.println(dip,DEC); } else if(incomingByte==52) { Serial.println(dip,OCT); } keyPressed=false; } } else { // turn LED off: digitalWrite(ledPin, LOW); keyPressed=true; } if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); //Serial.println("1:BIN 2: HEX 3:DEC 4:OCT"); Serial.println("I received your choiece."); } } ```