Project

General

Profile

Revision 08263708

ID082637087477fc8102faef8726839e84269dfafe
Parent 0e182761
Child 750e8795

Added by Haley about 10 years ago

added arduino and joystick code

View differences:

arduino/RCbuggyMega/RCbuggyMega.ino
1
/*
2
  Makes Arduino receive input from xbee and parse data.
3
 
4
 The circuit:
5
 * RX is digital pin 2 (connect to TX of XBee)
6
 * TX is digital pin 3 (connect to RX of XBee)
7
 
8
 */
9

  
10
//#include <SoftwareSerial.h>
11
#include <Servo.h> 
12

  
13
Servo myservo;  // create servo object to control a servo 
14

  
15
//SoftwareSerial xbee(2, 3); // RX, TX
16
unsigned long timer = 0L;
17
char data;
18
String message;
19
char intbuf[32];
20
int brake = 0;
21
int steeringAngle = 135;
22
int pingPong = 1;
23
int startfound = 0;
24
int midfound = 0;
25
int endfound = 1;
26

  
27
void setup()  {
28
  Serial.begin(9600);
29
  //Serial.println( "Arduino started sending bytes via XBee" );
30
  Serial1.begin(9600);
31

  
32
  pinMode(4, OUTPUT);
33
  pinMode(5, OUTPUT);
34
  pinMode(8, OUTPUT);
35
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
36
  myservo.write(133);
37
}
38

  
39
void loop()  {
40

  
41
  // receive and parse message from xbee
42
  if(Serial1.available() > 0) { 
43

  
44
    timer = millis();
45

  
46
    // read message from xbee
47
    data = Serial1.read();
48

  
49
    // parse message data
50
    if (data == 'A') {
51
      startfound = 1;
52
      midfound = 0;
53
      endfound = 0;
54
      message = "";
55
    }
56
    else if (data == 'B') {
57
      startfound = 0;
58
      midfound = 1;
59
      endfound = 0;
60
    }
61
    else if (data == 'C') {
62
      startfound = 0;
63
      midfound = 0;
64
      endfound = 1;
65
    }
66
    else if (startfound) {
67
      message = message + data;
68
    }
69
    else if (midfound) {
70
      if(data == '1')
71
        brake = 1;
72
      else
73
        brake = 0;
74
      message.toCharArray(intbuf, sizeof(intbuf));
75
      steeringAngle = atoi(intbuf);
76
    }  
77

  
78
    // flop external LED everytime message is recieved
79
    if ( pingPong == 0 ) {
80
      digitalWrite(4, LOW);
81
    } 
82
    else {
83
      digitalWrite(4, HIGH);
84
    }
85

  
86
    pingPong = 1 - pingPong;
87

  
88
  } // end receive message
89

  
90
  // brake if it has been greater than 3 seconds since we last got a message
91
  if( (millis() - timer) > 5000L ) {
92
    digitalWrite(8, 0);
93
    digitalWrite(5, HIGH);
94
    exit(1);
95
  }
96

  
97
  if((millis() - timer) > 2000L) {
98
    digitalWrite(12, HIGH);
99
  }
100
  else {
101
    digitalWrite(12, LOW);
102
  }
103

  
104
  // make brake LED light up if brakes should be down
105
  if( brake == 0 ) {
106
    digitalWrite(5, HIGH);
107
  } 
108
  else {
109
    digitalWrite(5, LOW);
110
  }
111

  
112
  // send parsed signal to brakes and servo
113
  digitalWrite(8, brake);
114

  
115
  // sets the servo position
116
  myservo.write(steeringAngle);
117
}
118

  
joystick/joystick.py
1
import pygame
2
import serial
3

  
4
# Define some colors
5
BLACK    = (   0,   0,   0)
6
WHITE    = ( 255, 255, 255)
7

  
8
# This is a simple class that will help us print to the screen
9
# It has nothing to do with the joysticks, just outputing the
10
# information.
11
class TextPrint:
12
    def __init__(self):
13
        self.reset()
14
        self.font = pygame.font.Font(None, 20)
15

  
16
    def printt(self, screen, textString):
17
        textBitmap = self.font.render(textString, True, BLACK)
18
        screen.blit(textBitmap, [self.x, self.y])
19
        self.y += self.line_height
20
        
21
    def reset(self):
22
        self.x = 10
23
        self.y = 10
24
        self.line_height = 15
25
        
26
    def indent(self):
27
        self.x += 10
28
        
29
    def unindent(self):
30
        self.x -= 10
31
    
32

  
33
pygame.init()
34
 
