Arduino Fun
I finally had the time to assemble my Arduino kit, which mostly took soldering the protoshield together. My first program is fairly simple and written in C (as opposed to AVR assembler, which is actually pretty easy). I attached two LEDs and one switch with a pull-up resistor to the Arduino microcontroller. The small C program toggles the red and green LEDs when the button is hit, send the current state back to the computer via the USB port and accepts commands to turn on either the red or green LED from the computer.
The full source code:
int inPin = 11; // choose the input pin (for a pushbutton) int val = 0; // variable for reading the pin status bool pushed = false; bool greenState = true; bool redState = false; void setup() { pinMode(12, OUTPUT); // declare LED as output pinMode(13, OUTPUT); // declare LED as output pinMode(inPin, INPUT); // declare pushbutton as input digitalWrite(12, HIGH); // turn LED ON digitalWrite(13, LOW); // turn LED ON Serial.begin(9600); } void green(bool state) { digitalWrite(12, state ? HIGH : LOW); greenState = state; } void red(bool state) { digitalWrite(13, state ? HIGH : LOW); redState = state; } void toggle() { green(!greenState); red(!redState); printState(); } void printState() { Serial.print("Red "); Serial.print(redState, DEC); Serial.print(" Green "); Serial.println(greenState, DEC); } void loop(){ // remote control if (Serial.available() > 0) { int b = Serial.read(); if (b == 'g') { Serial.println("Turning on green"); red(false); green(true); } if (b == 'r') { Serial.println("Turning on red"); red(true); green(false); } if (b == 's') { printState(); } Serial.flush(); } // button handler val = digitalRead(inPin); // read input value if (val == HIGH) { // check if the input is HIGH (button released) if(pushed) { pushed = false; Serial.println("Button Released"); toggle(); } } else { if(!pushed) { pushed = true; Serial.println("Button Pushed"); } } }
Stay tuned for more Arduino fun.
February 1, 2009 | Filed Under Electronics
Comments
3 Responses to “Arduino Fun”
Leave a Reply
Hi Jochen,
glad to see you do some _real_ hacking ;)
Arduino is so much fun. Keep going!
Cheers,
Alex
[...] I’ve been meaning to post this for a while but got caught up with work stuff again. Thinking that talking to an Arduino from C# should be fairly easy, I spent a good hour or so fiddling with it because I could never get the Arduino to run my sketch after establishing the serial connection. Turns out, the DTR Enable line needs to be set to high for it to start executing the program. Here’s a quick hack which interacts with the program I posted previously: [...]
Hmm… this reminds of of strange light experiments in the past… Keep on going ;)
Cheers,
Oliver