Hey Forum,
This post is in reference to my last post about mapping analog data to shift registers.
To summarize, I'm attempting to use an N-channel MOSFET transistor to drive a series of LEDs and their brightness (PWM) based on analog data from an accelerometer. I've succeeded in mapping the analog data to LEDs, but by using a pin off the Arduino for each LED so now, I want to consolidate everything and use the transistor to PWM all the LEDs only using one pin off the Arduino.
However, I'm stuck - I can't turn on the LEDs using the transistor. This is the original code I used to PWM individual pins:
const int Xdata = A0; // Analog input pin that the accelerometer is attached to
const int greenPin1 = 2; // Analog output pin that the LED is attached to
const int greenPin2 = 3;
int sensorValue = 0; // value read from the accelerometer
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog in value:
sensorValue = analogRead(Xdata);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 525, 0, 654);
// change the analog out value:
analogWrite(greenPin1, outputValue);
analogWrite(greenPin2, outputValue);
// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.println(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 10 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
}
I'm having trouble combining this sketch with the last example sketch proposed by Nick Gammon to achieve the overall LED pwm effect. It's slightly confusing because I'm no longer using the shift register like the sketch implies:
#include <SPI.h>
const byte LATCH = 10;
void setup ()
{
SPI.begin ();
} // end of setup
const byte maxDimIterations = 63;
byte c;
void loop ()
{
c++;
for (byte bright = 0; bright < maxDimIterations; bright++)
{
analogWrite (5, bright * 4);
digitalWrite (LATCH, LOW);
SPI.transfer (c);
digitalWrite (LATCH, HIGH);
delay (10);
} // end of for
} // end of loop
NOT TO MENTION the example sketch on bildr.org for transistors doesn't really help clarify things..:
//////////////////////////////////////////////////////////////////
//©2011 bildr
//Released under the MIT License - Please reuse change and share
//Simple code to output a PWM sine wave signal on pin 9
//////////////////////////////////////////////////////////////////
#define fadePin 3
void setup(){
pinMode(fadePin, OUTPUT);
}
void loop(){
for(int i = 0; i<360; i++){
//convert 0-360 angle to radian (needed for sin function)
float rad = DEG_TO_RAD * i;
//calculate sin of angle as number between 0 and 255
int sinOut = constrain((sin(rad) * 128) + 128, 0, 255);
analogWrite(fadePin, sinOut);
delay(15);
}
}
Any insight you can give is greatly appreciated. Thanks!
