Parallax Propeller C Code Examples
Index Array Variables
This code demonstrates how to initialize and iterate through an integer array in C for the Parallax Propeller microcontroller.
int main() // Main function
{
int p[] = {1, 2, 3, 5, 7, 11}; // Initialize the array
for(int i = 0; i < 6; i++) // Count i from 0 to 5
{
print("p[%d] = %d\n", i, p[i]); // Display array element & value
pause(500); // 1/2 second pause
}
}
Scan to Integer
This example shows how to prompt a user for input, scan an integer value, and use it in a loop.
int reps; // Declare variable named reps
int main() // Main function
{
print("Enter reps: "); // User prompt to enter reps
scan("%d\n", &reps); // Scan reps user types
print("\nCounting to %d\n", reps); // Display value scanned
for(int n = 1; n <= reps; n++) // Count to value scanned
{
print("i = %d\n", n); // Display each step
}
print("\nDone!"); // Display when done
}
Ping Sensor Distance Measurement
This code demonstrates how to use a Ping))) sensor to measure distance in centimeters and display the result.
int main() // Main function
{
while(1) // Repeat indefinitely
{
int cmDist = ping_cm(15); // Get cm distance from Ping)))
print("cmDist = %d\n", cmDist); // Display distance
pause(200); // Wait 1/5 second
}
}
SD Card – Write and Read Operations
This code demonstrates how to write data to an SD card and then read it back using the Parallax Propeller.
int DO = 22, CLK = 23, DI = 24, CS = 25; // SD card pins on Propeller BOE
int main(void) // Main function
{
sd_mount(DO, CLK, DI, CS); // Mount SD card
FILE* fp = fopen("test.txt", "w"); // Open a file for writing
fwrite("Testing 123...\n", 1, 15, fp); // Add contents to the file
fclose(fp); // Close the file
char s[15]; // Buffer for characters
fp = fopen("test.txt", "r"); // Reopen file for reading
fread(s, 1, 15, fp); // Read 15 characters
fclose(fp); // Close the file
print("First 15 chars in test.txt:\n"); // Display heading
print("%s", s); // Display characters
print("\n"); // With a newline at the end
}
Multicore Processing with Cog
This code demonstrates how to run a function in a separate cog (core) to blink an LED concurrently.
void blink(); // Forward declaration
int main() { // Main function
cog_run(blink, 128); // Run blink in other cog
}
void blink() { // Blink function for other cog
while(1) { // Endless loop for other cog
high(26); // P26 LED on
pause(100); // ...for 0.1 seconds
low(26); // P26 LED off
pause(100); // ...for 0.1 seconds
}
}
