使用 arduino 和光传感器移动电机

Moving a motor with an arduino and a photo-sensor

所以我开始使用我最近购买的 Arduino 套件,并且一直在尝试让电机移动(目前),然后再进行更复杂的操作。

我未来的小项目的重点是让 Arduino 在晚上感知 window 附近的光线。从那里它有望转动一个马达来敲响我的闹钟。虽然现在我只是想让电机在看到光时移动,一旦它停止看到光就关闭,因为我可以在几秒钟后添加自动关闭。

这是当前代码:

const int motorPin = 9;
const int sensorPin = 10;
int lightLevel, high = 0, low = 1023;

void setup()
{
  // Set up the motor pin to be an output:
  pinMode(motorPin, OUTPUT);

  // Set up the serial port:
  Serial.begin(9600);
}
void loop()
{
  motormoveLevel = analogRead(sensorPin);
  manualTune(); 
  analogWrite(motorPin, lightLevel);
}    


void manualTune()
{
  lightLevel = map(lightLevel, 0, 1023, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);
} 

它不编译,但是我从中导出的代码可以编译,这里是一个打开电机几秒钟然后间歇性关闭它的代码:

const int motorPin = 9;

void setup()
{
  // Set up the motor pin to be an output:
  pinMode(motorPin, OUTPUT);

  // Set up the serial port:
  Serial.begin(9600);
}

void loop()
{
   motorOnThenOff();
}


// This function turns the motor on and off like the blinking LED.
// Try different values to affect the timing.
void motorOnThenOff()
{
  int onTime = 3000;  // milliseconds to turn the motor on
  int offTime = 3000; // milliseconds to turn the motor off

  digitalWrite(motorPin, HIGH); // turn the motor on (full speed)
  delay(onTime);                // delay for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turn the motor off
  delay(offTime);               // delay for offTime milliseconds
}

此代码根据光电传感器打开和关闭 LED:

 const int sensorPin = 0;
 const int ledPin = 9;

 int lightLevel, high = 0, low = 1023;


void setup()
{
  pinMode(ledPin, OUTPUT);
}


void loop()
{
  lightLevel = analogRead(sensorPin);
  manualTune(); 
  analogWrite(ledPin, lightLevel);
}


void manualTune()
{
  lightLevel = map(lightLevel, 0, 1023, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);
} 

所以基本上,我正在尝试使用这两段代码让电机根据它是否感应到光线来移动。我的“弗兰肯斯坦的怪物”没有编译,因此,我想帮助结合这两个代码,使电机在光线照射到光电传感器时移动,而在它被覆盖时不移动(我已经知道如何接线) .

你不能在引脚 0 上模拟读取。你必须使用 A0-A5 (14-19)