Project

General

Profile

Raspberry PI GPIO Scol plugin
rpiservo.cpp
1
2#include "rpiservo.h"
3#include "plugin.h"
4
5#include <string>
6#include <algorithm>
7#include <iostream>
8
9#include <boost/thread.hpp>
10
11#ifdef RPI
12#include <wiringPi.h>
13#include <time.h>
14#include <sys/time.h>
15#endif
16
17long mapData(float x, long in_min, long in_max, long out_min, long out_max)
18{
19 return (long)((x - (float)in_min) * ((float)out_max - (float)out_min) / ((float)in_max - (float)in_min) + (float)out_min);
20}
21
22//
23//Class RpiServo
24//
25
26RpiServo::RpiServo()
27{
28}
29
30RpiServo::RpiServo(int pin, float value):
31 mPin(pin),
32 mValue(1500), // midpoint
33 mState(false)
34{
35 WriteValue(value);
36
37#ifdef RPI
38 pinMode(mPin, OUTPUT);
39 digitalWrite(mPin, LOW);
40
41 mState = true;
42
43 boost::thread::attributes attrs;
44 struct sched_param param;
45 param.sched_priority = 50;
46 pthread_attr_setschedparam(attrs.native_handle(), &param);
47
48 mThread = boost::thread(attrs, boost::bind(&RpiServo::threadLoop, this));
49#endif
50
51}
52
53RpiServo::~RpiServo()
54{
55#ifdef RPI
56 if (mState)
57 {
58 mState = false;
59 mThread.join();
60 }
61 digitalWrite(mPin, LOW);
62#endif
63}
64
65void RpiServo::threadLoop()
66{
67#ifdef RPI
68 while (mState)
69 {
70 //wave cycle duration is 20 millisecond, rotation value between 1 and 2 millisecond
71 digitalWrite(mPin, HIGH);
72 delayMicroseconds(mValue);
73 digitalWrite(mPin, LOW);
74
75 // Wait until the end of an 8mS time-slot
76 boost::this_thread::sleep_for(boost::chrono::microseconds(20000 - mValue));
77 }
78#endif
79}
80
81void RpiServo::WriteValue(float value)
82{
83 if (value < 0.0f)
84 value = 0.0f;
85 else if (value > 180.0f)
86 value = 180.0f;
87
88 mValue = mapData(value, 0, 180, -250, 1250) + 1000;
89}