Calling a Twilio Number to control Spark Core

Here is a project using Twilio to control Spark Core. Using Twilio we can easily create powerful IVRs. Twilio provides TwiML (Twilio Markup Language) to create IVRs. We can attach a TwiML file to a number, when a incoming call detected Twilio reads this XML file and process the XML file. We provide some texts that will speak out to the caller, gather digits from the caller, etc… Since this is not related to Spark Core, refer to this link for more details about the TwiML and how to attach to a number.

We instruct the Twilio speak some texts and gather digits from the caller. When the caller enters some digits, the Twilio will call a request URL. The entered digits will be passed to the URL. We can create a server side script to process these digits.

In this process the when the user enters a secret PIN then the Spark Cloud API is called to turn on a light, in this project the light is attached to the Digital Pin D7. The Spark Core is flashed with default Tinker firmware. In this demo if you input 55231# then the light will be turned on, if it is 55230# then the light will be turned off.

The following TwiML and PHP Script is used in this demo.

TwiML (Twilio.xml)

<?xml version="1.0" encoding="UTF-8"?>
    <Gather action="/twilioaction.php" method="GET">
            Thank you for trying Spark Core and Twilio Demo, please enter your PIN number, followed by the pound sign.
    <Say>We didn't receive any input. Goodbye!</Say>

Response Script (PHP) (twilioaction.php)

if($_REQUEST['Digits'] == '55231' || $_REQUEST['Digits'] == '55230'){
	$url = '<<codeid>>/digitalWrite';
	if($_REQUEST['Digits'] == '55231'){
		$data = array(
			'access_token' => '<<accesstoken>>', 
			'params' => 'D7,HIGH'
		$data = array(
			'access_token' => '<<accesstoken>>', 
			'params' => 'D7,LOW'

	// use key 'http' even if you send the request to https://...
	$options = array(
		'http' => array(
			'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
			'method'  => 'POST',
			'content' => http_build_query($data),
	$context  = stream_context_create($options);
	$result = file_get_contents($url, false, $context);
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	if($_REQUEST['Digits'] == '55231')
		echo "<Response><Say>Your light will be turned on, Goodbye!.</Say></Response>";
		echo "<Response><Say>Your light will be turned off, Goodbye!.</Say></Response>";
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<Response><Say>You entered " . $_REQUEST['Digits'] . ", you are not authorized to use this demo, Goodbye!.</Say></Response>";

How to use

  1. Create Twilio account,
  2. Purchase a Twilio Number (optional, you can use the general demo number),
  3. Copy and upload the above TwiML and PHP Script to the server,
  4. Configure the Number Properties (TwiML, see below image)

Demo Video