User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Fri Nov 30, 2012 4:35 am

Wendo wrote:Sorry, I don't understand. The Pi has 1 serial port in the GPIO header. What you connect to it is up to you
The Arduino **DEVICE** is using a serial port through USB. Like in : http://www.aonsquared.co.uk/the_dark_pi_rises

The ATMEGA on the Gertboard - I don't know where it is connected?

User avatar
Gert van Loo
Posts: 2482
Joined: Tue Aug 02, 2011 7:27 am
Contact: Website

Re: Question about Atmel chip

Fri Nov 30, 2012 10:28 am

The ATMEGA on the Gertboard - I don't know where it is connected?
The ATMEGA serial pins come out on two header pins. (Red oval in picture below)
Those two header pins are placed adjacent to GPIO 14 & 15 which are the serial port pins of the Raspberry-Pi.
(Yellow arrows in picture below). So all you need to do to make a serial connection between the Atemega and the Gertboard
is to place two jumpers on the pins (Like the MISO and MOSI pins in the purple rectangle).
Attachments
serial_jumpers.jpg
serial_jumpers.jpg (132.65 KiB) Viewed 4245 times

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Fri Nov 30, 2012 10:49 am

Gert van Loo wrote:
The ATMEGA on the Gertboard - I don't know where it is connected?
The ATMEGA serial pins come out on two header pins. (Red oval in picture below)
Those two header pins are placed adjacent to GPIO 14 & 15 which are the serial port pins of the Raspberry-Pi.
(Yellow arrows in picture below). So all you need to do to make a serial connection between the Atemega and the Gertboard
is to place two jumpers on the pins (Like the MISO and MOSI pins in the purple rectangle).
thank you Gert for this information but what is it called when these jumpers are connected to the RPi?

If I want to send it data, where is it located?

EDIT: I think the information I want is on pages 36/37 of the Gertboard manual... I will get back here tomorrow and tell you.

User avatar
Gert van Loo
Posts: 2482
Joined: Tue Aug 02, 2011 7:27 am
Contact: Website

Re: Question about Atmel chip

Fri Nov 30, 2012 11:03 pm

thank you Gert for this information but what is it called when these jumpers are connected to the RPi?

If I want to send it data, where is it located?
Uuuuuhhhhh......... Its is called a UART. You can only connect a UART to another UART.
So the Atmega UART has to talk to the Pi UART.
- And the baudrate has to be the same.
- And you have to cross you TX and RX pins but that is already done on the Gertboard
as the Atmegea TX is placed adjacent to the Pi RX.
- And you have to be able to control the Pi UART yourself which means you have to tell the Pi OS
to NOT use it. There are lots of posts about how to get the UART on the PI working. I am not going to repeat that here.

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Sat Dec 01, 2012 5:15 am

Gert van Loo wrote:
thank you Gert for this information but what is it called when these jumpers are connected to the RPi?

If I want to send it data, where is it located?
Uuuuuhhhhh......... Its is called a UART. You can only connect a UART to another UART.
So the Atmega UART has to talk to the Pi UART.
- And the baudrate has to be the same.
- And you have to cross you TX and RX pins but that is already done on the Gertboard
as the Atmegea TX is placed adjacent to the Pi RX.
- And you have to be able to control the Pi UART yourself which means you have to tell the Pi OS
to NOT use it. There are lots of posts about how to get the UART on the PI working. I am not going to repeat that here.
How do I write to UART?
...You can use menus to configure minicom (by typing minicom –s). Alternatively, included with the
Gertboard software is a file minirc.ama0 with the settings you need to read from the GPIO UART
pins at 9600 baud. ...

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Sat Dec 01, 2012 10:39 am

I have set up my Arduino Device (not the Gertboard ATMEGA) and run a few tests:

1. dmesg output (for UART):

Code: Select all

[    0.075782] hw-breakpoint: maximum watchpoint size is 4 bytes.
[    0.075820] mailbox: Broadcom VideoCore Mailbox driver
[    0.075926] bcm2708_vcio: mailbox at f200b880
[    0.076032] bcm_power: Broadcom power driver
[    0.076070] bcm_power_open() -> 0
[    0.076096] bcm_power_request(0, 8)
[    0.576774] bcm_mailbox_read -> 00000080, 0
[    0.576815] bcm_power_request -> 0
[    0.576840] Serial: AMBA PL011 UART driver
[    0.576997] dev:f1: ttyAMA0 at MMIO 0x20201000 (irq = 83) is a PL011 rev3
This seems to tell me that the device is registered with name 'ttyAMA0'.

2. Run TCP Server:

Code: Select all