35
# Set the width and height of the screen [width,height]
36
size = [500, 700]
37
screen = pygame.display.set_mode(size)
38

  
39
pygame.display.set_caption("My Game")
40

  
41
#Loop until the user clicks the close button.
42
done = False
43

  
44
# Used to manage how fast the screen updates
45
clock = pygame.time.Clock()
46

  
47
# Initialize the joysticks
48
pygame.joystick.init()
49
    
50
# Get ready to print
51
textPrint = TextPrint()
52

  
53
# Set starting values
54
steeringAngle = 0
55
brake = 1
56

  
57
# Open serial port
58
ser = serial.Serial('COM8', 9600, timeout=5)
59

  
60

  
61
# -------- Main Program Loop -----------
62
while done==False:
63
    # EVENT PROCESSING STEP
64
    for event in pygame.event.get(): # User did something
65
        if event.type == pygame.QUIT: # If user clicked close
66
            done=True # Flag that we are done so we exit this loop
67
        
68
        # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION
69
        if event.type == pygame.JOYBUTTONDOWN:
70
            print("Joystick button pressed.")
71
        if event.type == pygame.JOYBUTTONUP:
72
            print("Joystick button released.")
73
            
74
 
75
    # DRAWING STEP
76
    # First, clear the screen to white. Don't put other drawing commands
77
    # above this, or they will be erased with this command.
78
    screen.fill(WHITE)
79
    textPrint.reset()
80

  
81
    # Get count of joysticks
82
    joystick_count = pygame.joystick.get_count()
83

  
84
    textPrint.printt(screen, "Number of joysticks: {}".format(joystick_count) )
85
    textPrint.indent()
86
    
87
    # For each joystick:
88
    for i in range(joystick_count):
89
        joystick = pygame.joystick.Joystick(i)
90
        joystick.init()
91
    
92
        textPrint.printt(screen, "Joystick {}".format(i) )
93
        textPrint.indent()
94
    
95
        # Get the name from the OS for the controller/joystick
96
        name = joystick.get_name()
97
        textPrint.printt(screen, "Joystick name: {}".format(name) )
98
        
99
        # Usually axis run in pairs, up/down for one, and left/right for
100
        # the other.
101
        axes = joystick.get_numaxes()
102
        textPrint.printt(screen, "Number of axes: {}".format(axes) )
103
        textPrint.indent()
104
        
105
        for i in range( axes ):
106
            axis = joystick.get_axis( i )
107
            textPrint.printt(screen, "Axis {} value: {:>6.3f}".format(i, axis) )
108
            if i == 0:
109
                steeringAngle = axis
110
        textPrint.unindent()
111
            
112
        buttons = joystick.get_numbuttons()
113
        textPrint.printt(screen, "Number of buttons: {}".format(buttons) )
114
        textPrint.indent()
115

  
116
        for i in range( buttons ):
117
            button = joystick.get_button( i )
118
            textPrint.printt(screen, "Button {:>2} value: {}".format(i,button) )
119
            if button == 1:
120
                if i == 1:
121
                    brake = 0;
122
                elif i == 3:
123
                    brake = 1;
124
        textPrint.unindent()
125
            
126
        # Hat switch. All or nothing for direction, not like joysticks.
127
        # Value comes back in an array.
128
        hats = joystick.get_numhats()
129
        textPrint.printt(screen, "Number of hats: {}".format(hats) )
130
        textPrint.indent()
131

  
132
        for i in range( hats ):
133
            hat = joystick.get_hat( i )
134
            textPrint.printt(screen, "Hat {} value: {}".format(i, str(hat)) )
135
        textPrint.unindent()
136
        
137
        textPrint.unindent()
138

  
139
    
140
    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
141
    
142
    # Go ahead and update the screen with what we've drawn.
143
    pygame.display.flip()
144

  
145
    sAngle = (-1.0*(steeringAngle - 1))/2.0
146
    sAngle = (sAngle*60)+102
147
    # sAngle = (sAngle*range of motion)+minimum value
148
    sAngle = int(sAngle)
149
    if sAngle > 180:
150
        sAngle = 180
151

  
152
    # send data through xbee
153
    currentpacket = 'A'+str(sAngle)+'B'+str(brake)+'C'
154
    print currentpacket
155
    ser.write('A')
156
    ser.write(str(sAngle))
157
    ser.write('B')
158
    ser.write(str(brake))
159
    ser.write('C')
160
    
161
    # Limit to 20 frames per second
162
    #clock.tick(20)
163
    clock.tick(8)
164

  
165

  
166
ser.close()
167
# Close the window and quit.
168
# If you forget this line, the program will 'hang'
169
# on exit if running from IDLE.
170
pygame.quit ()

Also available in: Unified diff