Posts Tagged ‘Code’
Open APOD v1.0 Release
I published my first Android application, “Open APOD”, on the Google Play Store. I have developed this application to learn Android programming. You can get all the sources on my github or download it from Google Play. The application is Open Source and free of all charges. Get it, comment it, rate it …
Astronomy Picture Of the Day on your Android
I spent the last week or so learning Android programming. I find it important, in the learning of a new programming tool, to write something with clear specifications. This forces you to work on the best solution instead of using easy to code work-arounds.
The specifications are:
- The application should allow the user to read the Astrophotography Picture Of the Day published by NASA at http://apod.nasa.gov/apod on it’s Android device
- The application needs to be compatible with Android 1.5 (SDK #3)
- The user should be able to access the APOD for any date since june 16th 1995
- The user should be able to directly access the APOD of the current day
- The user should be able to navigate to the previous and next APODs
- The user should be able to navigate to the previous and next APODs with fling gestures
- The user should be able to view the picture in full size by clicking the preview picture
- The user should be redirected to the APOD website when clicking on the full size picture
These were the initial requirements … I will add some more stuff in the upcoming days:
- Change the full size picture activity from a WebView to an ImageView. This will allow the implementation of the OnClickListener callback and the re-use of the image bitmap in memory.
- Caching of the APODs on the SD card. This will save bandwidth, an important issue when using mobile networks.
- Adding a splash screen while loading the first APOD. Since loading the images can take a while on mobile networks, a splash screen with a spinner would look more professional.
The actual version of the project is published on my Github at the following address:
https://github.com/pchretien/APOD Feel free to fork, copying is not stealing!
A Simple Arduino Task Scheduler (1)
My motivation to write a task scheduler framework is to help me faster develop new Arduino projects. In most projects, we repeat the same tasks over and over before getting to play with the new stuff.
You can jump into the code right now by downloading it from my github account at:
https://github.com/pchretien/scheduler.
ITask Interface
Before using the scheduler functionalities, we have to explore the ITask interface. ITask is an interface that you must implement for all tasks to be scheduled and executed by the Scheduler. This interface has only two methods, “setup” and “run”.
The ITask::setup() method of your task object will be called in the global setup() function of your Arduino application. You place in this function all the initialization code your task object needs to execute correctly.
The ITask::run(Scheduler*) method is the method called by the scheduler when your task object is scheduled to run. It receives a reference to the Scheduler object so that your task object can re-schedule itself or another task.
class ITask
{
public:
virtual void setup() = 0;
virtual void run(Scheduler* scheduler) = 0;
};
Scheduler Singleton
The scheduler has two methods to schedule a task to run. To schedule a task to run immediately you use the queue(ITask*) method. This will add a task to the queue of tasks ready to run.
Then, to schedule a task to run in the future, you should use the schedule(ITask*, int) method. This method will set a task to run in a defined number of milliseconds in the future.
class Scheduler
{
public:
Scheduler();
void setup();
void processMessages();
void queue(ITask* task);
void clearQueue();
void schedule(ITask*, int);
void clearSchedule();
private:
ITask* _taskQueue[QUEUE_MAX];
ScheduleItem _taskSchedule[SCHEDULE_MAX];
};
The setup() method should be called from the main setup() function of your Arduino application. Finally, you can clear the queue and the schedule by calling the clearQueue() and clearSchedule() functions.
Task Implementation
In this example I will create a task that will turn on/off a LED every 500 milliseconds. First, you must derive your task class from the ITask interface.
class Blinker : public ITask
{
public:
void setup();
void run(Scheduler*);
Blinker(int, int);
private:
int _pin;
int _period;
int _state;
};
Following is the implementation of this task …
The constructor initializes internal values. Here, you can put all the code you want to run at the time of creation of the Task object.
Blinker::Blinker(int pin, int period)
{
_pin = pin;
_state = 0;
_period = period;
}
The “setup” method will be called from the setup() method of your Arduino program. In this example we only need to configure the digital pin #13 as an output.
void Blinker::setup()
{
pinMode( _pin, OUTPUT);
}
The “run” method will be called by the scheduler when the task is ready to run. In this example, the first thing the Task does is to re-schedule itself to run in _period milliseconds. Once re-scheduled, the Task will toggle the LED connected on pin number _pin of the Arduino micro-controller.
void Blinker::run(Scheduler* scheduler)
{
scheduler->schedule(this, _period);
_state = (_state>0)?0:1;
digitalWrite(_pin, _state);
}
Finally you must create the task and schedule it for the first run. In this example, the Task is created in the global scope and scheduled in the setup() method.
// Create a task scheduler singleton
Scheduler __scheduler;
...
// Create custom tasks
Blinker _blinker12(12, 1000);
...
void setup()
{
...
_blinker12.setup();
...
__scheduler.setup();
__scheduler.queue(&_blinker12);
// or ...
//__scheduler.schedule(&_blinker12, 1000);
...
}
void loop()
{
__scheduler.processMessages();
}
You can download the complete example from my Github account. In this example I drive five different Tasks in parallel. Two tasks are driving servo motors, two others are driving LEDs and the last is printing data on the serial port.
This is a work-in-progress project and will keep you informed of new developments as I go. If you try it, please leave me your impressions in the comment section below or contact me via my Github account.
Kids Clock V2.0
A big problem with my first version of the KidsClock was that despite my efforts to track time accurately, it was drifting a few minutes everyday. This is because the Arduino does not come with a built-in real time clock like full scale computers.
To fix that problem I added a real time clock chip, the DS1307, to my circuit. Using this chip and some libraries from the Arduino community have make the code a lot simpler.
The ds1307 circuit has a battery that allows your Arduino to be unpluged without losing time. This is a great improvement over the previous version.
The libraries I use can be found at:
http://code.google.com/p/arduino-time/
To set the time of the RTC to the local time I used this sample project:
http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock
Following is the code of the application. The clock red led turns on at 20:00h and the green led at 6:30 in the morning using the Alarm library.
/*
* kidsclock2.pde
*/
#include
#include
#include
#include
#define RED_LED 8
#define GREEN_LED 11
#define BOARD_LED 13
// 6:30 am every day
#define mh 6
#define mm 30
// 20:00 pm every day
#define eh 20
#define em 0
int boardLedState = HIGH;
void setup()
{
Serial.begin(9600);
setSyncProvider(RTC.get); // the function to get the time from the RTC
if(timeStatus()!= timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
Alarm.alarmRepeat(mh,mm,0, MorningAlarm);
Alarm.alarmRepeat(eh,em,0,EveningAlarm);
InitLEDs();
}
void InitLEDs()
{
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
pinMode(BOARD_LED, OUTPUT);
if( (hour() == mh && minute() >= mm ) ||
(hour() == eh && minute() < em) || (hour() > mh && hour() < eh) )
{
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
}
else
{
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
}
}
void MorningAlarm()
{
Serial.println("Alarm: - Morning");
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
}
void EveningAlarm()
{
Serial.println("Alarm: - Evening");
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
}
void loop()
{
boardLedState = !boardLedState;
digitalWrite( BOARD_LED, boardLedState);
digitalClockDisplay();
Alarm.delay(1000); // wait one second between clock display
}
void digitalClockDisplay()
{
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.println();
}
void printDigits(int digits)
{
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
Manage Virtual Assistant Using Git
It is now easy as 1-2-3 to hire a Virtual Assistant to help you out with your software development projects. You don’t have to be a large corporation to work with these oversea companies. The key to success with impartition reside, as many will tell you, in two things.
First, your ability to clearly define the work to do. You will get through it with time and practice. Communication is most often very hard because of the distance and the language barrier.
Second, your ability to control the quality and the velocity of the code produced by the team and to merge it to the final product. For that task you can get help from technologies such as Git, a distributed source control application.
In the context of impartition, Git becomes very effective because there is no need for the developers to know about it. Here is the sequence I use to work with remote Virtual Assistants:
- Since branching in Git is very effective and low cost, you start by creating a branch for a specific developer.
- Checkout the user branch
- Zip the project and send it to the programmer.
- Repeat 1 to 3 for all programmers.
- Once a programmer send back a zip of the project, you can use Git to view and merge all changes made by this user.
This can only be done on a distributed source control application. If you have several developer for a longer period of time, you may want to take time to teach Git to them so they can send you patches to simplify the merge process.
Arduino and Infrared (IR) Remotes
This Article is the first of a series on programming an Arduino micro controller to control X-10 devices using an infrared (IR) remote control. This is a relatively cheap project. To make the first part of this project you will need an Arduino micro-controller, an IR receiver and any IR remote control. The overall cost should not exceed $50.
First you need to crack the protocol of the IR remote control you picked up. You can pretty much use any IR remote control you have in your house - no complex circuit is required. If you purchased the ZX-IRM infrared receiver, you can connect it directly to your Arduino board. Otherwise, you will find plenty of information on the web on how to build an IR receiver.
Infrared communication is carried using pulses of infrared light. Most packets of data contain about 16 bits of data. The duration of the light pulse determines if the bit transferred is 0 or 1. The following program displays all light pulses received through the infrared (IR) receiver. This information will help you crack the protocol used by your remote control. Because of delays produced by the Serial communication with the Arduino board, there may be some inconsistencies in the data displayed. I recommend pressing more than once the remote key to get an accurate reading of the binary stream received.
These are the things you first have to look at when reading the program outputs:
- The duration of the START pulse.
- The duration of 0 and 1 pulses.
- The presence and duration of a STOP/REPEAT pulse.
- The length, in bits, of the data stream.
#define IR_LED 7
#define MAX 128
#define MICRO_STEP 10
#define IDLE_PULSE 10000
unsigned long pulses[MAX];
void setup()
{
pinMode(IR_LED, INPUT);
Serial.begin(115200);
}
void loop()
{
// The IR receiver output is set HIGH until a signal comes in ...
if( digitalRead(IR_LED) == LOW)
{
//Start receiving data ...
int count = 0;
int exit = 0;
while(!exit)
{
while( digitalRead(IR_LED) == LOW )
delayMicroseconds(MICRO_STEP);
// Store the time when the pulse begin
unsigned long start = micros();
int max_high = 0;
while( digitalRead(IR_LED) == HIGH )
{
delayMicroseconds(MICRO_STEP);
max_high += MICRO_STEP;
if( max_high > IDLE_PULSE )
{
exit = 1;
break;
}
}
unsigned long duration = micros() - start;
pulses[count++] = duration;
}
for(int i=0; i<count; i++)
{
if(pulses[i] > IDLE_PULSE)
{
Serial.print("<");
Serial.print(pulses[i], DEC);
Serial.print(">|");
}
else
{
Serial.print(pulses[i], DEC);
Serial.print("|");
}
}
Serial.println(".");
}
}
The start pulse is always the first and longest pulse of the stream. This pulse marks the starting point of the data stream. Subsequent to the start pulse are the data bits. There is no standard for this stream of bits but you will usually find about 8 to 16 bits of data.
Following the data stream, you should look for the stop pulse. The stop pulse is not mandatory and in most protocols, the stop pulse is used to signal command repetition. If the user maintains the remote button pressed, the stop pulse is sent repeatedly until the button is released. However, if there is no stop pulse, the data stream, starting with the start pulse, is repeatedly sent in its entirety when the remote button is maintained pressed.
Finally, you should look for the length of the data stream sent by the remote control every time a button is pressed. Most new remotes are using a fixed length data stream. You can easily determine the length of the stream by counting the number 0 and 1 pulses received for each command.
In the next article, I will put everything together and start writing code in order to use the remote control.
Philippe Chrétien
Kids Clock
Ok, that one is not rocket science but it realy realy worth the 20$ Arduino micro controller I used to make that kids clock.
The idea here is to make sure my 4 years old kid will not wake up at 3:30AM because he has confused the small needle with big needle. The code is real simple … red LED on before wake up time … green LED on after wake up time.
Following is the code … of course that could have been a lot more complicated but this is doing the job just fine. Stay tuned for future enhancements.
#include <avr/interrupt.h>
#include <avr/io.h>
#define INIT_TIMER_COUNT 6
#define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT
#define RED_LED 8
#define GREEN_LED 11
#define BOARD_LED 13
#define NIGHT_TIME 36000 // 10*60*60
int led13 = HIGH;
long counter = 0;
long stepStack = 0;
long seconds = 0;
// Aruino runs at 16 Mhz, so we have 1000 Overflows per second...
// 1/ ((16000000 / 64) / 256) = 1 / 1000
ISR(TIMER2_OVF_vect) {
RESET_TIMER2;
counter++;
if(!(counter%1000))
{
// enqueue step message
stepStack++;
}
};
void startup()
{
int led = 0;
for(int i=0; i<5; i++)
{
digitalWrite(RED_LED, led);
digitalWrite(GREEN_LED, led^1);
led ^= 1;
delay(500);
}
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
}
void setup()
{
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
pinMode(BOARD_LED, OUTPUT);
//Timer2 Settings: Timer Prescaler /64,
TCCR2A |= (1<<CS22);
TCCR2A &= ~((1<<CS21) | (1<<CS20));
// Use normal mode
TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
// Use internal clock - external clock not used in Arduino
ASSR |= (0<<AS2);
//Timer2 Overflow Interrupt Enable
TIMSK2 |= (1<<TOIE2) | (0<<OCIE2A);
RESET_TIMER2;
sei();
startup();
}
void loop()
{
if(stepStack)
{
// Toggle the LED
led13 ^= 1;
digitalWrite(13, led13);
seconds ++;
stepStack--;
}
if( seconds > NIGHT_TIME )
{
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
}
}
Go Dynamic with Google App Engine Cron Jobs
Using shared hosting services still is the most affordable solution for small and medium business projects. However, one of the features you often have to let go using shared hosting is server side autonomous processing.
Imagine you want to automatically send an email to all users with expired account or you want to clean a server cache once a day to save storage space, you will hit a wall using standard web hosting services. To get this kind of service you usually need to buy a dedicated hosting plan for several hundreds of dollars a month.
An other solution would be to buy a Linux Slice hosting plan but, then, you are on your own to secure and manage your server. This is a speciality not many programmers and web developers are familiar with. It takes a lot of your precious time just to keep the server up.
So, what would you think of a free and limitless solution to your server side processing needs? This is what Google App Engine offers through their Cron jobs implementation. You have full control over the scheduling of the cron jobs using the cron.yaml configuration file.
A Google App Engine cron job can call any url of your appstore application. From there, you can write your Python code to query your website using the URL fetch service. You cal also send emails using the Mail service.
You can do all that while keeping your actual website where is is. If you ever consider moving your website to an other hosting provider, your Google App Engine cron job will continue to work with no modifications.
Following is an example of a simple cron job definition.
Your comments are welcome,
Philippe Chrétien
app.yaml
application: yourappname
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: main.py
cron.yaml
cron:
- description: daily mailing job
url: /mailjob
schedule: every 24 hours
main.py
#!/usr/bin/env python
import cgi
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.api import urlfetch
class MailJob(webapp.RequestHandler):
def get(self):
# Call your website using URL Fetch service ...
url = "http://www.yoursite.com/page_or_service"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
# Send emails using Mail service ...
mail.send_mail(sender="admin@gmail.com",
to="someone@gmail.com",
subject="Your account on YourSite.com has expired",
body="Bla bla bla ...")
return
application = webapp.WSGIApplication([
('/mailjob', MailJob)], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
basbrun.appspot.com
I have updated my Google App Engine base website. You can try it at: basbrun.appspot.com and get the code at: http://github.com/pchretien/gaebase. This version is a merge with the developpement done on secretquiz.com.
The site offers a fully functionnal user management system with a simple contact form. The code is distributed under GPL so feel free to use it in your project.
Philippe Chrétien
Google App Engine Email Service
Help improving Google App Engine, go to the Google App Engine Issues page and vote for the issue 677. This is a big no go for many GAE developpers using the Mail service:
http://code.google.com/p/googleappengine/issues/list
Take a few minutes to read more about the needs of the Google App Engine community.
Philippe Chrétien