from time import sleep
import sys
import socket
while True:
    s = socket.socket()         # Create a socket object
    host = '10.0.0.1'          # Get local machine name
    port = 9999                 # Reserve a port for your service.


    import serial
    DEVICE = '/dev/ttyACM0' # the arduino serial interface (use dmesg when connecting)
    ##DEVICE = 'COM12'
    BAUD = 9600
    ser = serial.Serial(DEVICE, BAUD)
    try: 
        print "Server started on", str(host) + ":" + str(port)
        print 'Waiting for clients...'
     
        s.bind((host, port))        # Bind to the port
        s.listen(5)                 # Now wait for client connection.
        c, addr = s.accept()     # Establish connection with client.
        print 'Got connection from', addr
        while True:
            msg = c.recv(3) # get 3 bytes from the TCP connection
            ser.write(msg)  # write the 3 bytes to the serial interface
            #print msg
            if msg == "":
                c.shutdown(socket.SHUT_RDWR)
                c.close()
                print "Lost connection with"+ str(addr) +"! Restarting server..."
                sleep(2)
		break
    except KeyboardInterrupt:
        print "[ALERT]  Closing shell...  [ALERT]"
        c.shutdown(socket.SHUT_RDWR)
        c.close()
        ser.close()
        sys.exit("Application forcibly halted!")
All good so far...normally if a device is not connected the TCP server would spit out errors.

