Created
June 2, 2016 09:48
-
-
Save Michal-Fularz/69d7f996a321174f4d0ff550087ac4c7 to your computer and use it in GitHub Desktop.
Arduino code for reading the park distance sensors from Chinese car kit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Name: ParkDistanceControl.ino | |
Created: 4/14/2016 5:46:25 PM | |
Author: Amin | |
*/ | |
#include <SoftwareSerial\SoftwareSerial.h> | |
const uint8_t data_pin = 7; | |
const uint8_t led_pin = 13; | |
uint8_t sensor_data[32]; | |
unsigned long pulse_duration; | |
int serial_counter = 0; | |
SoftwareSerial softwareSerial(8, 9); // RX, TX | |
// the setup function runs once when you press reset or power the board | |
void setup() { | |
pinMode(data_pin, INPUT); | |
pinMode(led_pin, OUTPUT); | |
Serial.begin(115200); | |
softwareSerial.begin(9600); | |
} | |
uint8_t convertArrayToValue(uint8_t *array) | |
{ | |
uint8_t value = array[0]; | |
// send first byte converted to value throught the SerialPort | |
for (uint8_t i = 1; i < 8; i++) | |
{ | |
value = value << 1; | |
value += array[i]; | |
} | |
return value; | |
} | |
// the loop function runs over and over again until power down or reset | |
void loop() { | |
// wait for the long starting pulse | |
do | |
{ | |
pulse_duration = pulseIn(data_pin, HIGH, 3000); | |
} while (pulse_duration < 1800); | |
// get first short pulse | |
pulse_duration = pulseIn(data_pin, HIGH, 1000); | |
if (pulse_duration < 150) | |
{ | |
// read the four bytes | |
for (uint8_t i = 0; i < 32; i++) | |
{ | |
pulse_duration = pulseIn(data_pin, HIGH, 300); | |
// short is about 100us = 0 | |
// long is about 200us = 1 | |
if (pulse_duration < 150) | |
{ | |
sensor_data[i] = 0; | |
} | |
else | |
{ | |
sensor_data[i] = 1; | |
} | |
} | |
if (serial_counter < 10) | |
{ | |
softwareSerial.print("E"); | |
// send first byte converted to value throught the SerialPort | |
for (uint8_t i = 0; i < 3; i++) | |
{ | |
uint8_t value = convertArrayToValue(&sensor_data[i * 8]); | |
softwareSerial.print(value); | |
softwareSerial.print(","); | |
} | |
softwareSerial.print("\n"); | |
serial_counter++; | |
} | |
else | |
{ | |
serial_counter = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment