本帖最后由 laythy 于 2021-7-23 15:56 编辑
小白求教:串口控制IO口问题:
想用串口接收数据,判断数据,然后控制IO口高低电平,来控制小车的轮子:ALPHA1脚接的A1,以此类推BETA2接的B2.按照下面的程序,给串口发1或2.3.4,都没反应。另外接的OLED没问题,正常。
#include <Arduino.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_RESET);
int ICByte; // 串口接收数据(1Byte)
#define ALPHA1 2
#define ALPHA2 3
#define BETA1 4
#define BETA2 5
void setup()
{
// put your setup code here, to run once:
pinMode(ALPHA1, OUTPUT);
pinMode(ALPHA2, OUTPUT);
pinMode(BETA1, OUTPUT);
pinMode(BETA2, OUTPUT);
digitalWrite(ALPHA1, LOW);
digitalWrite(ALPHA2, LOW);
digitalWrite(BETA1, LOW);
digitalWrite(BETA2, LOW);
Serial.begin(9600);
Serial.setTimeout(5000);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // 设置I2C地址 0x3C
display.clearDisplay(); // 清屏
display.setTextColor(WHITE); // 设置字体颜色 白色(只对Adafruit品牌的OLED有效)
display.display(); // 显示
display.setTextSize(2); // 设置字体大小 2
display.setCursor(0,0); // 设置显示位置(起始点,即左上角坐标)
display.print("Serial OK!");
display.display();
delay(1000);
}
void loop()
{
// put your main code here, to run repeatedly:
digitalWrite(ALPHA1, LOW);
digitalWrite(ALPHA2, LOW);
digitalWrite(BETA1, LOW);
digitalWrite(BETA2, LOW);
if (Serial.available() > 0)
{
ICByte = Serial.read();
display.clearDisplay();
display.setCursor(0,0);
display.print(ICByte);
display.display();
switch(ICByte)
{
case 1 :
digitalWrite(ALPHA1, HIGH);
digitalWrite(ALPHA2, LOW);
digitalWrite(BETA1, HIGH);
digitalWrite(BETA2, LOW);
delay(200);
break;
case 2 :
digitalWrite(ALPHA1, LOW);
digitalWrite(ALPHA2, HIGH);
digitalWrite(BETA1, HIGH);
digitalWrite(BETA2, LOW);
delay(200);
break;
case 3 :
digitalWrite(ALPHA1, LOW);
digitalWrite(ALPHA2, HIGH);
digitalWrite(BETA1, LOW);
digitalWrite(BETA2, HIGH);
delay(200);
break;
case 4 :
digitalWrite(ALPHA1, HIGH);
digitalWrite(ALPHA2, LOW);
digitalWrite(BETA1, LOW);
digitalWrite(BETA2, HIGH);
delay(200);
break;
default:
delay(200);
break;
}
}
else
{
display.clearDisplay();
display.setCursor(0,0);
display.print("Serial is Waiting...");
display.display();
ICByte=0;
}
}
|