3. Start up TCP Client and connect to server...(this has had no problems forever and does not affect operation of Raspberry Pi.
- this should send the the raspberry pi - which it does [PASS]

4. Check if data is going to Arduino...
a. Is the light flashing for serial transmission?
"NO!"
b. Are the motors moving?
"NO!"
c. Is there any activity?
"NO!"

Something is going wrong here... I am not sure, but I think it is the ser.write() to the Arduino via the UART port.

I tried crossing the wires, checking the connections (five times) and then a different set-up.

Nothing seems to work.

Can someone please assist me in what could be one of three problems:
- Arduino wiring is wrong
- The UART has not been configured for use ( if so how do I do it? - n00by instructions please)
- The Sketch for the ATMEGA (on the Gertboard) has not configured the default 'Clock speed' and 'timer' speeds.

User avatar
panik
Posts: 369
Joined: Fri Sep 23, 2011 12:29 pm
Location: Netherlands

Re: Question about Atmel chip

Sat Dec 01, 2012 11:49 am

wallarug wrote:Can someone please assist me in what could be one of three problems:
- Arduino wiring is wrong
- The UART has not been configured for use ( if so how do I do it? - n00by instructions please)
- The Sketch for the ATMEGA (on the Gertboard) has not configured the default 'Clock speed' and 'timer' speeds.
- Connect Pi TX to Atmel RX, and Pi RX to Atmel TX. See Gert's picture and the Gertboard user manual.
- Freeing up the serial port is documented on a lot of places. For example here: http://raspberrypihobbyist.blogspot.nl/ ... -port.html
- Your only concern is 'baudrate'.

I don't understand your python socket code. UART has nothing to do with TCP. Try to find a simple serial python example somewhere. Or just see if you receive the Arduino Serial.println() commands in minicom. Go from there. Start with a default example sketch without messing with the Timers.

Google result for 'python serial': http://arduino.cc/playground/Interfacing/Python

User avatar
panik
Posts: 369
Joined: Fri Sep 23, 2011 12:29 pm
Location: Netherlands

Re: Question about Atmel chip

Sat Dec 01, 2012 12:55 pm

Too late to edit my post.
The first sentence in your post contradicts with the last part. Are you using a standard Arduino connected by USB, or the ATmega on the Gertboard? What do you mean by 'The Sketch for the ATMEGA (on the Gertboard)'?

When using a standard Arduino, you either use serial over USB (no need to 'configure for use'), or use the TX and RX pins, with appropriate voltage level conversion (3.3 vs 5 volt).

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Sat Dec 01, 2012 11:32 pm

panik wrote:Too late to edit my post.
The first sentence in your post contradicts with the last part. Are you using a standard Arduino connected by USB, or the ATmega on the Gertboard? What do you mean by 'The Sketch for the ATMEGA (on the Gertboard)'?

When using a standard Arduino, you either use serial over USB (no need to 'configure for use'), or use the TX and RX pins, with appropriate voltage level conversion (3.3 vs 5 volt).
Set-ups:
1. Gertboard ATMEGA:
a. UART connected using jumpers between the two appropriate pins on the Gertboard
b. Same Sketch as the Arduino (I will post below...I had not realised I had not posted yet)
c. Write data using the SPI interface (and Adruino IDE on RPi)
d. PYTHON SCRIPT: ... is a TCP server that receives data from a client and then relays that data to the Adruino or ATMEGA

2. Arduino connected through USB:
a. USB connected to RPi USB port
b. Upload Sketch through the IDE program
c. PYTHON SCRIPT: ... is a TCP server that recieves data from a client and then relays that data to the Adruino Through USB.

3. Arduino connected via UART:
a. UART connected to Ardruino RX/TX pins
b. Upload Sketch through Windows PC and IDE
c. PYTHON SCRIPT: ... is a TCP server that receives data from a client and then relays that data to the Adruino Through UART.


Only number two works at the moment (Arduino through USB).

I do not need to receive anything from the Arduino and that is why I do not use minicom. I ONLY WRITE ONE WAY - RPi TO ARDUINO / ATMEGA.

Arduino / ATMEGA sketch:

Code: Select all

/*
 * Robot Motor Controller script with PWM speed control
 */
//---------------------- Motors
int motorLHigh = 4;
int motorLLow = 2;
int motorLPWM = 9;
int motorRHigh = 7;
int motorRLow = 8;
int motorRPWM = 10;
int ledPin = 13;
int Byte1 = 0;  //for incoming serial data
int Byte2 = 0;  //for incoming serial data
int Byte3 = 0;  //for incoming serial data
int motor_a = 0;
int motor_b = 0;
int dir_y = 0;


void setup() {
Serial.begin(9600);  // opens serial port, sets data rate at 9600bps
//TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00); 
//TCCR0B = _BV(CS00);
pinMode(motorLPWM, OUTPUT);
pinMode(motorRPWM, OUTPUT);
pinMode(motorRHigh, OUTPUT);
pinMode(motorRLow, OUTPUT);
pinMode(motorLHigh, OUTPUT);
pinMode(motorLLow, OUTPUT);
pinMode(ledPin, OUTPUT);
}


void loop() {
digitalWrite(ledPin, HIGH);

if(Serial.available()==3)
{
  Byte1 = Serial.read(); // Incoming data from Serial connection
  motor_a = int(Byte1);
  Byte2 = Serial.read(); // Incoming data from Serial connection
  motor_b = int(Byte2);
  Byte3 = Serial.read(); // Incoming data from Serial connection
  dir_y = int(Byte3);
  
  if (dir_y == 2) { //Motor Backwards
  digitalWrite(motorLLow, HIGH);
  digitalWrite(motorLHigh, LOW);
  digitalWrite(motorRLow, HIGH);
  digitalWrite(motorRHigh, LOW);
  analogWrite(motorLPWM, motor_a);
  analogWrite(motorRPWM, motor_b);
  }
  else if (dir_y == 1) {  //Motor Forwards and Single motor Turning
  digitalWrite(motorLLow, LOW);
  digitalWrite(motorLHigh, HIGH);
  digitalWrite(motorRLow, LOW);
  digitalWrite(motorRHigh, HIGH);
  analogWrite(motorLPWM, motor_a);
  analogWrite(motorRPWM, motor_b);
  }
  }
  
}
TCP Server:

Code: Select all

from time import sleep
import sys
import socket
while True:
    s = socket.socket()         # Create a socket object
    host = '10.0.0.1'          # Get local machine name
    port = 9999                 # Reserve a port for your service.


    [b]import serial
    DEVICE = '/dev/ttyACM0' # the arduino serial interface (use dmesg when connecting)
    ##DEVICE = 'COM12'
    BAUD = 9600
    ser = serial.Serial(DEVICE, BAUD)[/b]
    try: 
        print "Server started on", str(host) + ":" + str(port)
        print 'Waiting for clients...'
     
        s.bind((host, port))        # Bind to the port
        s.listen(5)                 # Now wait for client connection.
        c, addr = s.accept()     # Establish connection with client.
        print 'Got connection from', addr
        while True:
            [b]msg = c.recv(3) # get 3 bytes from the TCP connection
            ser.write(msg)  # write the 3 bytes to the serial interface[/b]
            #print msg
            if msg == "":
                c.shutdown(socket.SHUT_RDWR)
                c.close()
                print "Lost connection with"+ str(addr) +"! Restarting server..."
                sleep(2)
		break
    except KeyboardInterrupt:
        print "[ALERT]  Closing shell...  [ALERT]"
        c.shutdown(socket.SHUT_RDWR)
        c.close()
        ser.close()
        sys.exit("Application forcibly halted!")

This bits in bold are important to the serial interface.

TCP Client / Control Script:

Code: Select all

print "*************************"        ###########################################
print "*Module version Beta 1.6*"        #     #####     ##    ##      #####       #
print "*Standby for imports....*"        #   ####      #    ##    #     ####  ###  #
print "*************************"        #   ##       ###  ####  ###    ####  #### #
print "                         "        #   ###      ###  ####  ###    ####  ###  #
import pygame                            #     #####  ###  ####  ###    ####       #
import socket                            ###########################################
import sys                               #Revision number: 2                       # 
import os                                ###########################################
from time import gmtime, strftime, sleep
from pygame.locals import *

##########################################
# All Variables used in script being     #
#  set to zero so that it is recognised  #
#   by the except statements.            #
##########################################

init = 0            #
question_one = 0
question_two = 0    #
question_three = 0
network_one = 0
network_two = 0
network_value = 0
motor_a =0
motor_b = 0
a = 0               #
b = 0               #
x = 0
y = 0
manual_input = 0
debug_value = 0     #
i = 0
motor_a_prev = 0    #
motor_b_prev = 0    #
dir_y_prev = 0      #
dir_y = 0
connection = 0



############################
# Declearing sendcommmand. #
############################

def sendcommand(motor_a,motor_b,dir_y):
    byte1 = chr(int(motor_a))
    byte2 = chr(int(motor_b))
    byte3 = chr(int(dir_y))
    sock.send(byte1+byte2+byte3)

##################
#Asset Detection!#
##################

if os.path.exists("C:\Users\Tom"):
    commander_name = "Ingram"
elif os.path.exists("C:\Users\Cian"):
    commander_name = "Byrne"
else:
    commander_name = ""


time = strftime("%H:%M:%S")
os_type = os.name
if os_type == "nt":
    os_type = "Windows"
    if os.path.exists("C:\Windows\DesktopTileResources"):
        os_name = "8"
        kernel_version = str("6.2")
    else:
        os_name = "7"
        kernel_version = str("6.1")

else:
    os_type = "OSX"
    os_name = "10.8"
    kernel_version = str("XNU") #Will make searchable if command post switches so Linux/OSX


print ("Welcome back Commander " + commander_name)
print ("You are running on " + os_type + " " + os_name + " with kernel version " + kernel_version)
print " "
print ("The current time is " + time)
print " "


##########################################
# Manual functionality specification     #
# Ingram & Byrne's idea                  #
##########################################

try:
    question_one = raw_input("Would you like to use Default Settings? (y/n): ")

    if question_one == "y":
        question_two = "y"
        question_three = "y"
        network_value = "y"
        i = "pos"
    if question_one != "y":
        network_value = "n"
        if question_one != "n":
            while question_one != "y" and question_one != "n":
                print "Please enter a valid value"
                question_one = raw_input("Would you like to start both the TCP client and Joystick? (y/n): ")
                if question_one == "y":
                    question_two = "y"
                    question_three = "y"
                elif question_one == "n":
                    break
        question_two = raw_input("Would you like to enable TCP client for this sesson? (y/n): ")

        while question_two != "y" and question_two != "n":
            if question_two == "y" or question_two == "n":
                break
            print "Please enter a valid value"
            question_two = raw_input("Would you like to enable TCP client for this sesson? (y/n): ")

        question_three = raw_input("Would you like to enable the Joystick Controller? (y/n): ")
        while question_three != "y" and question_three != "n":
            if question_three == "y" or question_three == "n":
                break
            print "Please enter a valid value"
            question_three = raw_input("Would you like to enable the Joystick Controller? (y/n): ")


    ############################
    #Joystick Detection Script!#
    ############################

    if question_three == "y":
        pygame.init()
        joycount = pygame.joystick.get_count()

        if joycount == 0:
            print "                                                                      "
            print "**********************************************************************"
            print "* [ WARNING ]           No joystick detected!            [ WARNING ] *"
            print "*                                                                    *"
            print "*                   Restart module with joystick!                    *"
            print "*                                                                    *"
            print "* [ WARNING ]           Module halt in TIME-5            [ WARNING ] *"
            print "**********************************************************************"
            sleep(5)
            sys.exit("No joystick found!")
        else:
            print " "
            print "[ SUCCESS ] Joystick Detected! [ SUCCESS ] "    
        j = pygame.joystick.Joystick(0)
        j.init()
        print " "
        print " ************************************************ " 
        print ' * Initialized Joystick : %s' % j.get_name() + " * "
        print " ************************************************ "
    else:
        print "                                                                          "
        print "**************************************************************************"
        print "*                                                                        *"
        print "* [ WARNING ]  Manual input method will now be activated!  [ WARNING ]   *" 
        print "*                                                                        *"
        print "**************************************************************************"
        manual_input = 1



    #########################
    # TCP client is  below. #
    #########################

    ######################################
    # Check for TCP connection settings. #
    ######################################

    while question_two == "y":
        if network_value == "n":
            print " "
            print " "
            network_one = raw_input("Would you like to use a pre-set IP address? ('n' or 'adhoc'/'local') : ")
            while network_one != "n" and network_one != "adhoc" and network_one != "local":
                print "Please enter a valid value"
                network_one = raw_input("Would you like to use a pre-set IP address? ('n' or 'adhoc'/'local') : ")
                if network_one == "n" or network_one == "adhoc" or network_one == "local":
                     break
            if network_one == "adhoc":
                HOST, PORT = "10.0.0.1", 9999
            elif network_one == "local":
                HOST, PORT = 'localhost', 9999
            elif network_one == "n":
                HOST = raw_input("Enter the Desired IP Address. (FORMAT: e.g. 192.168.12.1): ")
                PORT = input("Enter the Desired Port number. (FORMAT: e.g. 9999): ")
        elif network_value == "y":
            HOST, PORT = "192.168.12.24", 9999

        connection = 0
        connection_attempt = 1
        con_attempted = 0
        while connection == 0:
            print " "
            print "[ ALERT ]  Stand by for TCP connection on " + str(HOST) + ":" + str(PORT)+ "!  Attempt: " + str(connection_attempt) + "  [ ALERT ]"
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                sock.connect((HOST, PORT)) #'''Added in a try command for unsucessful TCP connection'''
                sockname = socket.gethostname()
                print " "
                print "[ ALERT ]   Connected to " +str(sockname)+" @ "+ str(HOST) + ":" + str(PORT)+"  [ ALERT ]   "
                connection = 1
            
            except:
                #print " "
                print "[ ALERT ]  Unable to connect to " + HOST +", please check your connection!   [ ALERT ]"
                connection_attempt = connection_attempt + 1
                sleep(5)
                if connection_attempt > 2 and con_attempted == 0:
                    print " "
                    con_attempt = raw_input("Are you sure " + str(HOST) + ":" + str(PORT) + " is your desired address? (y/n)")
                    con_attempted = 1
                    while con_attempt != "y" and con_attempt != "n":
                        print "Please input a valid value!"
                        con_attempt = raw_input("Are you sure " + str(HOST) + ":" + str(PORT) + " is your desired address? (y/n)")
                        
                    if con_attempt == "n":
                        HOST = raw_input("Enter the Desired IP Address. (FORMAT: e.g. '192.168.12.1'): ")
                        PORT = input("Enter the Desired Port number. (FORMAT: e.g. 9999): ")
                        
                    
                if connection_attempt > 5:
                    #print " "
                    print "[ WARNING ]  Connection attempts have failed, the script will now exit!  [ WARNING ] "
                    sleep(3)
                    #print " "
                    sys.exit("Connection Failed!")
        break #Discovered flaw, once completed that section would continue the while loop!

    else:
        print " "
        print "[ WARNING ]  No TCP Client this sesson!  [ WARNING ] "
except KeyboardInterrupt:
        if question_two == "y":
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
        sys.exit("Closing Application...")


#########################################
# The mode that you want to enter which #
#  can be one of the following:         #
#########################################

try:
    if question_one != "y":
        if str(question_three) == "y":
            print " "
            i = raw_input("What do you want to detect? (button/pos/all): ")
        elif str(question_three) == "n":
            print " "
            debug_value = raw_input("Do you want to enter debug mode? (y/n): ")
        else:
            print "Enter a correct value next time!"
            sys.exit("Value Error!")
except KeyboardInterrupt:
        if question_two == "y":
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
        sys.exit("Closing Application...")


######################################
#                                    #
#       D E B U G   M O D E          #
#                                    #
#      Advanced out of ALPHA         #
######################################
try:
    if debug_value == "n":
        print " Loading WASD Full Speed Control..."
        pygame.init()
        screen = pygame.display.set_mode((64, 64))
        pygame.display.set_caption('WASD Control of CMD-ROBOT')
        pygame.mouse.set_visible(0)
        done = False
        while not done:
           for event in pygame.event.get():
                if (event.type == KEYUP):
                    if (event.key == K_a):
                        print "Moving Left!"
                        motor_b = 255
                        motor_a = 0
                        dir_y = 1
                    elif (event.key == K_s):
                        print "Moving Backwards!"
                        dir_y = 2
                        motor_a = 255
                        motor_b = 255                   
                    elif (event.key == K_d):
                        print "Moving Right!"
                        dir_y = 1
                        motor_b = 0
                        motor_a = 255
                    elif (event.key == K_w):
                        print "Moving Forwards!"
                        dir_y = 1
                        motor_a = 255
                        motor_b = 255
                    elif (event.key == K_ESCAPE):
                        done = True
                    else:
                        motor_a = 0
                        motor_b = 0                
                    if question_two == "y":
                        sendcommand(motor_a,motor_b,dir_y)
                    print (motor_a,motor_b)
except KeyboardInterrupt:
        if question_two == "y":
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
        sys.exit("Closing Application...")

try:    
    if debug_value == "y":
        from random import *
        print " "
        print "Welcome to Debug mode for CMD robots...Use with caution!!! "
        print "Loading... "
        sleep(3)
        print " "
        print "[ ALERT ]  Script Loaded Successfully!  [ ALERT ]  "
        print " "
        print " ******************* "
        print " * BEGIN DEBUGGING * "
        print " ******************* "
        while True:
            print " "
            motor_a = input("LEFT MOTOR: Enter value between -255 and 255: ")
            motor_b = input("RIGHT MOTOR: Enter value between -255 and 255: ")
            if motor_a < 0 and motor_a > -256 or motor_b < 0 and motor_b > -256:
                dir_y = 2
                motor_a = 255 - abs(motor_a)
                motor_a = abs(motor_a)
                motor_b = 255 - abs(motor_b)
                motor_b = abs(motor_b)
                print "Going Backwards!"
                if question_two == "y":
                    sendcommand(motor_a,motor_b,dir_y)
                    print "Sent to server!"
            elif motor_a >= 0 and motor_a < 256 or motor_b >= 0 and motor_b < 256:               
                dir_y = 1
                motor_a = abs(motor_a)
                motor_b = abs(motor_b)
                print "Going Forwards!"
                if question_two == "y":
                    sendcommand(motor_a,motor_b,dir_y)
                    print "Sent to server!"
            elif motor_a == "" or motor_b == "": # Will work once we change input to raw_input otherwise we get an error!
                motor_a = 0
                motor_b = 0
                dir_y = 1
                if question_two == "y":
                    sendcommand(motor_a,motor_b,dir_y)
                    print "Reset values command sent to server!"
                
                

            else:
                print "Number not in range, value not sent to server"
                print "Not sent to TCP Server!"
            print (motor_a, motor_b)
except KeyboardInterrupt:
        if question_two == "y":
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
        sys.exit("Closing Application...")





###########################################################

try:
    while i == "pos":
        if question_two == "y":
            sockname = str(sockname)
        else:
            sockname = "nothing"

        if init == 0:
            print " "
            print "[ WARNING ]  Initiating Control of " + str(sockname) + " in...  [ WARNING ] "
            print " "
            sleep(3)
            print " "
            print " ***** "
            print " * 3 * "
            print " ***** "
            print " "
            sleep(1)
            print " ***** "
            print " * 2 * "
            print " ***** "
            print " "
            sleep(1)
            print " ***** "
            print " * 1 * "
            print " ***** "
            print " "
            sleep(1)
            print " ***** "
            print " * 0 * "
            print " ***** "
            sleep(1)
            print " "
            print " ************************************* "
            print " "
            print " * Initiated Control of " + str(sockname) + "!"
            print " "
            print " ************************************* "
            init = init + 1
            sleep (1.5)


        pygame.event.pump()
        y = j.get_axis(1)
        x = j.get_axis(0)   
        z = j.get_axis(2)   
        z = round(z,1)
        #print(x,y,z)
       
        if y < 0:               ############################
            y = abs(y)          #New Y-axes inversion code!#
        elif y > 0:             ############################
            y = y*-1
            
    #############################################
    # Formulas for working out the speed of the #
    # motor in certain areas of the Joystick!   #
    #############################################

        f = 1
        sy = f*(y)
        sx = f*(x)
        

    #############################################
    ## Joystick Control Registry and Conversion!#
    #############################################

        if j.get_button(0):
            if x == 0:
                a = abs(sy)
                b = abs(sy)
            elif y > 0:
                if x > 0 and y <= x:
                    a = abs(x)
                    b = 0
                elif x > 0 and y > x:
                    a = abs(sy)
                    b = abs(sy) - abs(x)
                elif x < 0 and y <= -x:
                    b = abs(x)
                    a = 0
                elif x < 0 and y > -x:
                    b = abs(sy)
                    a = abs(sy) - abs(x)
            
            elif y == 0 and x != 0:
                if x < 0:
                    a = 0
                    b = abs(sx)
                elif x > 0:
                    a = abs(sx)
                    b = 0
            elif y < 0:
                if x > 0 and y >= -x:
                    a = abs(x)
                    b = 0
                elif x > 0 and y < -x:
                    a = abs(sy)
                    b = abs(sy) - abs(x)
                elif x < 0 and y >= x:
                    a = 0
                    b = abs(x)
                elif x < 0 and y < x:
                    a = abs(sy) - abs(x)
                    b = abs(sy)
        else:
            a = 0
            b = 0
                   

    ######################################
    ## PWM convertion for AnalogueWrite()#
    ######################################

        PWM = 255
        a = PWM*a
        a = round(a, 1)
        b = PWM*b
        b = round(b, 1)

    ###################################
    # Arduino Varibles Decleared Here!#
    ###################################

        motor_a = a
        motor_b = b

    ####################################
    # NEW: Single PWM Channel LOW fix! #
    ####################################

        if y < 0:           
            y = 2                # Backwards
        else:               
            y = 1                # Forewards
        dir_y = y


    ##########################################
    # Sends data ONLY when data is different!#
    ##########################################
        if question_two == "y":
            if motor_a != motor_a_prev:
                sendcommand(motor_a,motor_b,dir_y)
            elif motor_b != motor_b_prev:
                sendcommand(motor_a,motor_b,dir_y)
            elif dir_y != dir_y_prev:
                sendcommand(motor_a,motor_b,dir_y)


            motor_a_prev = motor_a
            motor_b_prev = motor_b
            dir_y_prev = dir_y
    

####################################
# Printing Output - Only used in   #
# development of Joystick Control. #
####################################

        print (int(a),int(b))
        
except KeyboardInterrupt:
        if question_two == "y":
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
        sys.exit("Closing Application...")

#####################################################
##@@@@@@@@@@@@@@@@@@@@@@ END @@@@@@@@@@@@@@@@@@@@@ ##
#####################################################

    
##################
#CUSTOM FUNCTIONS#  Currently unstable, to make usable in coming updates
##################


while i == "button":
    pygame.event.pump()
    if j.get_button(1):
        print "Left"
    if j.get_button(0):
        print "Kill"
    if j.get_button(2):
        print "Right"

###################################################

while i == "speed":
    print"currently in progress"
    x = 0.4
    y = 0.5
    f = 100
    sy = f*abs(y)
    print sy


###################################################


while i == "all":
    pygame.event.pump()
    y = j.get_axis(1)
    y = round(y,2)
    x = j.get_axis(0)
    x = round(x,2)
    z = j.get_axis(2)
    z = round(z,1)
    if j.get_button(0):
        b0 = " Kill"
    else:
        b0 = ""
    if j.get_button(1):
        b1 = " Left"
    else:
        b1 = ""
    if j.get_button(2):
        b2 = " Right"
    else:
        b2 = ""
    print(str(x) + "," + str(y) + "," + str(z) + b0 + b1 + b2)

'''CMD Official Comment ART

#####################################
###     #####    ##    #####      ###
##  ########   #    #   ####  ###  ##
##  ########  ###  ###  ####  #### ##
##  ########  ###  ###  ####  ###  ##
###     ####  ###  ###  ####      ###
#####################################
'''
endstatement = raw_input("You have reached the end of the script! (exit/ *) ")
if endstatement == "exit":
    sys.exit("End of script!")
Most of this script is not important / relevant to the issue I have expressed here.

How do I get the TCP Server (above) to send the data onto the ATMEGA (either the Gertboard or the Arduino) through the UART interface on the Raspberry Pi's GPIO header?

User avatar
panik
Posts: 369
Joined: Fri Sep 23, 2011 12:29 pm
Location: Netherlands

Re: Question about Atmel chip

Sun Dec 02, 2012 12:59 am

Start with uploading a simple Arduino sketch to the Gertboard AVR that echoes sensordata or whatever to the Arduino IDE's built-in Serial Monitor. Even a simple 'Hello!' in a loop with a small delay. Does that work? Even if you don't need to read data from the AVR. Just try if it works.

If it doesn't; have you freed up the serial port on the Raspberry Pi? And rebooted after that?

If it does, make a simple python prototype, and upload a simple Arduino sketch on the Gertboard to communicate back and forth (See the Arduino-python link before). When you have that working, add the code snippets wherever you want.

Wendo
Posts: 142
Joined: Sun Jun 10, 2012 8:27 pm

Re: Question about Atmel chip

Sun Dec 02, 2012 3:32 am

If you're uploading to the gertboard ATmega chip via a windows PC and a programmer, you need to tell the Windows Arduino IDE that your ATmega is running at 12Mhz rather than the standard for Arduino of 16Mhz.

Otherwise the baud rate will be wrong on the programmed chip.

You can do that by adding the following to /hardware/arduino/boards.txt on the windows PC

Code: Select all

gert328.name=Gertboard with ATmega328 

gert328.upload.using=avrispmkii
gert328.upload.protocol=stk500v2
gert328.upload.maximum_size=32768
gert328.upload.speed=57600
gert328.upload.disable_flushing=true

gert328.bootloader.low_fuses=0xE7
gert328.bootloader.high_fuses=0xDA
gert328.bootloader.extended_fuses=0x07
gert328.bootloader.path=atmega
gert328.bootloader.file=ATmegaBOOT_168_gert328.hex
gert328.bootloader.unlock_bits=0x3F
gert328.bootloader.lock_bits=0x0F

gert328.build.mcu=atmega328p
gert328.build.f_cpu=12000000L
gert328.build.core=arduino
gert328.build.variant=standard

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Sun Dec 02, 2012 5:15 am

Wendo wrote:If you're uploading to the gertboard ATmega chip via a windows PC and a programmer, you need to tell the Windows Arduino IDE that your ATmega is running at 12Mhz rather than the standard for Arduino of 16Mhz.
NO! That was for the Arduino ATMEGA. The Gertboard one is on the Raspberry Pi and is uploaded via the SPI interface:
1. ... c. Write data using the SPI interface (and Adruino IDE on RPi)

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Sun Dec 02, 2012 5:17 am

panik wrote:Start with uploading a simple Arduino sketch to the Gertboard AVR that echoes sensordata or whatever to the Arduino IDE's built-in Serial Monitor. Even a simple 'Hello!' in a loop with a small delay. Does that work? Even if you don't need to read data from the AVR. Just try if it works.

If it doesn't; have you freed up the serial port on the Raspberry Pi? And rebooted after that?

If it does, make a simple python prototype, and upload a simple Arduino sketch on the Gertboard to communicate back and forth (See the Arduino-python link before). When you have that working, add the code snippets wherever you want.
I can upload to the GertB ATMEGA with zero problems!

It is the act of sending the serial port data (after the sketch has been uploaded) that causes problems.

User avatar
panik
Posts: 369
Joined: Fri Sep 23, 2011 12:29 pm
Location: Netherlands

Re: Question about Atmel chip

Sun Dec 02, 2012 12:42 pm

wallarug wrote:I can upload to the GertB ATMEGA with zero problems!

It is the act of sending the serial port data (after the sketch has been uploaded) that causes problems.
We understood. That part was clear.
panik wrote:Start with uploading a simple Arduino sketch to the Gertboard AVR that echoes sensordata or whatever to the Arduino IDE's built-in Serial Monitor. Even a simple 'Hello!' in a loop with a small delay. Does that work? Even if you don't need to read data from the AVR. Just try if it works.

If it doesn't; have you freed up the serial port on the Raspberry Pi? And rebooted after that?
So... does it work? Freed up the serial port yet?

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Sun Dec 02, 2012 9:56 pm

panik wrote:
wallarug wrote:I can upload to the GertB ATMEGA with zero problems!

It is the act of sending the serial port data (after the sketch has been uploaded) that causes problems.
We understood. That part was clear.
panik wrote:Start with uploading a simple Arduino sketch to the Gertboard AVR that echoes sensordata or whatever to the Arduino IDE's built-in Serial Monitor. Even a simple 'Hello!' in a loop with a small delay. Does that work? Even if you don't need to read data from the AVR. Just try if it works.

If it doesn't; have you freed up the serial port on the Raspberry Pi? And rebooted after that?
So... does it work? Freed up the serial port yet?
I haven't got around to it yet.

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Mon Dec 17, 2012 7:27 am

Ok. I'm back! :D

We have success. The serial port is open and controllable through arduino on the Gertboard.

Back to an earlier question of mine:

1. How do I 'set' the 'bits' that store the information about the timers and clock speeds?
NOTES: Gert said in an earlier post:
by Gert van Loo » Sat Oct 27, 2012 4:59 pm
wallarug wrote:
I also have a question about the ATMEGA chip on the board.

Can I use the same sketch that I created for my Arduino Uno and upload it to the Gertboard ATMEGA chip?

I am not using any delay() commands so this should not effect the operation. Also, what are the default timer speeds as well on the ~12MHz @ 3v3 version of the chip?

Yes your image will work. But as you yourself noticed the X-tal is 12 MHz not 16 so all your timer values will be off.
As to the default timer speed:There is no default timer speed. Default the timers are off until your program sets them up.
...that the timers on the ATMEGA are not set by default... Please don't point me to: ... I have already read these and they have not helped with this problem.

2. How do I wire my nice new motor shield to the Gertboard?
NOTES: It says it will accept 3v3 voltages and I have a sketch that works with it here on my Arduino Uno:

Code: Select all

/*
 * Robot Motor Controller script with PWM speed control
 */
//---------------------- Motors
int motorLHigh = 4;
int motorLLow = 2;
int motorLPWM = 9;
int motorRHigh = 7;
int motorRLow = 8;
int motorRPWM = 10;
int ledPin = 13;
int Byte1 = 0;  //for incoming serial data
int Byte2 = 0;  //for incoming serial data
int Byte3 = 0;  //for incoming serial data
int motor_a = 0;
int motor_b = 0;
int dir_y = 0;


void setup() {
Serial.begin(9600);  // opens serial port, sets data rate at 9600bps
//TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00); 
//TCCR0B = _BV(CS00);
pinMode(motorLPWM, OUTPUT);
pinMode(motorRPWM, OUTPUT);
pinMode(motorRHigh, OUTPUT);
pinMode(motorRLow, OUTPUT);
pinMode(motorLHigh, OUTPUT);
pinMode(motorLLow, OUTPUT);
pinMode(ledPin, OUTPUT);
}


void loop() {
digitalWrite(ledPin, HIGH);

if(Serial.available()==3)
{
  Byte1 = Serial.read(); // Incoming data from Serial connection
  motor_a = int(Byte1);
  Byte2 = Serial.read(); // Incoming data from Serial connection
  motor_b = int(Byte2);
  Byte3 = Serial.read(); // Incoming data from Serial connection
  dir_y = int(Byte3);
  Serial.write(Byte1); // I added this to test serial connection
  
  if (dir_y == 2) { //Motor Backwards
  digitalWrite(motorLLow, HIGH);
  digitalWrite(motorLHigh, LOW);
  digitalWrite(motorRLow, HIGH);
  digitalWrite(motorRHigh, LOW);
  analogWrite(motorLPWM, motor_a);
  analogWrite(motorRPWM, motor_b);
  }
  else if (dir_y == 1) {  //Motor Forwards and Single motor Turning
  digitalWrite(motorLLow, LOW);
  digitalWrite(motorLHigh, HIGH);
  digitalWrite(motorRLow, LOW);
  digitalWrite(motorRHigh, HIGH);
  analogWrite(motorLPWM, motor_a);
  analogWrite(motorRPWM, motor_b);
  }
  }
  
}
This is the link to it's information: http://www.pololu.com/docs/pdf/0J49/dua ... shield.pdf

I have tried just putting all the ATMEGAs connections from the gertboard into the shield where the Arduino would normally be but I had no luck.

I still have to try the separate header specifically for use without Arduino.


Gorden's post on: https://projects.drogon.net/raspberry-pi/gertboard/ is very useful with assistance from: http://codeandlife.com/2012/07/29/ardui ... unication/ ...which provides a nice arduino test script. I thank both of these sources greatly.

User avatar
wallarug
Posts: 460
Joined: Mon May 14, 2012 8:21 am
Location: Sydney, Australia

Re: Question about Atmel chip

Wed Dec 26, 2012 6:11 am

All working now... I just have to refine my software. Hardware = excellent.

The Gertboard ATMEGA is controlling the speed of the motors with the sketch that I posted above. I wired the shield as per this picture:
Image

Thanks for all the help provided by Gert, Gorden and panik. It has been great working with you.

:D :D :D

Happy Raspberry Pi-ing and Merry Christmas and a Happy New Year in 2013.

Return to “HATs and other add-ons”